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