Debian Codegraph @

terps/glulxe/profile-analyze.py

raw symbols SCIP
1 #!/usr/bin/python
2
3 from __future__ import print_function
4
5 """
6 This script reads in the profile-raw file generated by Glulxe profiling,
7 and lists the ten most costly functions. (In terms of how much total time
8 was spent inside each function. If a function calls other functions, the
9 time spent in them is not charged to the parent; that is, a function
10 which does nothing but call other functions will be considered uncostly.)
11
12 Optionally, this script can also read the debug output of the Inform 6
13 compiler (or the assembly output), and use that to figure out the
14 names of all the functions that were profiled. Both the old and new
15 (Inform 6.33) debug file format are supported.
16
17 You can also generate profiling output in the same form as dumbfrotz's
18 Z-machine profiling output. (If that happens to be what you want.) Use
19 the --dumbfrotz argument.
20
21 Using this script is currently a nuisance. The requirements:
22
23 - You must compile Glulxe with profiling (the VM_PROFILING compile-time
24 option).
25 - (If you want function names) you should compile your Inform 6 source
26 using the -k switch. This generates a "gameinfo.dbg" file.
27 - Run Glulxe, using the "--profile profile-raw" option. (Optionally,
28 also the "--profcalls" option.) Play some of the game, and quit. This
29 generates a data file called "profile-raw".
30 - Run this script, giving gameinfo.dbg and profile-raw as arguments.
31 - You can provide "--glk dispatch_dump.xml" as an optional extra argument.
32 This file gives the names of Glk functions; it is available from
33 https://github.com/erkyrath/glk-dev/tree/master/dispatch_dump .
34
35 To sum up, in command-line form:
36
37 % inform -G -k game.inf
38 % glulxe --profile profile-raw game.ulx
39 % python profile-analyze.py profile-raw gameinfo.dbg --glk dispatch_dump.xml
40
41 You can replace the debug output with the assembly output of the Inform
42 compiler, which you get with the -a switch. Save the output and use it
43 instead of the debug file:
44
45 % inform -G -a game.inf > game.asm
46 % glulxe --profile profile-raw game.ulx
47 % python profile-analyze.py profile-raw game.asm --glk dispatch_dump.xml
48
49 * The output:
50
51 The output will be a list of ten functions, showing how much time and
52 how many CPU cycles each one cost. Both the function's own cost and its
53 cost including children (the functions it calls itself) are shown.
54
55 (The top function is generally @glk_$c0 (or @glk_select). This just means
56 that the game spent a lot of time waiting for user input.)
57
58 You can change how many functions are listed with the --count option.
59 You can change the sorting criterion with the --sort option: the options
60 are self_time, self_ops, total_time, total_ops, and call_count.
61
62 * The limitations:
63
64 The profiling code is not smart about VM operations that rearrange the
65 call stack. In fact, it's downright stupid. @restart, @restore,
66 @restoreundo, or @throw will kill the interpreter.
67
68 The old debug file format (Inform 6.32 and earlier) does not work correctly
69 with game files larger than 16 megabytes.
70
71 If you leave off the "--glk dispatch_dump.xml" argument, everything will
72 still work, but @glk function entries will be listed by number rather
73 than by name.
74
75 If you included the "--profcalls" argument when running Glulxe, the
76 function information will include the number of times it called, and was
77 called by, every other function. This is rather slow, so it distorts
78 the function timing information. Only use "--profcalls" when you are
79 interested in specific call patterns (i.e., trying to identify where
80 a particular function is being called from).
81
82 * Interactive browsing:
83
84 You can explore the profiling data in more detail by running the script
85 interactively:
86
87 % python -i profile-analyze.py profile-raw game.asm --glk dispatch_dump.xml
88
89 After it runs, you'll be left at a Python prompt. You might want to list
90 functions sorted in other ways:
91
92 >>> list_by('total_time') # top 10 by total time including children
93 >>> list_by('total_ops') # top 10 by total CPU cycles including children
94 >>> list_by('self_ops', 20) # top 20 by CPU cycles excluding children
95
96 You can also dig into the data directly. The environment will contain
97 mappings called "functions" (mapping addresses to function objects), and
98 "function_names" (names to function objects).
99
100 >>> functions[0x3c]
101 <Function $3c 'Main__'>
102 >>> function_names['Main__']
103 <Function $3c 'Main__'>
104 >>> function_names['Main__'].dump()
105 Main__:
106 at $00003c (line 0); called 1 times
107 0.000067 sec (1 ops) spent executing
108 6.273244 sec (117578 ops) including child calls
109 >>> function_names['Main__'].show_calls()
110 Main__:
111 at $00003c (line 0); called 1 times:
112 made 1 calls to other functions:
113 1 to <Function $48 "Main">
114
115 (Again, the show_calls() information is only available if you use the
116 "--profcalls" argument when running Glulxe.)
117
118 A Function object has lots of attributes:
119
120 addr=INT: The VM address of the function (in hex).
121 hexaddr=STRING: The VM address of the function in hex (as a string).
122 name=STRING: The function's name, or '<???>' if the function is
123 not known (veneer functions).
124 linenum=INT: The line number of the function from the source code,
125 or 0 if it is not derived from source (Main__, etc).
126 call_count=INT: The number of times the function was called.
127 accel_count=INT: The number of times the function was called with
128 acceleration.
129 total_time=FLOAT: The amount of time spent during all calls to the
130 function (in seconds, as a floating-point value).
131 total_ops=INT: The number of opcodes executed during all calls to
132 the function.
133 self_time=FLOAT: The amount of time spent during all calls to the
134 function, excluding time spent in subcalls (functions called *by* the
135 function).
136 self_ops=INT: The number of opcodes executed during all calls to
137 the function, excluding time spent in subcalls.
138 max_depth=INT: The deepest this function has been nested on the
139 stack, during any call.
140 max_stack_use=INT: The greatest number of words on the stack, during
141 any call. (This is measured when the function returns, so it may
142 not capture the peak stack usage. If a function never returns, e.g.
143 Main__(), then this value is approximate.)
144
145 (The self_time is the "cost" used for the original listing.)
146
147 Note that if a function does not make any function calls, total_time
148 will be the same as self_time (and total_ops the same as self_ops).
149
150 Some of the function entries refer to special interpreter operations.
151 (These have high addresses, outside the range of normal game files.)
152 Functions with addresses in the 0xE0000000 range are the interpreter's
153 output opcodes: @streamchar, @streamunichar, @streamnum, @streamstr.
154
155 Functions with addresses in the 0xF0000000 range are @glk opcode calls.
156 The number in the lower bits specifies which Glk function was called.
157 You will always see a large self_time for function 0xF00000C0; this
158 represents all the time spent waiting for input in glk_select().
159
160 (Both the 0xE0000000 and 0xF0000000 entries represent time spent in the
161 Glk library, but they get there by different code paths.)
162
163 The function with the lowest address is the top-level Main__()
164 function generated by the compiler. Its total_time is the running time
165 of the entire program; its total_ops is the number of opcodes executed
166 by the entire program; its max_depth is zero.
167
168 * Debug file browsing:
169
170 If you just want to browse an Inform debug file, and bypass all the
171 profiling stuff, just do:
172
173 # python -i profile-analyze.py -d gameinfo.dbg
174
175 This will leave you at a Python prompt. The global "debugfile" contains
176 the parsed debug information, which you can browse:
177
178 >>> debugfile.arrays[0]
179 <Array "gg_event", 4 els of 4 bytes (16 total), at 160940
180 (<SourceLoc "parserm" line 96>)>
181
182 """
183
184 import sys, os.path
185 import optparse
186 import io
187 import xml.sax
188 from struct import unpack
189 from chunk import Chunk
190
191 popt = optparse.OptionParser(usage='profile-analyze.py [options] profile-raw [ gameinfo.dbg | game.asm ]')
192
193 popt.add_option('--glk',
194 action='store', dest='dispatchfile', metavar='DISPATCH_DUMP',
195 help='path to dispatch_dump.xml file (optional)')
196 popt.add_option('--dumbfrotz',
197 action='store_true', dest='dumbfrotz',
198 help='use dumbfrotz-compatible output format')
199 popt.add_option('-d', '--debug',
200 action='store_true', dest='debugonly',
201 help='read only the debug data, no profile data')
202 popt.add_option('-c', '--count',
203 action='store', dest='listcount',
204 type=int, default=10,
205 help='list the N slowest functions')
206 popt.add_option('-s', '--sort',
207 action='store', dest='listsort',
208 type=str, default='self_time',
209 help='sort criterion for functions (self_time, self_ops, total_time, total_ops, call_count)')
210
211 (opts, args) = popt.parse_args()
212
213 if (not args):
214 print('Usage: profile-analyze.py [--dumbfrotz] [--glk dispatch_dump.xml] profile-raw [ gameinfo.dbg | game.asm ]')
215 sys.exit(1)
216
217 profile_raw = None
218 game_file_data = None
219
220 if not opts.debugonly:
221 # Normal operation
222 profile_raw = args[0]
223 if (not os.path.exists(profile_raw)):
224 print('File not readable:', profile_raw)
225 sys.exit(1)
226
227 if (len(args) >= 2):
228 game_file_data = args[1]
229 if (not os.path.exists(game_file_data)):
230 print('File not readable:', game_file_data)
231 sys.exit(1)
232 else:
233 # Debug-only operation
234 game_file_data = args[0]
235 if (not os.path.exists(game_file_data)):
236 print('File not readable:', game_file_data)
237 sys.exit(1)
238
239 if (opts.dispatchfile):
240 if (not os.path.exists(opts.dispatchfile)):
241 print('File not readable:', opts.dispatchfile)
242 sys.exit(1)
243
244 special_functions = {
245 0xE0000001: 'streamchar',
246 0xE0000002: 'streamunichar',
247 0xE0000003: 'streamnum',
248 0xE0000004: 'streamstr',
249 }
250
251 glk_functions = {}
252
253 functions = None
254 callcounts = None
255 sourcemap = None
256
257 class Function:
258 def __init__(self, addr, hexaddr, attrs):
259 self.addr = addr
260 self.hexaddr = hexaddr
261 val = special_functions.get(addr)
262 if (addr >= 0xF0000000):
263 name = glk_functions.get(addr-0xF0000000)
264 if (not name):
265 name = hex(addr-0xF0000000)[2:]
266 name = '$' + name.replace('L', '')
267 self.name = '<@glk_' + name + '>'
268 self.special = True
269 elif (val is None):
270 self.name = '<???>'
271 self.special = False
272 else:
273 self.name = '<@' + val + '>'
274 self.special = True
275 self.linenum = 0
276 self.call_count = int(attrs['call_count'])
277 self.accel_count = 0
278 val = attrs.get('accel_count')
279 if (val):
280 self.accel_count = int(val)
281 self.total_ops = int(attrs['total_ops'])
282 self.total_time = float(attrs['total_time'])
283 self.self_ops = int(attrs['self_ops'])
284 self.self_time = float(attrs['self_time'])
285 val = attrs.get('max_depth')
286 if (val):
287 self.max_depth = int(val)
288 val = attrs.get('max_stack_use')
289 if (val):
290 self.max_stack_use = int(val)
291 self.incalls = {}
292 self.outcalls = {}
293
294 def __repr__(self):
295 return '<Function $' + self.hexaddr + ' "' + self.name + '">'
296
297 def dump(self):
298 print('%s:' % (self.name,))
299 print(' %s' % (self.get_summary(),))
300 print(' %.6f sec (%d ops) spent executing' % (self.self_time, self.self_ops))
301 print(' %.6f sec (%d ops) including child calls' % (self.total_time, self.total_ops))
302
303 def dump_dumbfrotz_style(self):
304 percent1 = ' '
305 percent2 = ' '
306 pc1 = int(100*(float(self.self_ops)/float(ops_executed)))
307 pc2 = int(100*(float(self.total_ops)/float(ops_executed)))
308 if (pc1 > 0):
309 percent1 = "%3d%%" % pc1
310 if (pc2 > 0):
311 percent2 = "%3d%%" % pc2
312 print('%-36s %s %-10lu %s %-10lu %-10lu %-4d' % (self.name, percent1, self.self_ops, percent2, self.total_ops, self.call_count, self.max_depth))
313
314 def get_summary(self):
315 res = 'at $%06x' % (self.addr,)
316 if (self.linenum):
317 res += ' (line %d)' % (self.linenum,)
318 res += '; called %d times' % (self.call_count,)
319 if (self.accel_count):
320 res += ' (%d accelerated)' % (self.accel_count,)
321 return res
322
323 def show_calls(self):
324 if not callcounts:
325 raise Exception('Profile data did not include call counts!')
326 print('%s:' % (self.name,))
327 print(' %s:' % (self.get_summary(),))
328 ls = list(self.incalls.items())
329 ls.sort() # by addr
330 for (addr, count) in ls:
331 func = functions.get(addr, '<???>')
332 print(' %d from %s' % (count, func))
333 ls = list(self.outcalls.items())
334 ls.sort() # by addr
335 val = sum([count for (addr, count) in ls])
336 print(' made %d calls to other functions:' % (val,))
337 for (addr, count) in ls:
338 func = functions.get(addr, '<???>')
339 print(' %d to %s' % (count, func))
340
341 class DispatchDumpHandler(xml.sax.handler.ContentHandler):
342 def startElement(self, name, attrs):
343 if (name == 'function'):
344 addr = int(attrs['id'])
345 glk_functions[addr] = str(attrs['name'])
346
347 class ProfileRawHandler(xml.sax.handler.ContentHandler):
348 def startElement(self, name, attrs):
349 global functions, callcounts
350
351 if (name == 'profile'):
352 functions = {}
353 callcounts = {}
354 if (name == 'function'):
355 hexaddr = attrs.get('addr')
356 addr = int(hexaddr, 16)
357 func = Function(addr, hexaddr, attrs)
358 functions[addr] = func
359 if (name == 'calls'):
360 hexaddr = attrs.get('fromaddr')
361 fromaddr = int(hexaddr, 16)
362 hexaddr = attrs.get('toaddr')
363 toaddr = int(hexaddr, 16)
364 count = int(attrs.get('count'))
365 callcounts[(fromaddr, toaddr)] = count
366
367 class SFrameHandler:
368 def __init__(self, tag, parent=None, depth=None, children={}, active=None, handler=None):
369 self.tag = tag
370 self.parent = parent
371 self.depth = depth
372 self.children = children
373 self.handler = handler
374 if active is None:
375 active = (handler is not None)
376 self.active = active
377
378 class SFrameFrame:
379 def __init__(self, name, attrs, depth):
380 self.name = name
381 self.attrs = attrs
382 self.depth = depth
383 self.children = None
384 self.handler = None
385 self.accumchar = None
386 self.accumobj = None
387
388 def final(self):
389 self.name = None
390 self.attrs = None
391 self.children = None
392 self.handler = None
393 self.accumchar = None
394 self.accumobj = None
395
396 class SimpleXMLFrame(xml.sax.handler.ContentHandler):
397 def __init__(self):
398 xml.sax.handler.ContentHandler.__init__(self)
399 self.sstack = None
400 self.taghandlers = {}
401 self.init()
402
403 def startDocument(self):
404 self.sstack = []
405
406 def endDocument(self):
407 assert len(self.sstack) == 0
408
409 def startElement(self, name, attrs):
410 parframe = None
411 if self.sstack:
412 parframe = self.sstack[-1]
413
414 frame = SFrameFrame(name, attrs, len(self.sstack))
415 self.sstack.append(frame)
416
417 parhan = None
418 if parframe and parframe.children:
419 parhan = parframe.children.get(name)
420 if parhan is not None:
421 if type(parhan) is list:
422 parhan = parhan[0]
423 frame.handler = parhan
424 if parhan in (int, str):
425 frame.accumchar = []
426 elif parhan is ():
427 taghan = self.taghandlers[name]
428 frame.handler = taghan
429 frame.children = taghan.children
430 frame.accumobj = {}
431 elif callable(parhan):
432 frame.handler = parhan
433 frame.accumchar = []
434 else:
435 raise Exception('unknown element handler thingie: %s' % (parhan,))
436 else:
437 taghan = self.taghandlers.get(name)
438 if taghan:
439 active = taghan.active
440 if active:
441 if taghan.parent is not None:
442 if not (parframe and parframe.name == taghan.parent):
443 active = False
444 if taghan.depth is not None:
445 if not (frame.depth == taghan.depth):
446 active = False
447 if active:
448 frame.handler = taghan
449 frame.children = taghan.children
450 frame.accumobj = {}
451
452 def characters(self, data):
453 frame = self.sstack[-1]
454 if frame.accumchar is not None:
455 frame.accumchar.append(data)
456
457 def endElement(self, name):
458 frame = self.sstack.pop()
459 assert frame.name == name
460
461 res = None
462 if frame.handler is None:
463 pass
464 elif frame.handler is str:
465 res = ''.join(frame.accumchar)
466 elif frame.handler is int:
467 val = ''.join(frame.accumchar)
468 res = int(val.strip())
469 elif isinstance(frame.handler, SFrameHandler):
470 if frame.handler.handler:
471 res = frame.handler.handler(frame.name, frame.attrs, frame.accumobj)
472 else:
473 res = frame.accumobj
474 elif callable(frame.handler):
475 val = ''.join(frame.accumchar)
476 res = frame.handler(frame.name, frame.attrs, val)
477 else:
478 raise Exception('unknown element handler thingie: %s' % (frame.handler,))
479
480 frame.final()
481
482 if self.sstack and res is not None:
483 parframe = self.sstack[-1]
484 if parframe.accumobj is not None:
485 if type(parframe.children.get(name)) is list:
486 subls = parframe.accumobj.get(name)
487 if subls:
488 subls.append(res)
489 else:
490 subls = [ res ]
491 parframe.accumobj[name] = subls
492 else:
493 parframe.accumobj[name] = res
494
495 def handle_tag(self, tag, parent=None, depth=None, children={},
496 active=None, handler=None):
497 self.taghandlers[tag] = SFrameHandler(tag, parent, depth, children, active, handler)
498
499 class NewDebugFile:
500 def __init__(self):
501 self.sourcefiles = {}
502 self.constants = {}
503 self.objects = []
504 self.globals = []
505 self.arrays = []
506 self.functions = []
507
508 class NewDebugSourceFile:
509 def __init__(self, index, filename):
510 self.index = index
511 self.filename = filename
512 def __repr__(self):
513 return '<SourceFile %d: "%s">' % (self.index, self.filename,)
514
515 class NewDebugConstant:
516 def __init__(self, ident, value=None, sourceloc=None):
517 self.id = ident
518 self.value = value
519 if not sourceloc:
520 sourceloc = 'compiler'
521 self.sourceloc = sourceloc
522 def __repr__(self):
523 return '<Constant "%s": %d (%s)>' % (self.id, self.value, self.sourceloc)
524
525 class NewDebugObject:
526 def __init__(self, ident, value=None, sourceloc=None, artificial=False):
527 self.id = ident
528 self.value = value
529 if not sourceloc:
530 sourceloc = 'compiler'
531 self.sourceloc = sourceloc
532 self.artificial = '*' if artificial else ''
533 def __repr__(self):
534 return '<Object "%s"%s: %d (%s)>' % (self.id, self.artificial, self.value, self.sourceloc)
535
536 class NewDebugGlobal:
537 def __init__(self, ident, address, sourceloc=None):
538 self.id = ident
539 self.address = address
540 if not sourceloc:
541 sourceloc = 'compiler'
542 self.sourceloc = sourceloc
543 def __repr__(self):
544 return '<Global "%s" at %d (%s)>' % (self.id, self.address, self.sourceloc)
545
546 class NewDebugArray:
547 def __init__(self, ident, address, bytecount, bytesperel, sourceloc=None):
548 self.id = ident
549 self.address = address
550 self.bytecount = bytecount
551 self.bytesperel = bytesperel
552 self.elcount = bytecount / bytesperel
553 if not sourceloc:
554 sourceloc = 'compiler'
555 self.sourceloc = sourceloc
556 def __repr__(self):
557 return '<Array "%s", %d els of %d bytes (%d total), at %d (%s)>' % (self.id, self.elcount, self.bytesperel, self.bytecount, self.address, self.sourceloc)
558
559 class NewDebugFunction:
560 def __init__(self, ident, address, args=(), sourceloc=None, artificial=False):
561 self.id = ident
562 self.address = address
563 self.args = args
564 if not sourceloc:
565 sourceloc = 'veneer'
566 self.sourceloc = sourceloc
567 self.artificial = '*' if artificial else ''
568 def __repr__(self):
569 return '<Function "%s"%s at %d (%s)>' % (self.id, self.artificial, self.address, self.sourceloc)
570
571 class NewDebugSourceLoc:
572 def __init__(self, line, fileref=None):
573 self.line = line
574 self.fileref = fileref
575 def __repr__(self):
576 if (isinstance(self.fileref, NewDebugSourceFile)):
577 return '<SourceLoc "%s" line %d>' % (self.fileref.filename, self.line)
578 elif (self.fileref):
579 return '<SourceLoc file #%d, line %d>' % (self.fileref, self.line)
580 else:
581 return '<SourceLoc line %d>' % (self.line,)
582
583 class NewDebugHandler(SimpleXMLFrame):
584 def init(self):
585 self._debugfile = NewDebugFile()
586
587 self.handle_tag('source', parent='inform-story-file',
588 children={'given-path':str},
589 handler=self.handle_source_file)
590 self.handle_tag('constant', parent='inform-story-file',
591 children={'identifier':str, 'value':int, 'source-code-location':()},
592 handler=self.handle_constant)
593 self.handle_tag('object', parent='inform-story-file',
594 children={'identifier':self.handle_ident_artificial, 'value':int, 'source-code-location':()},
595 handler=self.handle_object)
596 self.handle_tag('global-variable', parent='inform-story-file',
597 children={'identifier':str, 'address':int, 'source-code-location':()},
598 handler=self.handle_global_var)
599 self.handle_tag('array', parent='inform-story-file',
600 children={'identifier':str, 'value':int, 'byte-count':int, 'bytes-per-element':int, 'source-code-location':()},
601 handler=self.handle_array)
602 self.handle_tag('routine', parent='inform-story-file',
603 children={'identifier':self.handle_ident_artificial, 'address':int, 'source-code-location':(), 'local-variable':[()]},
604 handler=self.handle_function)
605 self.handle_tag('source-code-location', active=False,
606 children={'line':int, 'file-index':int},
607 handler=self.handle_source_code_loc)
608 self.handle_tag('local-variable',
609 children={'identifier':str})
610
611 def debugfile(self):
612 return self._debugfile
613
614 def handle_source_file(self, name, attrs, obj):
615 srcfile = NewDebugSourceFile(int(attrs['index']), obj['given-path'])
616 self._debugfile.sourcefiles[srcfile.index] = srcfile
617
618 def handle_constant(self, name, attrs, obj):
619 con = NewDebugConstant(obj['identifier'], obj.get('value'), obj.get('source-code-location'))
620 self._debugfile.constants[con.id] = con
621
622 def handle_object(self, name, attrs, obj):
623 (ident, artificial) = obj['identifier']
624 con = NewDebugObject(ident, obj.get('value'), obj.get('source-code-location'), artificial=artificial)
625 self._debugfile.objects.append(con)
626
627 def handle_global_var(self, name, attrs, obj):
628 glob = NewDebugGlobal(obj['identifier'], obj['address'], obj.get('source-code-location'))
629 self._debugfile.globals.append(glob)
630
631 def handle_array(self, name, attrs, obj):
632 arr = NewDebugArray(obj['identifier'], obj['value'], obj['byte-count'], obj['bytes-per-element'], obj.get('source-code-location'))
633 self._debugfile.arrays.append(arr)
634
635 def handle_function(self, name, attrs, obj):
636 (ident, artificial) = obj['identifier']
637 args = obj.get('local-variable')
638 if not args:
639 args = ()
640 else:
641 args = tuple([ loc['identifier'] for loc in args ])
642 func = NewDebugFunction(ident, obj['address'], args, obj.get('source-code-location'), artificial=artificial)
643 self._debugfile.functions.append(func)
644
645 def handle_ident_artificial(self, name, attrs, obj):
646 artificial = attrs.get('artificial')
647 return (obj.strip(), artificial)
648
649 def handle_source_code_loc(self, name, attrs, obj):
650 fileref = obj.get('file-index')
651 if fileref is not None:
652 srcfile = self._debugfile.sourcefiles.get(fileref)
653 if srcfile:
654 fileref = srcfile
655 return NewDebugSourceLoc(obj['line'], fileref)
656
657
658 def parse_inform_assembly(fl):
659 global sourcemap
660 sourcemap = {}
661
662 lasttup = None
663 while True:
664 ln = fl.readline()
665 if (not ln):
666 break
667 ln = ln.strip()
668 ls = ln.split()
669 if (lasttup and not ls):
670 (linenum, funcname, addr) = lasttup
671 sourcemap[addr] = (linenum, funcname)
672 lasttup = None
673 try:
674 if (len(ls) >= 4 and ls[2] == '[' and ls[1].startswith('+')):
675 linenum = int(ls[0])
676 funcname = ls[3]
677 addr = int(ls[1][1:], 16)
678 lasttup = (linenum, funcname, addr)
679 except ValueError:
680 pass
681
682 class InformFunc:
683 def __init__(self, funcnum):
684 self.funcnum = funcnum
685 self.name = '<???>'
686 self.addr = 0
687 self.linenum = None
688 self.endaddr = None
689 self.endlinenum = None
690 self.locals = None
691 self.seqpts = None
692 def __repr__(self):
693 return '<InformFunc $' + hex(self.addr)[2:] + ' ' + repr(self.name) + '>'
694
695 class DebugFile:
696 def __init__(self, fl):
697 self.files = {}
698 self.functions = {}
699 self.function_names = {}
700 self.classes = []
701 self.objects = {}
702 self.arrays = {}
703 self.globals = {}
704 self.properties = {}
705 self.attributes = {}
706 self.actions = {}
707 self.fake_actions = {}
708 self.map = {}
709 self.header = None
710
711 dat = fl.read(2)
712 val = unpack('>H', dat)[0]
713 if (val != 0xDEBF):
714 raise ValueError('not an Inform debug file')
715
716 dat = fl.read(2)
717 self.debugversion = unpack('>H', dat)[0]
718 dat = fl.read(2)
719 self.informversion = unpack('>H', dat)[0]
720
721 rectable = {
722 1: self.read_file_rec,
723 2: self.read_class_rec,
724 3: self.read_object_rec,
725 4: self.read_global_rec,
726 5: self.read_attr_rec,
727 6: self.read_prop_rec,
728 7: self.read_fake_action_rec,
729 8: self.read_action_rec,
730 9: self.read_header_rec,
731 10: self.read_lineref_rec,
732 11: self.read_routine_rec,
733 12: self.read_array_rec,
734 13: self.read_map_rec,
735 14: self.read_routine_end_rec,
736 }
737
738 while True:
739 dat = fl.read(1)
740 rectype = unpack('>B', dat)[0]
741 if (rectype == 0):
742 break
743 recfunc = rectable.get(rectype)
744 if (not recfunc):
745 raise ValueError('unknown debug record type: %d' % (rectype,))
746 recfunc(fl)
747
748 for func in self.functions.values():
749 self.function_names[func.name] = func
750
751 def read_file_rec(self, fl):
752 dat = fl.read(1)
753 filenum = unpack('>B', dat)[0]
754 includename = self.read_string(fl)
755 realname = self.read_string(fl)
756 self.files[filenum] = ( includename, realname )
757
758 def read_class_rec(self, fl):
759 name = self.read_string(fl)
760 start = self.read_linenum(fl)
761 end = self.read_linenum(fl)
762 self.classes.append( (name, start, end) )
763
764 def read_object_rec(self, fl):
765 dat = fl.read(2)
766 num = unpack('>H', dat)[0]
767 name = self.read_string(fl)
768 start = self.read_linenum(fl)
769 end = self.read_linenum(fl)
770 self.objects[num] = (name, start, end)
771
772 def read_global_rec(self, fl):
773 dat = fl.read(1)
774 num = unpack('>B', dat)[0]
775 name = self.read_string(fl)
776 self.globals[num] = name
777
778 def read_array_rec(self, fl):
779 dat = fl.read(2)
780 num = unpack('>H', dat)[0]
781 name = self.read_string(fl)
782 self.arrays[num] = name
783
784 def read_attr_rec(self, fl):
785 dat = fl.read(2)
786 num = unpack('>H', dat)[0]
787 name = self.read_string(fl)
788 self.attributes[num] = name
789
790 def read_prop_rec(self, fl):
791 dat = fl.read(2)
792 num = unpack('>H', dat)[0]
793 name = self.read_string(fl)
794 self.properties[num] = name
795
796 def read_action_rec(self, fl):
797 dat = fl.read(2)
798 num = unpack('>H', dat)[0]
799 name = self.read_string(fl)
800 self.actions[num] = name
801
802 def read_fake_action_rec(self, fl):
803 dat = fl.read(2)
804 num = unpack('>H', dat)[0]
805 name = self.read_string(fl)
806 self.fake_actions[num] = name
807
808 def read_routine_rec(self, fl):
809 dat = fl.read(2)
810 funcnum = unpack('>H', dat)[0]
811 func = self.get_function(funcnum)
812
813 func.linenum = self.read_linenum(fl)
814 dat = fl.read(3)
815 addr = unpack('>I', b'\0'+dat)[0]
816 func.addr = int(addr)
817 func.name = self.read_string(fl)
818 locals = []
819 while True:
820 val = self.read_string(fl)
821 if (not val):
822 break
823 locals.append(val)
824 func.locals = locals
825
826 def read_lineref_rec(self, fl):
827 dat = fl.read(2)
828 funcnum = unpack('>H', dat)[0]
829 func = self.get_function(funcnum)
830
831 if (not func.seqpts):
832 func.seqpts = []
833
834 dat = fl.read(2)
835 count = unpack('>H', dat)[0]
836 for ix in range(count):
837 linenum = self.read_linenum(fl)
838 dat = fl.read(2)
839 addr = unpack('>H', dat)[0]
840 func.seqpts.append( (linenum, addr) )
841
842 def read_routine_end_rec(self, fl):
843 dat = fl.read(2)
844 funcnum = unpack('>H', dat)[0]
845 func = self.get_function(funcnum)
846
847 func.endlinenum = self.read_linenum(fl)
848 dat = fl.read(3)
849 addr = unpack('>I', b'\0'+dat)[0]
850 func.endaddr = int(addr)
851
852 def read_header_rec(self, fl):
853 dat = fl.read(64)
854 self.header = dat
855
856 def read_map_rec(self, fl):
857 while True:
858 name = self.read_string(fl)
859 if (not name):
860 break
861 dat = fl.read(3)
862 addr = unpack('>I', b'\0'+dat)[0]
863 addr = int(addr)
864 self.map[name] = addr
865
866 def read_linenum(self, fl):
867 dat = fl.read(4)
868 (funcnum, linenum, charnum) = unpack('>BHB', dat)
869 return (funcnum, linenum, charnum)
870
871 def read_string(self, fl):
872 val = b''
873 while True:
874 dat = fl.read(1)
875 if (dat == b'\0'):
876 return val.decode()
877 val += dat
878
879 def get_function(self, funcnum):
880 func = self.functions.get(funcnum)
881 if (not func):
882 func = InformFunc(funcnum)
883 self.functions[funcnum] = func
884 return func
885
886 # A simple I/O wrapper class: read a subrange of a (readable binary)
887 # file. We use this to treat a Blorb chunk as a readable file.
888 class BinaryRangeIO(io.RawIOBase):
889 def __init__(self, file, start, length):
890 self.file = file
891 self.start = start
892 self.length = length
893 self.offset = 0
894 self.file.seek(self.start)
895
896 def readable(self):
897 return True
898
899 def close(self):
900 self.file = None
901 io.RawIOBase.close(self)
902
903 def tell(self):
904 return self.offset
905
906 def readinto(self, dat):
907 count = len(dat)
908 if count > self.length - self.offset:
909 count = self.length - self.offset
910 newdat = self.file.read(count)
911 newlen = len(newdat)
912 dat[:newlen] = newdat
913 else:
914 newlen = self.file.readinto(dat)
915 self.offset += newlen
916 return newlen
917
918 def typestring(dat):
919 return "'" + dat.decode() + "'"
920
921 class BlorbChunk:
922 def __init__(self, formchunk, typ, start, len, formtype=None):
923 self.formchunk = formchunk
924 self.type = typ
925 self.start = start
926 self.len = len
927 self.formtype = formtype
928
929 def __repr__(self):
930 return '<BlorbChunk %s at %d, len %d>' % (typestring(self.type), self.start, self.len)
931
932 def data(self, max=None):
933 self.formchunk.seek(self.start)
934 toread = self.len
935 if (max is not None):
936 toread = min(self.len, max)
937 return self.formchunk.read(toread)
938
939 def describe(self):
940 if (not self.formtype):
941 return '%s (%d bytes, start %d)' % (typestring(self.type), self.len, self.start)
942 else:
943 return '%s/%s (%d+8 bytes, start %d)' % (typestring(self.type), typestring(self.formtype), self.len, self.start)
944
945 def blorb_find_debug_chunk(filename):
946 file = open(filename, 'rb')
947 formchunk = Chunk(file)
948 formchunk = formchunk
949
950 if (formchunk.getname() != b'FORM'):
951 raise Exception('This does not appear to be a Blorb file.')
952 formtype = formchunk.read(4)
953 if (formtype != b'IFRS'):
954 raise Exception('This does not appear to be a Blorb file.')
955
956 chunks = []
957 debugchunk = None
958
959 formlen = formchunk.getsize()
960 while formchunk.tell() < formlen:
961 chunk = Chunk(formchunk)
962 start = formchunk.tell()
963 size = chunk.getsize()
964 formtype = None
965 if chunk.getname() == b'FORM':
966 formtype = chunk.read(4)
967 subchunk = BlorbChunk(formchunk, chunk.getname(), start, size, formtype)
968 chunks.append(subchunk)
969 chunk.skip()
970 chunk.close()
971
972 for chunk in chunks:
973 if (chunk.type == b'Dbug'):
974 debugchunk = chunk
975
976 formchunk.close()
977 file.close()
978 file = None
979
980 return debugchunk
981
982
983 def list_by(key='self_time', limit=10):
984 ls = functions.values()
985 ls.sort(lambda x1, x2: cmp(getattr(x2, key), getattr(x1, key)))
986 for func in ls[:limit]:
987 func.dump()
988
989 # Read in the various files
990
991 if (opts.dispatchfile):
992 # Fills out the glk_functions global
993 xml.sax.parse(opts.dispatchfile, DispatchDumpHandler())
994
995 if (profile_raw):
996 # Fills out the functions global
997 xml.sax.parse(profile_raw, ProfileRawHandler())
998
999 need_function_address_offset = False
1000
1001 if (game_file_data):
1002 # Fill out the sourcemap global, by one of various methods
1003 fl = open(game_file_data, 'rb')
1004 val = fl.read(2)
1005 fl.close()
1006 if (not val):
1007 pass
1008 elif (val == b'\xde\xbf'):
1009 # Old-style Inform debug info.
1010 need_function_address_offset = True
1011 fl = open(game_file_data, 'rb')
1012 debugfile = DebugFile(fl)
1013 fl.close()
1014 sourcemap = {}
1015 for func in debugfile.functions.values():
1016 sourcemap[func.addr] = ( func.linenum[1], func.name )
1017 elif (val == b'<?'):
1018 # New-style Inform debug info.
1019 han = NewDebugHandler()
1020 xml.sax.parse(game_file_data, han)
1021 debugfile = han.debugfile()
1022 sourcemap = {}
1023 for func in debugfile.functions:
1024 linenum = 0
1025 if func.sourceloc and isinstance(func.sourceloc, NewDebugSourceLoc):
1026 linenum = func.sourceloc.line
1027 sourcemap[func.address] = ( linenum, func.id )
1028 elif (val == b'\x46\x4F'):
1029 # Looks like a Blorb file. Scan for a Dbug chunk.
1030 debugchunk = blorb_find_debug_chunk(game_file_data)
1031 if not debugchunk:
1032 raise Exception('This Blorb file has no Dbug chunk.')
1033 # Now we check the contents, which means repeating a
1034 # bunch of the above code.
1035 fl = open(game_file_data, 'rb')
1036 fl.seek(debugchunk.start+8)
1037 val = fl.read(2)
1038 if (val == b'\xde\xbf'):
1039 need_function_address_offset = True
1040 subfl = BinaryRangeIO(fl, debugchunk.start+8, debugchunk.len)
1041 debugfile = DebugFile(fl)
1042 subfl.close()
1043 sourcemap = {}
1044 for func in debugfile.functions.values():
1045 sourcemap[func.addr] = ( func.linenum[1], func.name )
1046 elif (val == b'<?'):
1047 subfl = BinaryRangeIO(fl, debugchunk.start+8, debugchunk.len)
1048 han = NewDebugHandler()
1049 xml.sax.parse(subfl, han)
1050 subfl.close()
1051 debugfile = han.debugfile()
1052 sourcemap = {}
1053 for func in debugfile.functions:
1054 linenum = 0
1055 if func.sourceloc and isinstance(func.sourceloc, NewDebugSourceLoc):
1056 linenum = func.sourceloc.line
1057 sourcemap[func.address] = ( linenum, func.id )
1058 else:
1059 raise Exception('Blorb Dbug chunk was not recognized.')
1060 fl.close()
1061 else:
1062 # Assume it's an Inform assembly dump.
1063 need_function_address_offset = True
1064 fl = open(game_file_data, 'rU')
1065 parse_inform_assembly(fl)
1066 fl.close()
1067
1068 if (profile_raw):
1069 # If there is profile data, display it.
1070
1071 source_start = min([ func.addr for func in functions.values()
1072 if not func.special ])
1073
1074 # For old debug formats, all the function addresses are relative to
1075 # the start of function memory. For the new format, they're all
1076 # correct as-is.
1077 if need_function_address_offset:
1078 function_address_offset = source_start
1079 else:
1080 function_address_offset = 0
1081
1082 if (not opts.dumbfrotz):
1083 print('Code segment begins at', hex(source_start))
1084 print(len(functions), 'called functions found in', profile_raw)
1085
1086 for (tup, count) in callcounts.items():
1087 (fromaddr, toaddr) = tup
1088 fromfunc = functions.get(fromaddr)
1089 tofunc = functions.get(toaddr)
1090 if (fromfunc):
1091 fromfunc.outcalls[toaddr] = count
1092 if (tofunc):
1093 tofunc.incalls[fromaddr] = count
1094
1095 if (sourcemap):
1096 badls = []
1097
1098 for (addr, func) in functions.items():
1099 if (func.special):
1100 continue
1101 tup = sourcemap.get(addr-function_address_offset)
1102 if (not tup):
1103 badls.append(addr)
1104 continue
1105 (linenum, funcname) = tup
1106 func.name = funcname
1107 func.linenum = linenum
1108
1109 if (not opts.dumbfrotz):
1110 if (badls):
1111 print(len(badls), 'functions from', profile_raw, 'did not appear in asm (veneer functions)')
1112
1113 function_names = {}
1114 for func in functions.values():
1115 function_names[func.name] = func
1116
1117 if (sourcemap):
1118 uncalled_funcs = [ funcname for (addr, (linenum, funcname)) in sourcemap.items() if (addr+function_address_offset) not in functions ]
1119 if (not opts.dumbfrotz):
1120 print(len(uncalled_funcs), 'functions found in', game_file_data, 'were never called')
1121
1122 if (opts.dumbfrotz):
1123 ls = functions.values()
1124 ls.sort(lambda x1, x2: cmp(x2.total_ops, x1.total_ops))
1125 ops_executed = 0
1126 routine_calls = 0
1127 max_stack_use = max([func.max_stack_use for func in ls])
1128 for func in ls:
1129 if (func.total_ops > ops_executed):
1130 ops_executed = func.total_ops
1131 routine_calls = routine_calls + func.call_count
1132 print('Total opcodes: %lu' % ops_executed)
1133 print('Total routine calls: %lu' % routine_calls)
1134 print('Max. stack usage: %li' % max_stack_use)
1135 print('')
1136 print('%-35s %-10s %-10s %-10s %-4s' % ('Routine', 'Ops', 'Ops(+Subs)', 'Calls', 'Nest'))
1137 for func in ls:
1138 func.dump_dumbfrotz_style()
1139 else:
1140 print('Functions that consumed the most time (excluding children):')
1141 ls = list(functions.values())
1142
1143 sortfunc = lambda fn:-fn.self_time
1144 if (opts.listsort in ('self_time', 'self-time', 'selftime')):
1145 sortfunc = lambda fn:-fn.self_time
1146 elif (opts.listsort in ('self_ops', 'self-ops', 'selfops')):
1147 sortfunc = lambda fn:-fn.self_ops
1148 elif (opts.listsort in ('total_time', 'total-time', 'totaltime')):
1149 sortfunc = lambda fn:-fn.total_time
1150 elif (opts.listsort in ('total_ops', 'total-ops', 'totalops')):
1151 sortfunc = lambda fn:-fn.total_ops
1152 elif (opts.listsort in ('call_count', 'call-count', 'callcount')):
1153 sortfunc = lambda fn:-fn.call_count
1154
1155 ls.sort(key=sortfunc)
1156 for func in ls[0 : opts.listcount]:
1157 func.dump()