Debian Codegraph @

rpython/jit/backend/ppc/tool/viewcode.py

raw symbols SCIP
1 #! /usr/bin/env python
2 """
3 Viewer for the output of compiled programs generating code.
4 Use on the log files created with 'PYPYLOG=jit-backend-dump:log'.
5
6 Try:
7 ./viewcode.py --text log # text only disassembly
8 ./viewcode.py log # also includes a pygame viewer
9 """
10 from __future__ import print_function
11
12 import new
13 import operator
14 import py
15 import re
16 import sys
17 import subprocess
18 from bisect import bisect_left
19
20 # don't use pypy.tool.udir here to avoid removing old usessions which
21 # might still contain interesting executables
22 udir = py.path.local.make_numbered_dir(prefix='viewcode-', keep=2)
23 tmpfile = str(udir.join('dump.tmp'))
24
25 # hack hack
26 import rpython.tool
27 mod = new.module('rpython.tool.udir')
28 mod.udir = udir
29 sys.modules['rpython.tool.udir'] = mod
30 rpython.tool.udir = mod
31
32 # ____________________________________________________________
33 # Some support code from Psyco. There is more over there,
34 # I am porting it in a lazy fashion... See py-utils/xam.py
35
36 if sys.platform == "win32":
37 pass # lots more in Psyco
38
39 def machine_code_dump(data, originaddr, backend_name, label_list=None):
40 objdump = ('objdump -EB --target=binary --architecture=powerpc:common64 '
41 '--adjust-vma=%(origin)d -D %(file)s')
42 #
43 f = open(tmpfile, 'wb')
44 f.write(data)
45 f.close()
46 p = subprocess.Popen(objdump % {
47 'file': tmpfile,
48 'origin': originaddr,
49 }, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
50 stdout, stderr = p.communicate()
51 assert not p.returncode, ('Encountered an error running objdump: %s' %
52 stderr)
53 # drop some objdump cruft
54 lines = stdout.splitlines(True)[6:] # drop some objdump cruft
55 return format_code_dump_with_labels(originaddr, lines, label_list)
56
57 def format_code_dump_with_labels(originaddr, lines, label_list):
58 from rpython.rlib.rarithmetic import r_uint
59 if not label_list:
60 label_list = []
61 originaddr = r_uint(originaddr)
62 itlines = iter(lines)
63 yield itlines.next() # don't process the first line
64 for lbl_start, lbl_name in label_list:
65 for line in itlines:
66 addr, _ = line.split(':', 1)
67 addr = int(addr, 16)
68 if addr >= originaddr+lbl_start:
69 yield '\n'
70 if lbl_name is None:
71 yield '--end of the loop--\n'
72 else:
73 yield str(lbl_name) + '\n'
74 yield line
75 break
76 yield line
77 # yield all the remaining lines
78 for line in itlines:
79 yield line
80
81 def load_symbols(filename):
82 # the program that lists symbols, and the output it gives
83 symbollister = 'nm %s'
84 re_symbolentry = re.compile(r'([0-9a-fA-F]+)\s\w\s(.*)')
85 #
86 print('loading symbols from %s...' % (filename,))
87 symbols = {}
88 p = subprocess.Popen(symbollister % filename, shell=True,
89 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
90 stdout, stderr = p.communicate()
91 assert not p.returncode, ('Encountered an error running nm: %s' %
92 stderr)
93 for line in stdout.splitlines(True):
94 match = re_symbolentry.match(line)
95 if match:
96 addr = long(match.group(1), 16)
97 name = match.group(2)
98 if name.startswith('pypy_g_'):
99 name = '\xb7' + name[7:]
100 symbols[addr] = name
101 print('%d symbols found' % (len(symbols),))
102 return symbols
103
104 re_addr = re.compile(r'[\s,$]0x([0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]+)')
105 re_lineaddr = re.compile(r'\s*0?x?([0-9a-fA-F]+)')
106
107 def lineaddresses(line):
108 result = []
109 i = 0
110 while 1:
111 match = re_addr.search(line, i)
112 if not match:
113 break
114 i = match.end()
115 addr = long(match.group(1), 16)
116 result.append(addr)
117 return result
118
119 # ____________________________________________________________
120
121 class CodeRange(object):
122 fallthrough = False
123
124 def __init__(self, world, addr, data):
125 self.world = world
126 self.addr = addr
127 self.data = data
128
129 def __repr__(self):
130 return '<CodeRange %s length %d>' % (hex(self.addr), len(self.data))
131
132 def touches(self, other):
133 return (self .addr < other.addr + len(other.data) and
134 other.addr < self .addr + len(self.data))
135
136 def update_from_old(self, other):
137 if other.addr < self.addr:
138 delta = self.addr - other.addr
139 assert delta <= len(other.data)
140 self.addr -= delta
141 self.data = other.data[:delta] + self.data
142 self_end = self .addr + len(self .data)
143 other_end = other.addr + len(other.data)
144 if other_end > self_end:
145 extra = other_end - self_end
146 assert extra <= len(other.data)
147 self.data += other.data[-extra:]
148
149 def cmpop(op):
150 def _cmp(self, other):
151 if not isinstance(other, CodeRange):
152 return NotImplemented
153 return op((self.addr, self.data), (other.addr, other.data))
154 return _cmp
155 __lt__ = cmpop(operator.lt)
156 __le__ = cmpop(operator.le)
157 __eq__ = cmpop(operator.eq)
158 __ne__ = cmpop(operator.ne)
159 __gt__ = cmpop(operator.gt)
160 __ge__ = cmpop(operator.ge)
161 del cmpop
162
163 def disassemble(self):
164 if not hasattr(self, 'text'):
165 lines = machine_code_dump(self.data, self.addr, self.world.backend_name)
166 lines = list(lines)
167 # instead of adding symbol names in the dumps we could
168 # also make the 0xNNNNNNNN addresses be red and show the
169 # symbol name when the mouse is over them
170 logentries = self.world.logentries
171 symbols = self.world.symbols
172 for i, line in enumerate(lines):
173 match = re_lineaddr.match(line)
174 if match:
175 addr = long(match.group(1), 16)
176 logentry = logentries.get(addr)
177 if logentry:
178 lines[i] = '\n%s\n%s' % (logentry, lines[i])
179 for addr in lineaddresses(line):
180 sym = symbols.get(addr)
181 if sym:
182 lines[i] = '%s\t%s\n' % (lines[i].rstrip(), sym)
183 self.text = ''.join(lines)
184 return self.text
185
186 def findjumps(self):
187 text = self.disassemble()
188 lines = text.splitlines()
189 line = ''
190 for i, line in enumerate(lines):
191 if '\tj' not in line: # poor heuristic to recognize lines that
192 continue # could be jump instructions
193 addrs = list(lineaddresses(line))
194 if not addrs:
195 continue
196 addr = addrs[-1]
197 final = '\tjmp' in line
198 yield i, addr, final
199 if self.fallthrough and '\tret' not in line:
200 yield len(lines), self.addr + len(self.data), True
201
202
203 class World(object):
204
205 def __init__(self):
206 self.ranges = []
207 self.labeltargets = {}
208 self.jumps = {}
209 self.symbols = {}
210 self.logentries = {}
211 self.backend_name = None
212 self.executable_name = None
213
214 def parse(self, f, textonly=True):
215 for line in f:
216 if line.startswith('BACKEND '):
217 self.backend_name = line.split(' ')[1].strip()
218 elif line.startswith('CODE_DUMP '):
219 pieces = line.split()
220 assert pieces[1].startswith('@')
221 assert pieces[2].startswith('+')
222 if len(pieces) == 3:
223 continue # empty line
224 baseaddr = long(pieces[1][1:], 16) & 0xFFFFFFFFL
225 offset = int(pieces[2][1:])
226 addr = baseaddr + offset
227 data = pieces[3].replace(':', '').decode('hex')
228 coderange = CodeRange(self, addr, data)
229 i = bisect_left(self.ranges, coderange)
230 j = i
231 while i>0 and coderange.touches(self.ranges[i-1]):
232 coderange.update_from_old(self.ranges[i-1])
233 i -= 1
234 while j<len(self.ranges) and coderange.touches(self.ranges[j]):
235 coderange.update_from_old(self.ranges[j])
236 j += 1
237 self.ranges[i:j] = [coderange]
238 elif line.startswith('LOG '):
239 pieces = line.split(None, 3)
240 assert pieces[1].startswith('@')
241 assert pieces[2].startswith('+')
242 baseaddr = long(pieces[1][1:], 16) & 0xFFFFFFFFL
243 offset = int(pieces[2][1:])
244 addr = baseaddr + offset
245 self.logentries[addr] = pieces[3]
246 elif line.startswith('SYS_EXECUTABLE '):
247 filename = line[len('SYS_EXECUTABLE '):].strip()
248 if filename != self.executable_name and filename != '??':
249 self.symbols.update(load_symbols(filename))
250 self.executable_name = filename
251
252 def find_cross_references(self):
253 # find cross-references between blocks
254 fnext = 0.1
255 for i, r in enumerate(self.ranges):
256 for lineno, targetaddr, _ in r.findjumps():
257 self.labeltargets[targetaddr] = True
258 if i % 100 == 99:
259 f = float(i) / len(self.ranges)
260 if f >= fnext:
261 sys.stderr.write("%d%%" % int(f*100.0))
262 fnext += 0.1
263 sys.stderr.write(".")
264 sys.stderr.write("100%")
265 # split blocks at labeltargets
266 t = self.labeltargets
267 #print t
268 for r in self.ranges:
269 #print r.addr, r.addr + len(r.data)
270 for i in range(r.addr + 1, r.addr + len(r.data)):
271 if i in t:
272 #print i
273 ofs = i - r.addr
274 self.ranges.append(CodeRange(self, i, r.data[ofs:]))
275 r.data = r.data[:ofs]
276 r.fallthrough = True
277 try:
278 del r.text
279 except AttributeError:
280 pass
281 break
282 # hack hack hacked
283 sys.stderr.write("\n")
284
285 def show(self, showtext=True, showgraph=True):
286 if showgraph:
287 g1 = Graph('codedump')
288 self.ranges.sort()
289 for r in self.ranges:
290 disassembled = r.disassemble()
291 if showtext:
292 print(disassembled)
293 if showgraph:
294 text, width = tab2columns(disassembled)
295 text = '0x%x\n\n%s' % (r.addr, text)
296 g1.emit_node('N_%x' % r.addr, shape="box", label=text,
297 width=str(width*0.1125))
298 for lineno, targetaddr, final in r.findjumps():
299 if final:
300 color = "black"
301 else:
302 color = "red"
303 g1.emit_edge('N_%x' % r.addr, 'N_%x' % targetaddr,
304 color=color)
305 sys.stdout.flush()
306 if showgraph:
307 g1.display()
308
309 def showtextonly(self):
310 self.ranges.sort()
311 for r in self.ranges:
312 disassembled = r.disassemble()
313 print(disassembled)
314 del r.text
315
316
317 def tab2columns(text):
318 lines = text.split('\n')
319 columnwidth = []
320 for line in lines:
321 columns = line.split('\t')[:-1]
322 while len(columnwidth) < len(columns):
323 columnwidth.append(0)
324 for i, s in enumerate(columns):
325 width = len(s.strip())
326 if not s.endswith(':'):
327 width += 2
328 columnwidth[i] = max(columnwidth[i], width)
329 columnwidth.append(1)
330 result = []
331 for line in lines:
332 columns = line.split('\t')
333 text = []
334 for width, s in zip(columnwidth, columns):
335 text.append(s.strip().ljust(width))
336 result.append(' '.join(text))
337 lengths = [len(line) for line in result]
338 lengths.append(1)
339 totalwidth = max(lengths)
340 return '\\l'.join(result), totalwidth
341
342 # ____________________________________________________________
343 # XXX pasted from
344 # http://codespeak.net/svn/user/arigo/hack/misc/graphlib.py
345 # but needs to be a bit more subtle later
346
347 from rpython.translator.tool.make_dot import DotGen
348 from dotviewer.graphclient import display_page
349
350 class Graph(DotGen):
351
352 def highlight(self, word, text, linked_to=None):
353 if not hasattr(self, '_links'):
354 self._links = {}
355 self._links_to = {}
356 self._links[word] = text
357 if linked_to:
358 self._links_to[word] = linked_to
359
360 def display(self):
361 "Display a graph page locally."
362 display_page(_Page(self))
363
364
365 class NoGraph(Exception):
366 pass
367
368 class _Page:
369 def __init__(self, graph_builder):
370 if callable(graph_builder):
371 graph = graph_builder()
372 else:
373 graph = graph_builder
374 if graph is None:
375 raise NoGraph
376 self.graph_builder = graph_builder
377
378 def content(self):
379 return _PageContent(self.graph_builder)
380
381 class _PageContent:
382 fixedfont = True
383
384 def __init__(self, graph_builder):
385 if callable(graph_builder):
386 graph = graph_builder()
387 else:
388 graph = graph_builder
389 assert graph is not None
390 self.graph_builder = graph_builder
391 self.graph = graph
392 self.links = getattr(graph, '_links', {})
393 if not hasattr(graph, '_source'):
394 graph._source = graph.generate(target=None)
395 self.source = graph._source
396
397 def followlink(self, link):
398 try:
399 return _Page(self.graph._links_to[link])
400 except NoGraph:
401 return _Page(self.graph_builder)
402
403 # ____________________________________________________________
404
405 if __name__ == '__main__':
406 if '--text' in sys.argv:
407 sys.argv.remove('--text')
408 showgraph = False
409 else:
410 showgraph = True
411 if len(sys.argv) != 2:
412 print(__doc__, file=sys.stderr)
413 sys.exit(2)
414 #
415 import cStringIO
416 from rpython.tool import logparser
417 log1 = logparser.parse_log_file(sys.argv[1])
418 text1 = logparser.extract_category(log1, catprefix='jit-backend-dump')
419 f = cStringIO.StringIO()
420 f.writelines(text1)
421 f.seek(0)
422 del log1, text1
423 #
424 world = World()
425 world.parse(f)
426 if showgraph:
427 world.find_cross_references()
428 world.show(showtext=True)
429 else:
430 world.showtextonly()