dis.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. """Disassembler of Python byte code into mnemonics."""
  2. import sys
  3. import types
  4. from opcode import *
  5. from opcode import __all__ as _opcodes_all
  6. __all__ = ["dis","disassemble","distb","disco"] + _opcodes_all
  7. del _opcodes_all
  8. def dis(x=None):
  9. """Disassemble classes, methods, functions, or code.
  10. With no argument, disassemble the last traceback.
  11. """
  12. if x is None:
  13. distb()
  14. return
  15. if type(x) is types.InstanceType:
  16. x = x.__class__
  17. if hasattr(x, 'im_func'):
  18. x = x.im_func
  19. if hasattr(x, 'func_code'):
  20. x = x.func_code
  21. if hasattr(x, '__dict__'):
  22. items = x.__dict__.items()
  23. items.sort()
  24. for name, x1 in items:
  25. if type(x1) in (types.MethodType,
  26. types.FunctionType,
  27. types.CodeType,
  28. types.ClassType):
  29. print "Disassembly of %s:" % name
  30. try:
  31. dis(x1)
  32. except TypeError, msg:
  33. print "Sorry:", msg
  34. print
  35. elif hasattr(x, 'co_code'):
  36. disassemble(x)
  37. elif isinstance(x, str):
  38. disassemble_string(x)
  39. else:
  40. raise TypeError, \
  41. "don't know how to disassemble %s objects" % \
  42. type(x).__name__
  43. def distb(tb=None):
  44. """Disassemble a traceback (default: last traceback)."""
  45. if tb is None:
  46. try:
  47. tb = sys.last_traceback
  48. except AttributeError:
  49. raise RuntimeError, "no last traceback to disassemble"
  50. while tb.tb_next: tb = tb.tb_next
  51. disassemble(tb.tb_frame.f_code, tb.tb_lasti)
  52. def disassemble(co, lasti=-1):
  53. """Disassemble a code object."""
  54. code = co.co_code
  55. labels = findlabels(code)
  56. linestarts = dict(findlinestarts(co))
  57. n = len(code)
  58. i = 0
  59. extended_arg = 0
  60. free = None
  61. while i < n:
  62. c = code[i]
  63. op = ord(c)
  64. if i in linestarts:
  65. if i > 0:
  66. print
  67. print "%3d" % linestarts[i],
  68. else:
  69. print ' ',
  70. if i == lasti: print '-->',
  71. else: print ' ',
  72. if i in labels: print '>>',
  73. else: print ' ',
  74. print repr(i).rjust(4),
  75. print opname[op].ljust(20),
  76. i = i+1
  77. if op >= HAVE_ARGUMENT:
  78. oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg
  79. extended_arg = 0
  80. i = i+2
  81. if op == EXTENDED_ARG:
  82. extended_arg = oparg*65536L
  83. print repr(oparg).rjust(5),
  84. if op in hasconst:
  85. print '(' + repr(co.co_consts[oparg]) + ')',
  86. elif op in hasname:
  87. print '(' + co.co_names[oparg] + ')',
  88. elif op in hasjrel:
  89. print '(to ' + repr(i + oparg) + ')',
  90. elif op in haslocal:
  91. print '(' + co.co_varnames[oparg] + ')',
  92. elif op in hascompare:
  93. print '(' + cmp_op[oparg] + ')',
  94. elif op in hasfree:
  95. if free is None:
  96. free = co.co_cellvars + co.co_freevars
  97. print '(' + free[oparg] + ')',
  98. print
  99. def disassemble_string(code, lasti=-1, varnames=None, names=None,
  100. constants=None):
  101. labels = findlabels(code)
  102. n = len(code)
  103. i = 0
  104. while i < n:
  105. c = code[i]
  106. op = ord(c)
  107. if i == lasti: print '-->',
  108. else: print ' ',
  109. if i in labels: print '>>',
  110. else: print ' ',
  111. print repr(i).rjust(4),
  112. print opname[op].ljust(15),
  113. i = i+1
  114. if op >= HAVE_ARGUMENT:
  115. oparg = ord(code[i]) + ord(code[i+1])*256
  116. i = i+2
  117. print repr(oparg).rjust(5),
  118. if op in hasconst:
  119. if constants:
  120. print '(' + repr(constants[oparg]) + ')',
  121. else:
  122. print '(%d)'%oparg,
  123. elif op in hasname:
  124. if names is not None:
  125. print '(' + names[oparg] + ')',
  126. else:
  127. print '(%d)'%oparg,
  128. elif op in hasjrel:
  129. print '(to ' + repr(i + oparg) + ')',
  130. elif op in haslocal:
  131. if varnames:
  132. print '(' + varnames[oparg] + ')',
  133. else:
  134. print '(%d)' % oparg,
  135. elif op in hascompare:
  136. print '(' + cmp_op[oparg] + ')',
  137. print
  138. disco = disassemble # XXX For backwards compatibility
  139. def findlabels(code):
  140. """Detect all offsets in a byte code which are jump targets.
  141. Return the list of offsets.
  142. """
  143. labels = []
  144. n = len(code)
  145. i = 0
  146. while i < n:
  147. c = code[i]
  148. op = ord(c)
  149. i = i+1
  150. if op >= HAVE_ARGUMENT:
  151. oparg = ord(code[i]) + ord(code[i+1])*256
  152. i = i+2
  153. label = -1
  154. if op in hasjrel:
  155. label = i+oparg
  156. elif op in hasjabs:
  157. label = oparg
  158. if label >= 0:
  159. if label not in labels:
  160. labels.append(label)
  161. return labels
  162. def findlinestarts(code):
  163. """Find the offsets in a byte code which are start of lines in the source.
  164. Generate pairs (offset, lineno) as described in Python/compile.c.
  165. """
  166. byte_increments = [ord(c) for c in code.co_lnotab[0::2]]
  167. line_increments = [ord(c) for c in code.co_lnotab[1::2]]
  168. lastlineno = None
  169. lineno = code.co_firstlineno
  170. addr = 0
  171. for byte_incr, line_incr in zip(byte_increments, line_increments):
  172. if byte_incr:
  173. if lineno != lastlineno:
  174. yield (addr, lineno)
  175. lastlineno = lineno
  176. addr += byte_incr
  177. lineno += line_incr
  178. if lineno != lastlineno:
  179. yield (addr, lineno)
  180. def _test():
  181. """Simple test program to disassemble a file."""
  182. if sys.argv[1:]:
  183. if sys.argv[2:]:
  184. sys.stderr.write("usage: python dis.py [-|file]\n")
  185. sys.exit(2)
  186. fn = sys.argv[1]
  187. if not fn or fn == "-":
  188. fn = None
  189. else:
  190. fn = None
  191. if fn is None:
  192. f = sys.stdin
  193. else:
  194. f = open(fn)
  195. source = f.read()
  196. if fn is not None:
  197. f.close()
  198. else:
  199. fn = "<stdin>"
  200. code = compile(source, fn, "exec")
  201. dis(code)
  202. if __name__ == "__main__":
  203. _test()