]> git.cworth.org Git - apitrace/blob - scripts/tracediff2.py
Handle less not existing.
[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 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         call.no = None
56         hash(call)
57         if call.functionName not in ignoredFunctionNames:
58             self.calls.append(call)
59
60
61 def readtrace(trace):
62     p = subprocess.Popen(
63         args = [
64             options.apitrace,
65             'pickle',
66             '--symbolic',
67             '--calls=' + options.calls,
68             trace
69         ],
70         stdout = subprocess.PIPE,
71     )
72
73     calls = []
74     parser = Loader(p.stdout)
75     parser.parse()
76     return parser.calls
77
78
79 class SDiffer:
80
81     def __init__(self, a, b, highlighter):
82         self.a = a
83         self.b = b
84         self.highlighter = highlighter
85         self.delete_color = highlighter.red
86         self.insert_color = highlighter.green
87
88     def diff(self):
89         matcher = difflib.SequenceMatcher(None, 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)
99             else:
100                 raise ValueError, 'unknown tag %s' % (tag,)
101
102     def replace(self, alo, ahi, blo, bhi):
103         assert alo < ahi and blo < bhi
104         
105         a_names = [call.functionName for call in self.a[alo:ahi]]
106         b_names = [call.functionName for call in self.b[blo:bhi]]
107
108         matcher = difflib.SequenceMatcher(None, a_names, b_names)
109         for tag, _alo, _ahi, _blo, _bhi in matcher.get_opcodes():
110             _alo += alo
111             _ahi += alo
112             _blo += blo
113             _bhi += blo
114             if tag == 'replace':
115                 self.replace_dissimilar(_alo, _ahi, _blo, _bhi)
116             elif tag == 'delete':
117                 self.delete(_alo, _ahi)
118             elif tag == 'insert':
119                 self.insert(_blo, _bhi)
120             elif tag == 'equal':
121                 self.replace_similar(_alo, _ahi, _blo, _bhi)
122             else:
123                 raise ValueError, 'unknown tag %s' % (tag,)
124
125     def replace_similar(self, alo, ahi, blo, bhi):
126         assert alo < ahi and blo < bhi
127         assert ahi - alo == bhi - blo
128         for i in xrange(0, bhi - blo):
129             a_call = self.a[alo + i]
130             b_call = self.b[blo + i]
131             assert a_call.functionName == b_call.functionName
132             assert len(a_call.args) == len(b_call.args)
133             self.replace_prefix()
134             self.highlighter.bold(True)
135             self.highlighter.write(b_call.functionName)
136             self.highlighter.bold(False)
137             self.highlighter.write('(')
138             sep = ''
139             for j in xrange(len(b_call.args)):
140                 self.highlighter.write(sep)
141                 self.replace_value(a_call.args[j], b_call.args[j])
142                 sep = ', '
143             self.highlighter.write(')')
144             if a_call.ret is not None or b_call.ret is not None:
145                 self.highlighter.write(' = ')
146                 self.replace_value(a_call.ret, b_call.ret)
147             self.highlighter.write('\n')
148
149     def replace_dissimilar(self, alo, ahi, blo, bhi):
150         assert alo < ahi and blo < bhi
151         if bhi - blo < ahi - alo:
152             first  = self.insert(blo, bhi)
153             second = self.delete(alo, ahi)
154         else:
155             first  = self.delete(alo, ahi)
156             second = self.insert(blo, bhi)
157
158         for g in first, second:
159             for line in g:
160                 yield line
161
162     def replace_value(self, a, b):
163         if b == a:
164             self.highlighter.write(str(b))
165         else:
166             self.highlighter.color(self.delete_color)
167             self.highlighter.write(str(a))
168             self.highlighter.normal()
169             self.highlighter.write(" -> ")
170             self.highlighter.color(self.insert_color)
171             self.highlighter.write(str(b))
172             self.highlighter.normal()
173
174     escape = "\33["
175
176     def delete(self, alo, ahi):
177         self.dump(self.delete_prefix, self.a, alo, ahi, self.normal_suffix)
178
179     def insert(self, blo, bhi):
180         self.dump(self.insert_prefix, self.b, blo, bhi, self.normal_suffix)
181
182     def equal(self, alo, ahi):
183         self.dump(self.equal_prefix, self.a, alo, ahi, self.normal_suffix)
184
185     def dump(self, prefix, x, lo, hi, suffix):
186         for i in xrange(lo, hi):
187             call = x[i]
188             prefix()
189             self.highlighter.bold(True)
190             self.highlighter.write(call.functionName)
191             self.highlighter.bold(False)
192             self.highlighter.write('(' + ', '.join(map(repr, call.args)) + ')')
193             if call.ret is not None:
194                 self.highlighter.write(' = ' + repr(call.ret))
195             suffix()
196             self.highlighter.write('\n')
197
198     def delete_prefix(self):
199         self.highlighter.write('- ')
200         self.highlighter.color(self.delete_color)
201     
202     def insert_prefix(self):
203         self.highlighter.write('+ ')
204         self.highlighter.color(self.insert_color)
205
206     def equal_prefix(self):
207         self.highlighter.write('  ')
208
209     def normal_suffix(self):
210         self.highlighter.normal()
211     
212     def replace_prefix(self):
213         self.highlighter.write('| ')
214
215
216 def main():
217     '''Main program.
218     '''
219
220     # Parse command line options
221     optparser = optparse.OptionParser(
222         usage='\n\t%prog <trace> <trace>',
223         version='%%prog')
224     optparser.add_option(
225         '-a', '--apitrace', metavar='PROGRAM',
226         type='string', dest='apitrace', default='apitrace',
227         help='apitrace command [default: %default]')
228     optparser.add_option(
229         '-c', '--calls', metavar='CALLSET',
230         type="string", dest="calls", default='1-10000',
231         help="calls to compare [default: %default]")
232
233     global options
234     (options, args) = optparser.parse_args(sys.argv[1:])
235     if len(args) != 2:
236         optparser.error("incorrect number of arguments")
237
238     ref_calls = readtrace(args[0])
239     src_calls = readtrace(args[1])
240
241     highlighter = LessHighlighter()
242
243     differ = SDiffer(ref_calls, src_calls, highlighter)
244     differ.diff()
245
246
247 if __name__ == '__main__':
248     main()