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