]> git.cworth.org Git - apitrace/blob - scripts/tracediff2.py
Don't prefix '| ' on calls that just have different call nos.
[apitrace] / scripts / tracediff2.py
1 #!/usr/bin/env python
2 ##########################################################################
3 #
4 # Copyright 2011 Jose Fonseca
5 # All Rights Reserved.
6 #
7 # Permission is hereby granted, free of charge, to any person obtaining a copy
8 # of this software and associated documentation files (the "Software"), to deal
9 # in the Software without restriction, including without limitation the rights
10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 # copies of the Software, and to permit persons to whom the Software is
12 # furnished to do so, subject to the following conditions:
13 #
14 # The above copyright notice and this permission notice shall be included in
15 # all copies or substantial portions of the Software.
16 #
17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 # THE SOFTWARE.
24 #
25 ##########################################################################/
26
27
28 import difflib
29 import optparse
30 import os.path
31 import subprocess
32 import sys
33
34 from unpickle import Unpickler
35 from highlight import ColorHighlighter, LessHighlighter
36
37
38 ignoredFunctionNames = set([
39     'glGetString',
40     'glXGetClientString',
41     'glXGetCurrentDisplay',
42     'glXGetProcAddress',
43     'glXGetProcAddressARB',
44     'wglGetProcAddress',
45 ])
46
47
48 class Loader(Unpickler):
49
50     def __init__(self, stream):
51         Unpickler.__init__(self, stream)
52         self.calls = []
53
54     def handleCall(self, call):
55         if call.functionName not in ignoredFunctionNames:
56             self.calls.append(call)
57             hash(call)
58
59
60 def readtrace(trace, calls):
61     p = subprocess.Popen(
62         args = [
63             options.apitrace,
64             'pickle',
65             '--symbolic',
66             '--calls=' + calls,
67             trace
68         ],
69         stdout = subprocess.PIPE,
70     )
71
72     calls = []
73     parser = Loader(p.stdout)
74     parser.parse()
75     return parser.calls
76
77
78 class SDiffer:
79
80     def __init__(self, a, b, highlighter, callNos = False):
81         self.a = a
82         self.b = b
83         self.highlighter = highlighter
84         self.delete_color = highlighter.red
85         self.insert_color = highlighter.green
86         self.callNos = callNos
87
88     def diff(self):
89         matcher = difflib.SequenceMatcher(self.isjunk, self.a, self.b)
90         for tag, alo, ahi, blo, bhi in matcher.get_opcodes():
91             if tag == 'replace':
92                 self.replace(alo, ahi, blo, bhi)
93             elif tag == 'delete':
94                 self.delete(alo, ahi)
95             elif tag == 'insert':
96                 self.insert(blo, bhi)
97             elif tag == 'equal':
98                 self.equal(alo, ahi, blo, bhi)
99             else:
100                 raise ValueError, 'unknown tag %s' % (tag,)
101
102     def isjunk(self, call):
103         return call.functionName == 'glGetError' and call.ret in ('GL_NO_ERROR', 0)
104
105     def replace(self, alo, ahi, blo, bhi):
106         assert alo < ahi and blo < bhi
107         
108         a_names = [call.functionName for call in self.a[alo:ahi]]
109         b_names = [call.functionName for call in self.b[blo:bhi]]
110
111         matcher = difflib.SequenceMatcher(None, a_names, b_names)
112         for tag, _alo, _ahi, _blo, _bhi in matcher.get_opcodes():
113             _alo += alo
114             _ahi += alo
115             _blo += blo
116             _bhi += blo
117             if tag == 'replace':
118                 self.replace_dissimilar(_alo, _ahi, _blo, _bhi)
119             elif tag == 'delete':
120                 self.delete(_alo, _ahi)
121             elif tag == 'insert':
122                 self.insert(_blo, _bhi)
123             elif tag == 'equal':
124                 self.replace_similar(_alo, _ahi, _blo, _bhi)
125             else:
126                 raise ValueError, 'unknown tag %s' % (tag,)
127
128     def replace_similar(self, alo, ahi, blo, bhi, prefix = None):
129         assert alo < ahi and blo < bhi
130         assert ahi - alo == bhi - blo
131         if prefix is None:
132             prefix = self.replace_prefix
133         for i in xrange(0, bhi - blo):
134             a_call = self.a[alo + i]
135             b_call = self.b[blo + i]
136             assert a_call.functionName == b_call.functionName
137             assert len(a_call.args) == len(b_call.args)
138             prefix()
139             if self.callNos:
140                 self.replace_value(a_call.no, b_call.no)
141                 self.highlighter.write(' ')
142             self.highlighter.bold(True)
143             self.highlighter.write(b_call.functionName)
144             self.highlighter.bold(False)
145             self.highlighter.write('(')
146             sep = ''
147             for j in xrange(len(b_call.args)):
148                 self.highlighter.write(sep)
149                 self.replace_value(a_call.args[j], b_call.args[j])
150                 sep = ', '
151             self.highlighter.write(')')
152             if a_call.ret is not None or b_call.ret is not None:
153                 self.highlighter.write(' = ')
154                 self.replace_value(a_call.ret, b_call.ret)
155             self.highlighter.write('\n')
156
157     def replace_dissimilar(self, alo, ahi, blo, bhi):
158         assert alo < ahi and blo < bhi
159         if bhi - blo < ahi - alo:
160             first  = self.insert(blo, bhi)
161             second = self.delete(alo, ahi)
162         else:
163             first  = self.delete(alo, ahi)
164             second = self.insert(blo, bhi)
165
166         for g in first, second:
167             for line in g:
168                 yield line
169
170     def replace_value(self, a, b):
171         if b == a:
172             self.highlighter.write(str(b))
173         else:
174             self.highlighter.strike()
175             self.highlighter.color(self.delete_color)
176             self.highlighter.write(str(a))
177             self.highlighter.normal()
178             #self.highlighter.write(" -> ")
179             self.highlighter.write(" ")
180             self.highlighter.color(self.insert_color)
181             self.highlighter.write(str(b))
182             self.highlighter.normal()
183
184     escape = "\33["
185
186     def delete(self, alo, ahi):
187         self.dump(self.delete_prefix, self.a, alo, ahi, self.normal_suffix)
188
189     def insert(self, blo, bhi):
190         self.dump(self.insert_prefix, self.b, blo, bhi, self.normal_suffix)
191
192     def equal(self, alo, ahi, blo, bhi):
193         if self.callNos:
194             self.replace_similar(alo, ahi, blo, bhi, prefix=self.equal_prefix)
195         else:
196             self.dump(self.equal_prefix, self.b, blo, bhi, self.normal_suffix)
197
198     def dump(self, prefix, x, lo, hi, suffix):
199         for i in xrange(lo, hi):
200             call = x[i]
201             prefix()
202             if self.callNos:
203                 self.highlighter.write(str(call.no) + ' ')
204             self.highlighter.bold(True)
205             self.highlighter.write(call.functionName)
206             self.highlighter.bold(False)
207             self.highlighter.write('(' + ', '.join(map(repr, call.args)) + ')')
208             if call.ret is not None:
209                 self.highlighter.write(' = ' + repr(call.ret))
210             suffix()
211             self.highlighter.write('\n')
212
213     def delete_prefix(self):
214         self.highlighter.write('- ')
215         self.highlighter.strike()
216         self.highlighter.color(self.delete_color)
217     
218     def insert_prefix(self):
219         self.highlighter.write('+ ')
220         self.highlighter.color(self.insert_color)
221
222     def equal_prefix(self):
223         self.highlighter.write('  ')
224
225     def normal_suffix(self):
226         self.highlighter.normal()
227     
228     def replace_prefix(self):
229         self.highlighter.write('| ')
230
231
232 def main():
233     '''Main program.
234     '''
235
236     # Parse command line options
237     optparser = optparse.OptionParser(
238         usage='\n\t%prog <trace> <trace>',
239         version='%%prog')
240     optparser.add_option(
241         '-a', '--apitrace', metavar='PROGRAM',
242         type='string', dest='apitrace', default='apitrace',
243         help='apitrace command [default: %default]')
244     optparser.add_option(
245         '-c', '--calls', metavar='CALLSET',
246         type="string", dest="calls", default='1-10000',
247         help="calls to compare [default: %default]")
248     optparser.add_option(
249         '--ref-calls', metavar='CALLSET',
250         type="string", dest="ref_calls", default=None,
251         help="calls to compare from reference trace")
252     optparser.add_option(
253         '--src-calls', metavar='CALLSET',
254         type="string", dest="src_calls", default=None,
255         help="calls to compare from source trace")
256     optparser.add_option(
257         '--call-nos',
258         action="store_true",
259         dest="call_nos", default=False,
260         help="dump call numbers")
261     global options
262     (options, args) = optparser.parse_args(sys.argv[1:])
263     if len(args) != 2:
264         optparser.error("incorrect number of arguments")
265
266     if options.ref_calls is None:
267         options.ref_calls = options.calls
268     if options.src_calls is None:
269         options.src_calls = options.calls
270
271     ref_calls = readtrace(args[0], options.ref_calls)
272     src_calls = readtrace(args[1], options.src_calls)
273
274     if sys.stdout.isatty():
275         highlighter = LessHighlighter()
276     else:
277         highlighter = ColorHighlighter()
278
279     differ = SDiffer(ref_calls, src_calls, highlighter, options.call_nos)
280     differ.diff()
281
282
283 if __name__ == '__main__':
284     main()