PageRenderTime 57ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/Lib/dis.py

https://github.com/albertz/CPython
Python | 535 lines | 453 code | 20 blank | 62 comment | 50 complexity | c9a99392b4fd1078829a3a7e0d4b1617 MD5 | raw file
  1. """Disassembler of Python byte code into mnemonics."""
  2. import sys
  3. import types
  4. import collections
  5. import io
  6. from opcode import *
  7. from opcode import __all__ as _opcodes_all
  8. __all__ = ["code_info", "dis", "disassemble", "distb", "disco",
  9. "findlinestarts", "findlabels", "show_code",
  10. "get_instructions", "Instruction", "Bytecode"] + _opcodes_all
  11. del _opcodes_all
  12. _have_code = (types.MethodType, types.FunctionType, types.CodeType,
  13. classmethod, staticmethod, type)
  14. FORMAT_VALUE = opmap['FORMAT_VALUE']
  15. def _try_compile(source, name):
  16. """Attempts to compile the given source, first as an expression and
  17. then as a statement if the first approach fails.
  18. Utility function to accept strings in functions that otherwise
  19. expect code objects
  20. """
  21. try:
  22. c = compile(source, name, 'eval')
  23. except SyntaxError:
  24. c = compile(source, name, 'exec')
  25. return c
  26. def dis(x=None, *, file=None, depth=None):
  27. """Disassemble classes, methods, functions, and other compiled objects.
  28. With no argument, disassemble the last traceback.
  29. Compiled objects currently include generator objects, async generator
  30. objects, and coroutine objects, all of which store their code object
  31. in a special attribute.
  32. """
  33. if x is None:
  34. distb(file=file)
  35. return
  36. # Extract functions from methods.
  37. if hasattr(x, '__func__'):
  38. x = x.__func__
  39. # Extract compiled code objects from...
  40. if hasattr(x, '__code__'): # ...a function, or
  41. x = x.__code__
  42. elif hasattr(x, 'gi_code'): #...a generator object, or
  43. x = x.gi_code
  44. elif hasattr(x, 'ag_code'): #...an asynchronous generator object, or
  45. x = x.ag_code
  46. elif hasattr(x, 'cr_code'): #...a coroutine.
  47. x = x.cr_code
  48. # Perform the disassembly.
  49. if hasattr(x, '__dict__'): # Class or module
  50. items = sorted(x.__dict__.items())
  51. for name, x1 in items:
  52. if isinstance(x1, _have_code):
  53. print("Disassembly of %s:" % name, file=file)
  54. try:
  55. dis(x1, file=file, depth=depth)
  56. except TypeError as msg:
  57. print("Sorry:", msg, file=file)
  58. print(file=file)
  59. elif hasattr(x, 'co_code'): # Code object
  60. _disassemble_recursive(x, file=file, depth=depth)
  61. elif isinstance(x, (bytes, bytearray)): # Raw bytecode
  62. _disassemble_bytes(x, file=file)
  63. elif isinstance(x, str): # Source code
  64. _disassemble_str(x, file=file, depth=depth)
  65. else:
  66. raise TypeError("don't know how to disassemble %s objects" %
  67. type(x).__name__)
  68. def distb(tb=None, *, file=None):
  69. """Disassemble a traceback (default: last traceback)."""
  70. if tb is None:
  71. try:
  72. tb = sys.last_traceback
  73. except AttributeError:
  74. raise RuntimeError("no last traceback to disassemble") from None
  75. while tb.tb_next: tb = tb.tb_next
  76. disassemble(tb.tb_frame.f_code, tb.tb_lasti, file=file)
  77. # The inspect module interrogates this dictionary to build its
  78. # list of CO_* constants. It is also used by pretty_flags to
  79. # turn the co_flags field into a human readable list.
  80. COMPILER_FLAG_NAMES = {
  81. 1: "OPTIMIZED",
  82. 2: "NEWLOCALS",
  83. 4: "VARARGS",
  84. 8: "VARKEYWORDS",
  85. 16: "NESTED",
  86. 32: "GENERATOR",
  87. 64: "NOFREE",
  88. 128: "COROUTINE",
  89. 256: "ITERABLE_COROUTINE",
  90. 512: "ASYNC_GENERATOR",
  91. }
  92. def pretty_flags(flags):
  93. """Return pretty representation of code flags."""
  94. names = []
  95. for i in range(32):
  96. flag = 1<<i
  97. if flags & flag:
  98. names.append(COMPILER_FLAG_NAMES.get(flag, hex(flag)))
  99. flags ^= flag
  100. if not flags:
  101. break
  102. else:
  103. names.append(hex(flags))
  104. return ", ".join(names)
  105. def _get_code_object(x):
  106. """Helper to handle methods, compiled or raw code objects, and strings."""
  107. # Extract functions from methods.
  108. if hasattr(x, '__func__'):
  109. x = x.__func__
  110. # Extract compiled code objects from...
  111. if hasattr(x, '__code__'): # ...a function, or
  112. x = x.__code__
  113. elif hasattr(x, 'gi_code'): #...a generator object, or
  114. x = x.gi_code
  115. elif hasattr(x, 'ag_code'): #...an asynchronous generator object, or
  116. x = x.ag_code
  117. elif hasattr(x, 'cr_code'): #...a coroutine.
  118. x = x.cr_code
  119. # Handle source code.
  120. if isinstance(x, str):
  121. x = _try_compile(x, "<disassembly>")
  122. # By now, if we don't have a code object, we can't disassemble x.
  123. if hasattr(x, 'co_code'):
  124. return x
  125. raise TypeError("don't know how to disassemble %s objects" %
  126. type(x).__name__)
  127. def code_info(x):
  128. """Formatted details of methods, functions, or code."""
  129. return _format_code_info(_get_code_object(x))
  130. def _format_code_info(co):
  131. lines = []
  132. lines.append("Name: %s" % co.co_name)
  133. lines.append("Filename: %s" % co.co_filename)
  134. lines.append("Argument count: %s" % co.co_argcount)
  135. lines.append("Kw-only arguments: %s" % co.co_kwonlyargcount)
  136. lines.append("Number of locals: %s" % co.co_nlocals)
  137. lines.append("Stack size: %s" % co.co_stacksize)
  138. lines.append("Flags: %s" % pretty_flags(co.co_flags))
  139. if co.co_consts:
  140. lines.append("Constants:")
  141. for i_c in enumerate(co.co_consts):
  142. lines.append("%4d: %r" % i_c)
  143. if co.co_names:
  144. lines.append("Names:")
  145. for i_n in enumerate(co.co_names):
  146. lines.append("%4d: %s" % i_n)
  147. if co.co_varnames:
  148. lines.append("Variable names:")
  149. for i_n in enumerate(co.co_varnames):
  150. lines.append("%4d: %s" % i_n)
  151. if co.co_freevars:
  152. lines.append("Free variables:")
  153. for i_n in enumerate(co.co_freevars):
  154. lines.append("%4d: %s" % i_n)
  155. if co.co_cellvars:
  156. lines.append("Cell variables:")
  157. for i_n in enumerate(co.co_cellvars):
  158. lines.append("%4d: %s" % i_n)
  159. return "\n".join(lines)
  160. def show_code(co, *, file=None):
  161. """Print details of methods, functions, or code to *file*.
  162. If *file* is not provided, the output is printed on stdout.
  163. """
  164. print(code_info(co), file=file)
  165. _Instruction = collections.namedtuple("_Instruction",
  166. "opname opcode arg argval argrepr offset starts_line is_jump_target")
  167. _Instruction.opname.__doc__ = "Human readable name for operation"
  168. _Instruction.opcode.__doc__ = "Numeric code for operation"
  169. _Instruction.arg.__doc__ = "Numeric argument to operation (if any), otherwise None"
  170. _Instruction.argval.__doc__ = "Resolved arg value (if known), otherwise same as arg"
  171. _Instruction.argrepr.__doc__ = "Human readable description of operation argument"
  172. _Instruction.offset.__doc__ = "Start index of operation within bytecode sequence"
  173. _Instruction.starts_line.__doc__ = "Line started by this opcode (if any), otherwise None"
  174. _Instruction.is_jump_target.__doc__ = "True if other code jumps to here, otherwise False"
  175. _OPNAME_WIDTH = 20
  176. _OPARG_WIDTH = 5
  177. class Instruction(_Instruction):
  178. """Details for a bytecode operation
  179. Defined fields:
  180. opname - human readable name for operation
  181. opcode - numeric code for operation
  182. arg - numeric argument to operation (if any), otherwise None
  183. argval - resolved arg value (if known), otherwise same as arg
  184. argrepr - human readable description of operation argument
  185. offset - start index of operation within bytecode sequence
  186. starts_line - line started by this opcode (if any), otherwise None
  187. is_jump_target - True if other code jumps to here, otherwise False
  188. """
  189. def _disassemble(self, lineno_width=3, mark_as_current=False, offset_width=4):
  190. """Format instruction details for inclusion in disassembly output
  191. *lineno_width* sets the width of the line number field (0 omits it)
  192. *mark_as_current* inserts a '-->' marker arrow as part of the line
  193. *offset_width* sets the width of the instruction offset field
  194. """
  195. fields = []
  196. # Column: Source code line number
  197. if lineno_width:
  198. if self.starts_line is not None:
  199. lineno_fmt = "%%%dd" % lineno_width
  200. fields.append(lineno_fmt % self.starts_line)
  201. else:
  202. fields.append(' ' * lineno_width)
  203. # Column: Current instruction indicator
  204. if mark_as_current:
  205. fields.append('-->')
  206. else:
  207. fields.append(' ')
  208. # Column: Jump target marker
  209. if self.is_jump_target:
  210. fields.append('>>')
  211. else:
  212. fields.append(' ')
  213. # Column: Instruction offset from start of code sequence
  214. fields.append(repr(self.offset).rjust(offset_width))
  215. # Column: Opcode name
  216. fields.append(self.opname.ljust(_OPNAME_WIDTH))
  217. # Column: Opcode argument
  218. if self.arg is not None:
  219. fields.append(repr(self.arg).rjust(_OPARG_WIDTH))
  220. # Column: Opcode argument details
  221. if self.argrepr:
  222. fields.append('(' + self.argrepr + ')')
  223. return ' '.join(fields).rstrip()
  224. def get_instructions(x, *, first_line=None):
  225. """Iterator for the opcodes in methods, functions or code
  226. Generates a series of Instruction named tuples giving the details of
  227. each operations in the supplied code.
  228. If *first_line* is not None, it indicates the line number that should
  229. be reported for the first source line in the disassembled code.
  230. Otherwise, the source line information (if any) is taken directly from
  231. the disassembled code object.
  232. """
  233. co = _get_code_object(x)
  234. cell_names = co.co_cellvars + co.co_freevars
  235. linestarts = dict(findlinestarts(co))
  236. if first_line is not None:
  237. line_offset = first_line - co.co_firstlineno
  238. else:
  239. line_offset = 0
  240. return _get_instructions_bytes(co.co_code, co.co_varnames, co.co_names,
  241. co.co_consts, cell_names, linestarts,
  242. line_offset)
  243. def _get_const_info(const_index, const_list):
  244. """Helper to get optional details about const references
  245. Returns the dereferenced constant and its repr if the constant
  246. list is defined.
  247. Otherwise returns the constant index and its repr().
  248. """
  249. argval = const_index
  250. if const_list is not None:
  251. argval = const_list[const_index]
  252. return argval, repr(argval)
  253. def _get_name_info(name_index, name_list):
  254. """Helper to get optional details about named references
  255. Returns the dereferenced name as both value and repr if the name
  256. list is defined.
  257. Otherwise returns the name index and its repr().
  258. """
  259. argval = name_index
  260. if name_list is not None:
  261. argval = name_list[name_index]
  262. argrepr = argval
  263. else:
  264. argrepr = repr(argval)
  265. return argval, argrepr
  266. def _get_instructions_bytes(code, varnames=None, names=None, constants=None,
  267. cells=None, linestarts=None, line_offset=0):
  268. """Iterate over the instructions in a bytecode string.
  269. Generates a sequence of Instruction namedtuples giving the details of each
  270. opcode. Additional information about the code's runtime environment
  271. (e.g. variable names, constants) can be specified using optional
  272. arguments.
  273. """
  274. labels = findlabels(code)
  275. starts_line = None
  276. for offset, op, arg in _unpack_opargs(code):
  277. if linestarts is not None:
  278. starts_line = linestarts.get(offset, None)
  279. if starts_line is not None:
  280. starts_line += line_offset
  281. is_jump_target = offset in labels
  282. argval = None
  283. argrepr = ''
  284. if arg is not None:
  285. # Set argval to the dereferenced value of the argument when
  286. # available, and argrepr to the string representation of argval.
  287. # _disassemble_bytes needs the string repr of the
  288. # raw name index for LOAD_GLOBAL, LOAD_CONST, etc.
  289. argval = arg
  290. if op in hasconst:
  291. argval, argrepr = _get_const_info(arg, constants)
  292. elif op in hasname:
  293. argval, argrepr = _get_name_info(arg, names)
  294. elif op in hasjrel:
  295. argval = offset + 2 + arg
  296. argrepr = "to " + repr(argval)
  297. elif op in haslocal:
  298. argval, argrepr = _get_name_info(arg, varnames)
  299. elif op in hascompare:
  300. argval = cmp_op[arg]
  301. argrepr = argval
  302. elif op in hasfree:
  303. argval, argrepr = _get_name_info(arg, cells)
  304. elif op == FORMAT_VALUE:
  305. argval = ((None, str, repr, ascii)[arg & 0x3], bool(arg & 0x4))
  306. argrepr = ('', 'str', 'repr', 'ascii')[arg & 0x3]
  307. if argval[1]:
  308. if argrepr:
  309. argrepr += ', '
  310. argrepr += 'with format'
  311. yield Instruction(opname[op], op,
  312. arg, argval, argrepr,
  313. offset, starts_line, is_jump_target)
  314. def disassemble(co, lasti=-1, *, file=None):
  315. """Disassemble a code object."""
  316. cell_names = co.co_cellvars + co.co_freevars
  317. linestarts = dict(findlinestarts(co))
  318. _disassemble_bytes(co.co_code, lasti, co.co_varnames, co.co_names,
  319. co.co_consts, cell_names, linestarts, file=file)
  320. def _disassemble_recursive(co, *, file=None, depth=None):
  321. disassemble(co, file=file)
  322. if depth is None or depth > 0:
  323. if depth is not None:
  324. depth = depth - 1
  325. for x in co.co_consts:
  326. if hasattr(x, 'co_code'):
  327. print(file=file)
  328. print("Disassembly of %r:" % (x,), file=file)
  329. _disassemble_recursive(x, file=file, depth=depth)
  330. def _disassemble_bytes(code, lasti=-1, varnames=None, names=None,
  331. constants=None, cells=None, linestarts=None,
  332. *, file=None, line_offset=0):
  333. # Omit the line number column entirely if we have no line number info
  334. show_lineno = linestarts is not None
  335. if show_lineno:
  336. maxlineno = max(linestarts.values()) + line_offset
  337. if maxlineno >= 1000:
  338. lineno_width = len(str(maxlineno))
  339. else:
  340. lineno_width = 3
  341. else:
  342. lineno_width = 0
  343. maxoffset = len(code) - 2
  344. if maxoffset >= 10000:
  345. offset_width = len(str(maxoffset))
  346. else:
  347. offset_width = 4
  348. for instr in _get_instructions_bytes(code, varnames, names,
  349. constants, cells, linestarts,
  350. line_offset=line_offset):
  351. new_source_line = (show_lineno and
  352. instr.starts_line is not None and
  353. instr.offset > 0)
  354. if new_source_line:
  355. print(file=file)
  356. is_current_instr = instr.offset == lasti
  357. print(instr._disassemble(lineno_width, is_current_instr, offset_width),
  358. file=file)
  359. def _disassemble_str(source, **kwargs):
  360. """Compile the source string, then disassemble the code object."""
  361. _disassemble_recursive(_try_compile(source, '<dis>'), **kwargs)
  362. disco = disassemble # XXX For backwards compatibility
  363. def _unpack_opargs(code):
  364. extended_arg = 0
  365. for i in range(0, len(code), 2):
  366. op = code[i]
  367. if op >= HAVE_ARGUMENT:
  368. arg = code[i+1] | extended_arg
  369. extended_arg = (arg << 8) if op == EXTENDED_ARG else 0
  370. else:
  371. arg = None
  372. yield (i, op, arg)
  373. def findlabels(code):
  374. """Detect all offsets in a byte code which are jump targets.
  375. Return the list of offsets.
  376. """
  377. labels = []
  378. for offset, op, arg in _unpack_opargs(code):
  379. if arg is not None:
  380. if op in hasjrel:
  381. label = offset + 2 + arg
  382. elif op in hasjabs:
  383. label = arg
  384. else:
  385. continue
  386. if label not in labels:
  387. labels.append(label)
  388. return labels
  389. def findlinestarts(code):
  390. """Find the offsets in a byte code which are start of lines in the source.
  391. Generate pairs (offset, lineno) as described in Python/compile.c.
  392. """
  393. byte_increments = code.co_lnotab[0::2]
  394. line_increments = code.co_lnotab[1::2]
  395. lastlineno = None
  396. lineno = code.co_firstlineno
  397. addr = 0
  398. for byte_incr, line_incr in zip(byte_increments, line_increments):
  399. if byte_incr:
  400. if lineno != lastlineno:
  401. yield (addr, lineno)
  402. lastlineno = lineno
  403. addr += byte_incr
  404. if line_incr >= 0x80:
  405. # line_increments is an array of 8-bit signed integers
  406. line_incr -= 0x100
  407. lineno += line_incr
  408. if lineno != lastlineno:
  409. yield (addr, lineno)
  410. class Bytecode:
  411. """The bytecode operations of a piece of code
  412. Instantiate this with a function, method, other compiled object, string of
  413. code, or a code object (as returned by compile()).
  414. Iterating over this yields the bytecode operations as Instruction instances.
  415. """
  416. def __init__(self, x, *, first_line=None, current_offset=None):
  417. self.codeobj = co = _get_code_object(x)
  418. if first_line is None:
  419. self.first_line = co.co_firstlineno
  420. self._line_offset = 0
  421. else:
  422. self.first_line = first_line
  423. self._line_offset = first_line - co.co_firstlineno
  424. self._cell_names = co.co_cellvars + co.co_freevars
  425. self._linestarts = dict(findlinestarts(co))
  426. self._original_object = x
  427. self.current_offset = current_offset
  428. def __iter__(self):
  429. co = self.codeobj
  430. return _get_instructions_bytes(co.co_code, co.co_varnames, co.co_names,
  431. co.co_consts, self._cell_names,
  432. self._linestarts,
  433. line_offset=self._line_offset)
  434. def __repr__(self):
  435. return "{}({!r})".format(self.__class__.__name__,
  436. self._original_object)
  437. @classmethod
  438. def from_traceback(cls, tb):
  439. """ Construct a Bytecode from the given traceback """
  440. while tb.tb_next:
  441. tb = tb.tb_next
  442. return cls(tb.tb_frame.f_code, current_offset=tb.tb_lasti)
  443. def info(self):
  444. """Return formatted information about the code object."""
  445. return _format_code_info(self.codeobj)
  446. def dis(self):
  447. """Return a formatted view of the bytecode operations."""
  448. co = self.codeobj
  449. if self.current_offset is not None:
  450. offset = self.current_offset
  451. else:
  452. offset = -1
  453. with io.StringIO() as output:
  454. _disassemble_bytes(co.co_code, varnames=co.co_varnames,
  455. names=co.co_names, constants=co.co_consts,
  456. cells=self._cell_names,
  457. linestarts=self._linestarts,
  458. line_offset=self._line_offset,
  459. file=output,
  460. lasti=offset)
  461. return output.getvalue()
  462. def _test():
  463. """Simple test program to disassemble a file."""
  464. import argparse
  465. parser = argparse.ArgumentParser()
  466. parser.add_argument('infile', type=argparse.FileType(), nargs='?', default='-')
  467. args = parser.parse_args()
  468. with args.infile as infile:
  469. source = infile.read()
  470. code = compile(source, args.infile.name, "exec")
  471. dis(code)
  472. if __name__ == "__main__":
  473. _test()