Debian Codegraph @

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