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