Debian Codegraph @

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