-
Notifications
You must be signed in to change notification settings - Fork 4
/
parser.py
executable file
·3181 lines (2302 loc) · 107 KB
/
parser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import sys, re, types, os, glob, logging
import traceback
import logging
from uuid import uuid1
from lxml import etree
from Peach.Engine.dom import *
from Peach.Engine import dom
import Peach.Engine
from Peach.Mutators import *
from Peach.Engine.common import *
from Peach.Engine.incoming import DataCracker
from Peach.mutatestrategies import *
from Peach.config import getInstanceProvider
def PeachStr(s):
"""
Our implementation of str() which does not
convert None to 'None'.
"""
if s is None:
return None
return str(s)
class PeachResolver(etree.Resolver):
def resolve(self, url, id, context):
scheme, filename = url.split(":", 1)
# raise PeachException("URL Exception: scheme required")
# Add the files path to our sys.path
if scheme == 'file':
if os.path.isfile(filename):
newpath = os.path.abspath('.')
if newpath not in sys.path:
sys.path.append(newpath)
return self.resolve_file(open(filename), context)
for d in sys.path:
for new_fn in (os.path.join(d, filename), os.path.join(d, 'Peach/Engine', filename)):
if os.path.isfile(new_fn):
newpath = os.path.abspath(os.path.split(new_fn)[0])
if newpath not in sys.path:
sys.path.append(newpath)
return self.resolve_file(open(new_fn), context)
raise PeachException("Peach was unable to locate [%s]" % url)
return etree.Resolver.resolve(self, url, id, context)
class ParseTemplate(object):
"""
The Peach 2 XML -> Peach DOM parser. Uses lxml library.
Parser returns a top level context object that contains things like templates, namespaces, etc.
"""
dontCrack = False
def __init__(self, configs=None):
self._parser = etree.XMLParser(remove_comments=True)
self._parser.resolvers.add(PeachResolver())
if configs is None:
self._configs = {}
else:
self._configs = configs
def _getBooleanAttribute(self, node, name):
"""If node has no attribute named |name| return True."""
v = self._getAttribute(node, name)
if not v:
return True
v = v.lower()
r = v in ('true', 'yes', '1')
if not r:
assert v in ('false', 'no', '0')
return r
def substituteConfigVariables(self, xmlString, final=False):
result = []
pos = 0
numVarsLeft = 0
numVarsFound = 0
unresolved = []
if not final:
logging.info("Analyzing XML for potential macros.")
for m in re.finditer(r"\$(\w+:?\w*)\$", xmlString):
result.append(xmlString[pos:m.start(0)])
varName = m.group(1)
handled = False
if varName in self._configs:
logging.debug('Setting "{}" to "{}"'.format(varName, self._configs[varName]))
result.append(self._configs[varName])
handled = True
elif ':' in varName:
# Instance provider
(instanceProviderName, identifier) = varName.split(':')
instanceProvider = getInstanceProvider(instanceProviderName)
try:
instance = str(instanceProvider.getInstanceById(identifier, self._configs))
logging.debug('Setting "{}" to "{}"'.format(varName, instance))
result.append(instance)
handled = True
except Exception:
# allow it to fail for now, probably need other macros to resolve this
pass
if not handled:
result.append(m.group(0))
unresolved.append(m.group(1))
numVarsLeft += 1
pos = m.end(0)
numVarsFound += 1
result.append(xmlString[pos:])
if not final:
logging.info("Found {} macros, {} resolved.".format(numVarsFound, numVarsFound - numVarsLeft))
elif unresolved:
for u in unresolved:
logging.warning("Unresolved macro: %s" % u)
return "".join(result)
def parse(self, uri):
"""
Parse a Peach XML file pointed to by uri.
"""
logging.info(highlight.info("Parsing %s" % uri))
doc = etree.parse(uri, parser=self._parser, base_url="http://phed.org").getroot()
if "_target" in self._configs:
target = etree.parse(self._configs["_target"], parser=self._parser, base_url="http://phed.org").getroot()
if split_ns(target.tag)[1] != 'Peach':
raise PeachException("First element in document must be Peach, not '%s'" % target.tag)
for child in target.iterchildren():
doc.append(child)
del self._configs["_target"]
# try early to find configuration macros
self.FindConfigurations(doc)
xmlString = etree.tostring(doc)
return self.parseString(xmlString, findConfigs=False)
def parseString(self, xml, findConfigs=True):
"""
Parse a string as Peach XML.
"""
xml = self.substituteConfigVariables(xml)
doc = etree.fromstring(xml, parser=self._parser, base_url="http://phed.org")
return self.HandleDocument(doc, findConfigs=findConfigs)
def GetClassesInModule(self, module):
"""
Return array of class names in module
"""
classes = []
for item in dir(module):
i = getattr(module, item)
if type(i) == type and item[0] != '_':
classes.append(item)
elif type(i) == types.MethodType and item[0] != '_':
classes.append(item)
elif type(i) == types.FunctionType and item[0] != '_':
classes.append(item)
elif repr(i).startswith("<class"):
classes.append(item)
return classes
def FindConfigurations(self, doc):
# FIRST check for a configuration section. If one exists, we need to parse it and then restart.
#print "Looking for Configuration element"
has_config = False
for child in doc.iterchildren():
child_tag = split_ns(child.tag)[1]
if child_tag != 'Configuration':
continue
#assert not has_config, "Multiple <Configuration> elements"
has_config = True
#print "Found Configuration element"
for child in child.iterchildren():
child_tag = split_ns(child.tag)[1]
assert child_tag == "Macro", "Unknown child in Configuration element: {}".format(child_tag)
name = child.get("name")
if name not in self._configs:
#print "\t%s = %s" % (name, child.get("value"))
self._configs[name] = child.get("value")
else:
#print "\t%s = %s [dropped]" % (name, child.get("value"))
pass
return has_config
def HandleDocument(self, doc, uri="", findConfigs=True):
if findConfigs and self.FindConfigurations(doc):
return self.parseString(etree.tostring(doc), findConfigs=False)
#self.StripComments(doc)
self.StripText(doc)
ePeach = doc
if split_ns(ePeach.tag)[1] != 'Peach':
raise PeachException("First element in document must be Peach, not '%s'" % ePeach.tag)
peach = dom.Peach()
peach.peachPitUri = uri
#peach.node = doc
self.context = peach
peach.mutators = None
#: List of nodes that need some parse love list of [xmlNode, parent]
self.unfinishedReferences = []
for i in ['templates', 'data', 'agents', 'namespaces', 'tests', 'runs']:
setattr(peach, i, ElementWithChildren())
# Peach attributes
for i in ['version', 'author', 'description']:
setattr(peach, i, self._getAttribute(ePeach, i))
# The good stuff -- We are going todo multiple passes here to increase the likely hood
# that things will turn out okay.
# Pass 1 -- Include, PythonPath, Defaults
for child in ePeach.iterchildren():
child_tag = split_ns(child.tag)[1]
if child_tag == 'Include':
# Include this file
nsName = self._getAttribute(child, 'ns')
nsSrc = self._getAttribute(child, 'src')
parser = ParseTemplate(self._configs)
ns = parser.parse(nsSrc)
ns.name = nsName + ':' + nsSrc
ns.nsName = nsName
ns.nsSrc = nsSrc
ns.elementType = 'namespace'
ns.toXml = new_instancemethod(dom.Namespace.toXml, ns)
nss = Namespace()
nss.ns = ns
nss.nsName = nsName
nss.nsSrc = nsSrc
nss.name = nsName + ":" + nsSrc
nss.parent = peach
ns.parent = nss
peach.append(nss)
peach.namespaces.append(ns)
setattr(peach.namespaces, nsName, ns)
elif child_tag == 'PythonPath':
# Add a search path
p = self.HandlePythonPath(child, peach)
peach.append(p)
sys.path.append(p.name)
elif child_tag == 'Defaults':
self.HandleDefaults(child, peach)
# one last check for unresolved macros
for child in ePeach.iterdescendants():
for k,v in list(child.items()):
child.set(k, self.substituteConfigVariables(v, final=True))
# Pass 2 -- Import
for child in ePeach.iterchildren():
child_tag = split_ns(child.tag)[1]
if child_tag == 'Import':
# Import module
if child.get('import') is None:
raise PeachException("Import element did not have import attribute!")
importStr = self._getAttribute(child, 'import')
if child.get('from') is not None:
fromStr = self._getAttribute(child, 'from')
if importStr == "*":
module = __import__(PeachStr(fromStr), globals(), locals(), [PeachStr(importStr)], -1)
try:
# If we are a module with other modules in us then we have an __all__
for item in module.__all__:
globals()["PeachXml_" + item] = getattr(module, item)
except:
# Else we just have some classes in us with no __all__
for item in self.GetClassesInModule(module):
globals()["PeachXml_" + item] = getattr(module, item)
else:
module = __import__(PeachStr(fromStr), globals(), locals(), [PeachStr(importStr)], -1)
for item in importStr.split(','):
item = item.strip()
globals()["PeachXml_" + item] = getattr(module, item)
else:
globals()["PeachXml_" + importStr] = __import__(PeachStr(importStr), globals(), locals(), [], -1)
Holder.globals = globals()
Holder.locals = locals()
i = Element()
i.elementType = 'import'
i.importStr = self._getAttribute(child, 'import')
i.fromStr = self._getAttribute(child, 'from')
peach.append(i)
# Pass 3 -- Template
for child in ePeach.iterchildren():
child_tag = split_ns(child.tag)[1]
if child_tag == "Python":
code = self._getAttribute(child, "code")
if code is not None:
exec(code)
elif child_tag == 'Analyzer':
self.HandleAnalyzerTopLevel(child, peach)
elif child_tag == 'DataModel' or child_tag == 'Template':
# do something
template = self.HandleTemplate(child, peach)
#template.node = child
peach.append(template)
peach.templates.append(template)
setattr(peach.templates, template.name, template)
# Pass 4 -- Data, Agent
for child in ePeach.iterchildren():
child_tag = split_ns(child.tag)[1]
if child_tag == 'Data':
# do data
data = self.HandleData(child, peach)
#data.node = child
peach.append(data)
peach.data.append(data)
setattr(peach.data, data.name, data)
elif child_tag == 'Agent':
agent = self.HandleAgent(child, None)
#agent.node = child
peach.append(agent)
peach.agents.append(agent)
setattr(peach.agents, agent.name, agent)
elif child_tag == 'StateModel' or child_tag == 'StateMachine':
stateMachine = self.HandleStateMachine(child, peach)
#stateMachine.node = child
peach.append(stateMachine)
elif child_tag == 'Mutators':
if self._getBooleanAttribute(child, "enabled"):
mutators = self.HandleMutators(child, peach)
peach.mutators = mutators
# Pass 5 -- Tests
for child in ePeach.iterchildren():
child_tag = split_ns(child.tag)[1]
if child_tag == 'Test':
tests = self.HandleTest(child, None)
#tests.node = child
peach.append(tests)
peach.tests.append(tests)
setattr(peach.tests, tests.name, tests)
elif child_tag == 'Run':
run = self.HandleRun(child, None)
#run.node = child
peach.append(run)
peach.runs.append(run)
setattr(peach.runs, run.name, run)
# Pass 6 -- Analyzers
# Simce analyzers can modify the DOM we need to make our list
# of objects we will look at first!
objs = []
for child in peach.getElementsByType(Blob):
if child.analyzer is not None and child.defaultValue is not None and child not in objs:
objs.append(child)
for child in peach.getElementsByType(String):
if child.analyzer is not None and child.defaultValue is not None and child not in objs:
objs.append(child)
for child in objs:
try:
analyzer = eval("%s()" % child.analyzer)
except:
analyzer = eval("PeachXml_" + "%s()" % child.analyzer)
analyzer.asDataElement(child, {}, child.defaultValue)
# We suck, so fix this up
peach._FixParents()
peach.verifyDomMap()
#peach.printDomMap()
return peach
def StripComments(self, node):
i = 0
while i < len(node):
if not etree.iselement(node[i]):
del node[i] # may not preserve text, don't care
else:
self.StripComments(node[i])
i += 1
def StripText(self, node):
node.text = node.tail = None
for desc in node.iterdescendants():
desc.text = desc.tail = None
def GetRef(self, str, parent=None, childAttr='templates'):
"""
Get the object indicated by ref. Currently the object must have
been defined prior to this point in the XML
"""
#print "GetRef(%s) -- Starting" % str
origStr = str
baseObj = self.context
hasNamespace = False
isTopName = True
found = False
# Parse out a namespace
if str.find(":") > -1:
ns, tmp = str.split(':')
str = tmp
#print "GetRef(%s): Found namepsace: %s" % (str, ns)
# Check for namespace
if hasattr(self.context.namespaces, ns):
baseObj = getattr(self.context.namespaces, ns)
else:
#print self
raise PeachException("Unable to locate namespace: " + origStr)
hasNamespace = True
for name in str.split('.'):
#print "GetRef(%s): Looking for part %s" % (str, name)
found = False
if not hasNamespace and isTopName and parent is not None:
# check parent, walk up from current parent to top
# level parent checking at each level.
while parent is not None and not found:
#print "GetRef(%s): Parent.name: %s" % (name, parent.name)
if hasattr(parent, 'name') and parent.name == name:
baseObj = parent
found = True
elif hasattr(parent, name):
baseObj = getattr(parent, name)
found = True
elif hasattr(parent.children, name):
baseObj = getattr(parent.children, name)
found = True
elif hasattr(parent, childAttr) and hasattr(getattr(parent, childAttr), name):
baseObj = getattr(getattr(parent, childAttr), name)
found = True
else:
parent = parent.parent
# check base obj
elif hasattr(baseObj, name):
baseObj = getattr(baseObj, name)
found = True
# check childAttr
elif hasattr(baseObj, childAttr):
obj = getattr(baseObj, childAttr)
if hasattr(obj, name):
baseObj = getattr(obj, name)
found = True
else:
raise PeachException("Could not resolve ref %s" % origStr)
# check childAttr
if found == False and hasattr(baseObj, childAttr):
obj = getattr(baseObj, childAttr)
if hasattr(obj, name):
baseObj = getattr(obj, name)
found = True
# check across namespaces if we can't find it in ours
if isTopName and found == False:
for child in baseObj:
if child.elementType != 'namespace':
continue
#print "GetRef(%s): CHecking namepsace: %s" % (str, child.name)
ret = self._SearchNamespaces(child, name, childAttr)
if ret:
#print "GetRef(%s) Found part %s in namespace" % (str, name)
baseObj = ret
found = True
isTopName = False
if not found:
raise PeachException("Unable to resolve reference: %s" % origStr)
return baseObj
def _SearchNamespaces(self, obj, name, attr):
"""
Used by GetRef to search across namespaces
"""
#print "_SearchNamespaces(%s, %s)" % (obj.name, name)
#print "dir(obj): ", dir(obj)
# Namespaces are stuffed under this variable
# if we have it we should be it :)
if hasattr(obj, 'ns'):
obj = obj.ns
if hasattr(obj, name):
return getattr(obj, name)
elif hasattr(obj, attr) and hasattr(getattr(obj, attr), name):
return getattr(getattr(obj, attr), name)
for child in obj:
if child.elementType != 'namespace':
continue
ret = self._SearchNamespaces(child, name, attr)
if ret is not None:
return ret
return None
def GetDataRef(self, str):
"""
Get the data object indicated by ref. Currently the object must
have been defined prior to this point in the XML.
"""
origStr = str
baseObj = self.context
# Parse out a namespace
if str.find(":") > -1:
ns, tmp = str.split(':')
str = tmp
#print "GetRef(): Found namepsace:",ns
# Check for namespace
if hasattr(self.context.namespaces, ns):
baseObj = getattr(self.context.namespaces, ns)
else:
raise PeachException("Unable to locate namespace")
for name in str.split('.'):
# check base obj
if hasattr(baseObj, name):
baseObj = getattr(baseObj, name)
# check templates
elif hasattr(baseObj, 'data') and hasattr(baseObj.data, name):
baseObj = getattr(baseObj.data, name)
else:
raise PeachException("Could not resolve ref '%s'" % origStr)
return baseObj
_regsHex = (
re.compile(r"^([,\s]*\\x([a-zA-Z0-9]{2})[,\s]*)"),
re.compile(r"^([,\s]*%([a-zA-Z0-9]{2})[,\s]*)"),
re.compile(r"^([,\s]*0x([a-zA-Z0-9]{2})[,\s]*)"),
re.compile(r"^([,\s]*x([a-zA-Z0-9]{2})[,\s]*)"),
re.compile(r"^([,\s]*([a-zA-Z0-9]{2})[,\s]*)")
)
def GetValueFromNode(self, node):
value = None
type = 'string'
if node.get('valueType') is not None:
type = self._getAttribute(node, 'valueType')
if not (type == 'literal' or type == 'hex'):
type = 'string'
if node.get('value') is not None:
value = self._getAttribute(node, 'value')
# Convert variouse forms of hex into a binary string
if type == 'hex':
if len(value) == 1:
value = "0" + value
ret = ''
valueLen = len(value) + 1
while valueLen > len(value):
valueLen = len(value)
for i in range(len(self._regsHex)):
match = self._regsHex[i].search(value)
if match is not None:
while match is not None:
ret += chr(int(match.group(2), 16))
value = self._regsHex[i].sub('', value)
match = self._regsHex[i].search(value)
break
return ret
elif type == 'literal':
return eval(value)
if value is not None and (type == 'string' or node.get('valueType') is None):
value = re.sub(r"([^\\])\\n", r"\1\n", value)
value = re.sub(r"([^\\])\\r", r"\1\r", value)
value = re.sub(r"([^\\])\\t", r"\1\t", value)
value = re.sub(r"([^\\])\\n", r"\1\n", value)
value = re.sub(r"([^\\])\\r", r"\1\r", value)
value = re.sub(r"([^\\])\\t", r"\1\t", value)
value = re.sub(r"^\\n", r"\n", value)
value = re.sub(r"^\\r", r"\r", value)
value = re.sub(r"^\\t", r"\t", value)
value = re.sub(r"\\\\", r"\\", value)
return value
def GetValueFromNodeString(self, node):
"""
This one is specific to <String> elements. We
want to preserve unicode characters.
"""
value = None
type = 'string'
if node.get('valueType') is not None:
type = self._getAttribute(node, 'valueType')
if not type in ['literal', 'hex', 'string']:
raise PeachException("Error: [%s] has invalid valueType attribute." % node.getFullname())
if node.get('value') is not None:
value = node.get('value')
# Convert variouse forms of hex into a binary string
if type == 'hex':
value = str(value)
if len(value) == 1:
value = "0" + value
ret = ''
valueLen = len(value) + 1
while valueLen > len(value):
valueLen = len(value)
for i in range(len(self._regsHex)):
match = self._regsHex[i].search(value)
if match is not None:
while match is not None:
ret += chr(int(match.group(2), 16))
value = self._regsHex[i].sub('', value)
match = self._regsHex[i].search(value)
break
return ret
elif type == 'literal':
value = eval(value)
if value is not None and type == 'string':
value = re.sub(r"([^\\])\\n", r"\1\n", value)
value = re.sub(r"([^\\])\\r", r"\1\r", value)
value = re.sub(r"([^\\])\\t", r"\1\t", value)
value = re.sub(r"([^\\])\\n", r"\1\n", value)
value = re.sub(r"([^\\])\\r", r"\1\r", value)
value = re.sub(r"([^\\])\\t", r"\1\t", value)
value = re.sub(r"^\\n", r"\n", value)
value = re.sub(r"^\\r", r"\r", value)
value = re.sub(r"^\\t", r"\t", value)
value = re.sub(r"\\\\", r"\\", value)
return value
def GetValueFromNodeNumber(self, node):
value = None
type = 'string'
if node.get('valueType') is not None:
type = self._getAttribute(node, 'valueType')
if not type in ['literal', 'hex', 'string']:
raise PeachException("Error: [%s] has invalid valueType attribute." % node.getFullname())
if node.get('value') is not None:
value = self._getAttribute(node, 'value')
# Convert variouse forms of hex into a binary string
if type == 'hex':
if len(value) == 1:
value = "0" + value
ret = ''
valueLen = len(value) + 1
while valueLen > len(value):
valueLen = len(value)
for i in range(len(self._regsHex)):
match = self._regsHex[i].search(value)
if match is not None:
while match is not None:
ret += match.group(2)
value = self._regsHex[i].sub('', value)
match = self._regsHex[i].search(value)
break
return int(ret, 16)
elif type == 'literal':
value = eval(value)
return value
# Handlers for Template ###################################################
def HandleTemplate(self, node, parent):
"""
Parse an element named Template. Can handle actual
Template elements and also reference Template elements.
e.g.:
<Template name="Xyz"> ... </Template>
or
<Template ref="Xyz" />
"""
template = None
# ref
if node.get('ref') is not None:
# We have a base template
obj = self.GetRef(self._getAttribute(node, 'ref'))
template = obj.copy(parent)
template.ref = self._getAttribute(node, 'ref')
template.parent = parent
else:
template = Template(self._getAttribute(node, 'name'))
template.ref = None
template.parent = parent
# name
if node.get('name') is not None:
template.name = self._getAttribute(node, 'name')
template.elementType = 'template'
# mutable
mutable = self._getAttribute(node, 'mutable')
if mutable is None or len(mutable) == 0:
template.isMutable = True
elif mutable.lower() == 'true':
template.isMutable = True
elif mutable.lower() == 'false':
template.isMutable = False
else:
raise PeachException(
"Attribute 'mutable' has unexpected value [%s], only 'true' and 'false' are supported." % mutable)
# pointer
pointer = self._getAttribute(node, 'pointer')
if pointer is None:
pass
elif pointer.lower() == 'true':
template.isPointer = True
elif pointer.lower() == 'false':
template.isPointer = False
else:
raise PeachException(
"Attribute 'pointer' has unexpected value [%s], only 'true' and 'false' are supported." % pointer)
# pointerDepth
if node.get("pointerDepth") is not None:
template.pointerDepth = self._getAttribute(node, 'pointerDepth')
# children
self.HandleDataContainerChildren(node, template)
# Switch any references to old name
if node.get('ref') is not None:
oldName = self._getAttribute(node, 'ref')
for relation in template._genRelationsInDataModelFromHere():
if relation.of == oldName:
relation.of = template.name
elif relation.From == oldName:
relation.From = template.name
#template.printDomMap()
return template
def HandleCommonTemplate(self, node, elem):
"""
Handle the common children of data elements like String and Number.
"""
elem.onArrayNext = self._getAttribute(node, "onArrayNext")
for child in node:
child_nodeName = split_ns(child.tag)[1]
if child_nodeName == 'Relation':
relation = self.HandleRelation(child, elem)
elem.relations.append(relation)
elif child_nodeName == 'Transformer':
if elem.transformer is not None:
raise PeachException("Error, data element [%s] already has a transformer." % elem.name)
elem.transformer = self.HandleTransformer(child, elem)
elif child_nodeName == 'Fixup':
self.HandleFixup(child, elem)
elif child_nodeName == 'Placement':
self.HandlePlacement(child, elem)
elif child_nodeName == 'Hint':
self.HandleHint(child, elem)
else:
raise PeachException("Found unexpected child node '%s' in element '%s'." % (child_nodeName, elem.name))
def HandleTransformer(self, node, parent):
"""
Handle Transformer element
"""
transformer = Transformer(parent)
childTransformer = None
params = []
# class
if node.get("class") is None:
raise PeachException("Transformer element missing class attribute")
generatorClass = self._getAttribute(node, "class")
transformer.classStr = generatorClass
# children
for child in node.iterchildren():
child_nodeName = split_ns(child.tag)[1]
if child_nodeName == 'Transformer':
if childTransformer is not None:
raise PeachException("A transformer can only have one child transformer")
childTransformer = self.HandleTransformer(child, transformer)
continue
if child_nodeName == 'Param':
param = self.HandleParam(child, transformer)
transformer.append(param)
params.append([param.name, param.defaultValue])
code = "PeachXml_" + generatorClass + '('
isFirst = True
for param in params:
if not isFirst:
code += ', '
else:
isFirst = False
code += PeachStr(param[1])
code += ')'
trans = eval(code, globals(), locals())
if childTransformer is not None:
trans.addTransformer(childTransformer.transformer)
transformer.transformer = trans
if parent is not None:
parent.transformer = transformer
transformer.parent = parent
#parent.append(transformer)
return transformer
def HandleDefaults(self, node, parent):
"""
Handle data element defaults
"""
# children
for child in node.iterchildren():
child_nodeName = split_ns(child.tag)[1]
if child_nodeName == 'Blob':
if child.get('valueType') is not None:
Blob.defaultValueType = self._getAttribute(child, 'valueType')
if Blob.defaultValueType not in ['string', 'literal', 'hex']:
raise PeachException("Error, default value for Blob.valueType incorrect.")
if child.get('lengthType') is not None:
Blob.defaultLengthType = self._getAttribute(child, 'lengthType')
if Blob.defaultLengthType not in ['string', 'literal', 'calc']:
raise PeachException("Error, default value for Blob.lengthType incorrect.")
elif child_nodeName == 'Flags':
if child.get('endian') is not None:
Flags.defaultEndian = self._getAttribute(child, 'endian')
if Flags.defaultEndian not in ['little', 'big', 'network']:
raise PeachException("Error, default value for Flags.endian incorrect.")
elif child_nodeName == 'Number':
if child.get('endian') is not None:
Number.defaultEndian = self._getAttribute(child, 'endian')