-
Notifications
You must be signed in to change notification settings - Fork 9
/
tracematch.py
executable file
·870 lines (662 loc) · 23.4 KB
/
tracematch.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
#!/usr/bin/env python3
##########################################################################
#
# Copyright 2008-2012 Jose Fonseca
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
##########################################################################/
import sys
import optparse
import string
import os
import re
import subprocess
class MatchObject:
def __init__(self):
self.params = {}
class Matcher:
def match(self, value, mo):
raise NotImplementedError
def _matchSequence(self, refValues, srcValues, mo):
if not isinstance(srcValues, (list, tuple)):
return False
if len(refValues) != len(srcValues):
return False
for refValue, srcValue in zip(refValues, srcValues):
if not refValue.match(srcValue, mo):
return False
return True
def __str__(self):
raise NotImplementerError
def __repr__(self):
return str(self)
class WildcardMatcher(Matcher):
def __init__(self, name = ''):
self.name = name
def match(self, value, mo):
if self.name:
try:
refValue = mo.params[self.name]
except KeyError:
mo.params[self.name] = value
else:
return refValue == value
return True
def __str__(self):
return '<' + self.name + '>'
class LiteralMatcher(Matcher):
def __init__(self, refValue):
self.refValue = refValue
def match(self, value, mo):
return self.refValue == value
def __str__(self):
return repr(self.refValue)
class ApproxMatcher(Matcher):
def __init__(self, refValue, tolerance = 2**-23):
self.refValue = refValue
self.tolerance = tolerance
def match(self, value, mo):
if not isinstance(value, float):
return
error = abs(self.refValue - value)
if self.refValue:
error = error / self.refValue
return error <= self.tolerance
def __str__(self):
return repr(self.refValue)
def isShaderDisassembly(value):
return value.find('// Generated by Microsoft (R) D3D Shader Disassembler\n') != -1
def normalizeShaderDisassembly(value):
# Unfortunately slightly different disassemblers produce different output
return '\n'.join([line.strip() for line in value.split('\n') if line.strip() and not line.startswith('//')])
class StringMatcher(Matcher):
def __init__(self, refValue):
self.refValue = refValue
def match(self, value, mo):
if isShaderDisassembly(self.refValue) and isShaderDisassembly(value):
return normalizeShaderDisassembly(self.refValue) == normalizeShaderDisassembly(value)
return self.refValue == value
def __str__(self):
return repr(self.refValue)
class BitmaskMatcher(Matcher):
def __init__(self, refElements):
self.refElements = refElements
def match(self, value, mo):
return self._matchSequence(self.refElements, value, mo)
def __str__(self):
return ' | '.join(map(str, self.refElements))
class OffsetMatcher(Matcher):
def __init__(self, refValue, offset):
self.refValue = refValue
self.offset = offset
def match(self, value, mo):
return self.refValue.match(value - self.offset, mo)
def __str__(self):
return '%s + %i' % (self.refValue, self.offset)
class ArrayMatcher(Matcher):
def __init__(self, refElements):
self.refElements = refElements
def match(self, value, mo):
return self._matchSequence(self.refElements, value, mo)
def __str__(self):
return '{' + ', '.join(map(str, self.refElements)) + '}'
class StructMatcher(Matcher):
def __init__(self, refMembers):
self.refMembers = refMembers
def match(self, value, mo):
if not isinstance(value, dict):
return False
if len(value) != len(self.refMembers):
return False
for name, refMember in self.refMembers.items():
try:
member = value[name]
except KeyError:
return False
else:
if not refMember.match(member, mo):
return False
return True
def __str__(self):
return '{' + ', '.join(['%s = %s' % refMember for refMember in self.refMembers.items()]) + '}'
class CallMatcher(Matcher):
def __init__(self, callNo, functionName, args, ret):
self.callNo = callNo
self.functionName = functionName
self.args = args
self.ret = ret
def _parseVersionedMethodName(self, name):
try:
ifaceName, methodName = name.split('::', 1)
except ValueError:
return None, 0, name
if ifaceName[-1] in string.digits:
ifaceVersion = int(ifaceName[-1])
ifaceName = ifaceName[:-1]
else:
ifaceVersion = 0
return ifaceName, ifaceVersion, methodName
def _matchFunctionName(self, srcFunctionName):
if self.functionName == srcFunctionName:
return True
# Match things like IDXGIFactory1::* and IDXGIFactory2::*
ifaceName, ifaceVersion, methodName = self._parseVersionedMethodName(self.functionName)
srcIfaceName, srcIfaceVersion, srcMethodName = self._parseVersionedMethodName(srcFunctionName)
return (
ifaceName == srcIfaceName and
ifaceVersion <= srcIfaceVersion and
methodName == srcMethodName
)
def match(self, call, mo):
callNo, srcFunctionName, srcArgs, srcRet = call
if not self._matchFunctionName(srcFunctionName):
return False
refArgs = [value for name, value in self.args]
srcArgs = [value for name, value in srcArgs]
if not self._matchSequence(refArgs, srcArgs, mo):
return False
if self.ret is None:
if srcRet is not None:
return False
else:
if not self.ret.match(srcRet, mo):
return False
if self.callNo is not None:
if not self.callNo.match(callNo, mo):
return False
return True
def __str__(self):
s = self.functionName
s += '(' + ', '.join(['%s = %s' % refArg for refArg in self.args]) + ')'
if self.ret is not None:
s += ' = ' + str(self.ret)
return s
class TraceMismatch(Exception):
pass
class TraceMatcher:
def __init__(self, calls):
self.calls = calls
def match(self, calls, verbose = False):
mo = MatchObject()
srcCalls = iter(calls)
for refCall in self.calls:
if verbose:
print(refCall)
skippedSrcCalls = []
while True:
try:
srcCall = next(srcCalls)
except StopIteration:
if skippedSrcCalls:
raise TraceMismatch('missing call\n %s\nfound\n %s)' % (refCall, skippedSrcCalls[0]))
else:
raise TraceMismatch('missing call\n %s' % refCall)
if verbose:
print('\t%s %s%r = %r' % srcCall)
if refCall.match(srcCall, mo):
break
else:
skippedSrcCalls.append(srcCall)
return mo
def __str__(self):
return ''.join(['%s\n' % call for call in self.calls])
#######################################################################
EOF = -1
SKIP = -2
class ParseError(Exception):
def __init__(self, msg=None, filename=None, line=None, col=None):
self.msg = msg
self.filename = filename
self.line = line
self.col = col
def __str__(self):
return ':'.join([str(part) for part in (self.filename, self.line, self.col, self.msg) if part != None])
class Scanner:
"""Stateless scanner."""
# should be overriden by derived classes
tokens = []
symbols = {}
literals = {}
ignorecase = False
def __init__(self):
flags = re.DOTALL
if self.ignorecase:
flags |= re.IGNORECASE
self.tokens_re = re.compile(
'|'.join(['(' + regexp + ')' for type, regexp, test_lit in self.tokens]),
flags
)
def next(self, buf, pos):
if pos >= len(buf):
return EOF, '', pos
mo = self.tokens_re.match(buf, pos)
if mo:
text = mo.group()
type, regexp, test_lit = self.tokens[mo.lastindex - 1]
pos = mo.end()
if test_lit:
type = self.literals.get(text, type)
return type, text, pos
else:
c = buf[pos]
return self.symbols.get(c, None), c, pos + 1
class Token:
def __init__(self, type, text, line, col):
self.type = type
self.text = text
self.line = line
self.col = col
class Lexer:
# should be overriden by derived classes
scanner = None
tabsize = 8
newline_re = re.compile(r'\r\n?|\n')
def __init__(self, buf = None, pos = 0, filename = None, fp = None):
if fp is not None:
# read whole file into memory
buf = fp.read()
pos = 0
if filename is None:
try:
filename = fp.name
except AttributeError:
filename = None
self.buf = buf
self.pos = pos
self.line = 1
self.col = 1
self.filename = filename
def __next__(self):
while True:
# save state
pos = self.pos
line = self.line
col = self.col
type, text, endpos = self.scanner.next(self.buf, pos)
assert pos + len(text) == endpos
self.consume(text)
type, text = self.filter(type, text)
self.pos = endpos
if type == SKIP:
continue
elif type is None:
msg = 'unexpected char '
if text >= ' ' and text <= '~':
msg += "'%s'" % text
else:
msg += "0x%X" % ord(text)
raise ParseError(msg, self.filename, line, col)
else:
break
return Token(type = type, text = text, line = line, col = col)
def consume(self, text):
# update line number
pos = 0
for mo in self.newline_re.finditer(text, pos):
self.line += 1
self.col = 1
pos = mo.end()
# update column number
while True:
tabpos = text.find('\t', pos)
if tabpos == -1:
break
self.col += tabpos - pos
self.col = ((self.col - 1)//self.tabsize + 1)*self.tabsize + 1
pos = tabpos + 1
self.col += len(text) - pos
def filter(self, type, text):
return type, text
class Parser:
def __init__(self, lexer):
self.lexer = lexer
self.lookahead = next(self.lexer)
def match(self, type):
return self.lookahead.type == type
def skip(self, type):
while not self.match(type):
self.consume()
def error(self):
raise ParseError(
msg = 'unexpected token %r' % self.lookahead.text,
filename = self.lexer.filename,
line = self.lookahead.line,
col = self.lookahead.col)
def consume(self, type = None):
if type is not None and not self.match(type):
self.error()
token = self.lookahead
self.lookahead = next(self.lexer)
return token
#######################################################################
ID, NUMBER, HEXNUM, STRING, WSTRING, WILDCARD, LPAREN, RPAREN, LCURLY, RCURLY, COMMA, AMP, EQUAL, PLUS, VERT, BLOB, MISSING = range(17)
class CallScanner(Scanner):
# token regular expression table
tokens = [
# whitespace
(SKIP, r'[ \t\f\r\n\v]+', False),
# comments
(SKIP, r'//[^\r\n]*', False),
# String IDs
(WSTRING, r'L"[^"\\]*(?:\\.[^"\\]*)*"', False),
# Alphanumeric IDs
(ID, r'D3DFVF_TEXCOORDSIZE[1-4]\([0-9]+\)|[a-zA-Z_][a-zA-Z0-9_]*(?:::[a-zA-Z_][a-zA-Z0-9_]*)?', True),
# Numeric IDs
(HEXNUM, r'-?0x[0-9a-fA-F]+', False),
# Numeric IDs
(NUMBER, r'-?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)(?:[eE][-+][0-9]+)?', False),
# String IDs
(STRING, r'"[^"\\]*(?:\\.[^"\\]*)*"', False),
# Wildcard
(WILDCARD, r'<[^>]*>', False),
]
# symbol table
symbols = {
'(': LPAREN,
')': RPAREN,
'{': LCURLY,
'}': RCURLY,
',': COMMA,
'&': AMP,
'=': EQUAL,
'+': PLUS,
'|': VERT,
'?': MISSING,
}
# literal table
literals = {
'blob': BLOB
}
class CallLexer(Lexer):
scanner = CallScanner()
def filter(self, type, text):
if type == WSTRING:
text = text[1:]
type = STRING
if type == STRING:
text = text[1:-1]
# quotes
text = text.replace('\\"', '"')
# DOS lines (necessary when mmaping)
text = text.replace('\r\n', '\n')
return type, text
class TraceParser(Parser):
def __init__(self, stream):
lexer = CallLexer(fp = stream)
Parser.__init__(self, lexer)
def eof(self):
return self.match(EOF)
def parse(self):
while not self.eof():
self.parse_call()
return TraceMatcher(self.calls)
def parse_call(self):
if self.lookahead.type == NUMBER:
token = self.consume()
callNo = self.handleInt(int(token.text))
elif self.lookahead.type == WILDCARD:
token = self.consume()
callNo = self.handleWildcard((token.text[1:-1]))
else:
callNo = None
functionName = self.consume(ID).text
args = self.parse_sequence(LPAREN, RPAREN, self.parse_pair)
if self.match(EQUAL):
self.consume(EQUAL)
ret = self.parse_value()
else:
ret = None
self.handleCall(callNo, functionName, args, ret)
def parse_pair(self):
'''Parse a `name = value` pair.'''
name = self.consume(ID).text
self.consume(EQUAL)
value = self.parse_value()
return name, value
def parse_opt_pair(self):
'''Parse an optional `name = value` pair.'''
if self.match(ID):
token = self.consume(ID)
if self.match(EQUAL):
self.consume(EQUAL)
name = token.text
value = self.parse_value()
else:
name = None
value = self.handleID(token.text)
value = self.parse_value_expr(value)
else:
name = None
value = self.parse_value()
if name is None:
return value
else:
return name, value
def parse_value(self):
value = self._parse_value()
return self.parse_value_expr(value)
def parse_value_expr(self, value):
if self.match(VERT):
flags = [value]
while self.match(VERT):
self.consume()
value = self._parse_value()
flags.append(value)
return self.handleBitmask(flags)
elif self.match(PLUS):
self.consume()
if self.match(NUMBER):
token = self.consume()
offset = int(token.text)
elif self.match(HEXNUM):
token = self.consume()
offset = int(token.text, 16)
else:
assert 0
return self.handleOffset(value, offset)
else:
return value
def _parse_value(self):
if self.match(AMP):
self.consume()
value = [self.parse_value()]
return self.handleArray(value)
elif self.match(ID):
token = self.consume()
value = token.text
return self.handleID(value)
elif self.match(STRING):
token = self.consume()
value = token.text
return self.handleString(value)
elif self.match(NUMBER):
token = self.consume()
try:
value = int(token.text)
except ValueError:
value = float(token.text)
return self.handleFloat(value)
else:
return self.handleInt(value)
elif self.match(HEXNUM):
token = self.consume()
value = int(token.text, 16)
return self.handleInt(value)
elif self.match(LCURLY):
value = self.parse_sequence(LCURLY, RCURLY, self.parse_opt_pair)
if len(value) and isinstance(value[0], tuple):
value = dict(value)
return self.handleStruct(value)
else:
return self.handleArray(value)
elif self.match(BLOB):
token = self.consume()
self.consume(LPAREN)
token = self.consume()
length = int(token.text)
self.consume(RPAREN)
return self.handleBlob(length)
elif self.match(WILDCARD):
token = self.consume()
return self.handleWildcard(token.text[1:-1])
elif self.match(MISSING):
token = self.consume()
# XXX: No handler for missing yet
return self.handleString(token.text)
else:
self.error()
def parse_sequence(self, ltype, rtype, elementParser):
'''Parse a comma separated list'''
elements = []
self.consume(ltype)
sep = None
while not self.match(rtype):
if sep is None:
sep = COMMA
else:
self.consume(sep)
element = elementParser()
elements.append(element)
self.consume(rtype)
return elements
def handleID(self, value):
raise NotImplementedError
def handleInt(self, value):
raise NotImplementedError
def handleFloat(self, value):
raise NotImplementedError
def handleString(self, value):
raise NotImplementedError
def handleBitmask(self, value):
raise NotImplementedError
def handleOffset(self, value, offset):
raise NotImplementedError
def handleArray(self, value):
raise NotImplementedError
def handleStruct(self, value):
raise NotImplementedError
def handleBlob(self, length):
return self.handleID('blob(%u)' % length)
def handleWildcard(self, name):
raise NotImplementedError
def handleCall(self, callNo, functionName, args, ret):
raise NotImplementedError
class RefTraceParser(TraceParser):
def __init__(self, fileName):
TraceParser.__init__(self, open(fileName, 'rt'))
self.calls = []
def parse(self):
TraceParser.parse(self)
return TraceMatcher(self.calls)
def handleID(self, value):
return LiteralMatcher(value)
def handleInt(self, value):
return LiteralMatcher(value)
def handleFloat(self, value):
return ApproxMatcher(value)
def handleString(self, value):
return StringMatcher(value)
def handleBitmask(self, value):
return BitmaskMatcher(value)
def handleOffset(self, value, offset):
return OffsetMatcher(value, offset)
def handleArray(self, value):
return ArrayMatcher(value)
def handleStruct(self, value):
return StructMatcher(value)
def handleWildcard(self, name):
return WildcardMatcher(name)
def handleCall(self, callNo, functionName, args, ret):
call = CallMatcher(callNo, functionName, args, ret)
self.calls.append(call)
class SrcTraceParser(TraceParser):
def __init__(self, stream):
TraceParser.__init__(self, stream)
self.calls = []
def parse(self):
TraceParser.parse(self)
return self.calls
def handleID(self, value):
return value
def handleInt(self, value):
return int(value)
def handleFloat(self, value):
return float(value)
def handleString(self, value):
return value
def handleBitmask(self, value):
return value
def handleArray(self, elements):
return list(elements)
def handleStruct(self, members):
return dict(members)
def handleCall(self, callNo, functionName, args, ret):
call = (callNo, functionName, args, ret)
self.calls.append(call)
def main():
# Parse command line options
optparser = optparse.OptionParser(
usage='\n\t%prog [OPTIONS] REF_TXT SRC_TRACE',
version='%%prog')
optparser.add_option(
'--apitrace', metavar='PROGRAM',
type='string', dest='apitrace', default=os.environ.get('APITRACE', 'apitrace'),
help='path to apitrace executable')
optparser.add_option(
'-v', '--verbose',
action="store_true",
dest="verbose", default=True,
help="verbose output")
(options, args) = optparser.parse_args(sys.argv[1:])
if len(args) != 2:
optparser.error('wrong number of arguments')
refFileName, srcFileName = args
refParser = RefTraceParser(refFileName)
refTrace = refParser.parse()
if options.verbose:
sys.stdout.write('// Reference\n')
sys.stdout.write(str(refTrace))
sys.stdout.write('\n')
if srcFileName.endswith('.trace'):
cmd = [options.apitrace, 'dump', '--verbose', '--color=never', srcFileName]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
srcStream = p.stdout
else:
srcStream = open(srcFileName, 'rt')
srcParser = SrcTraceParser(srcStream)
srcTrace = srcParser.parse()
if options.verbose:
sys.stdout.write('// Source\n')
sys.stdout.write(''.join(['%s %s%r = %r\n' % call for call in srcTrace]))
sys.stdout.write('\n')
if options.verbose:
sys.stdout.write('// Matching\n')
mo = refTrace.match(srcTrace, options.verbose)
if options.verbose:
sys.stdout.write('\n')
if options.verbose:
sys.stdout.write('// Parameters\n')
paramNames = list(mo.params.keys())
paramNames.sort()
for paramName in paramNames:
print('%s = %r' % (paramName, mo.params[paramName]))
if __name__ == '__main__':
main()