dis.py 19.4 KB
Newer Older
1
"""Disassembler of Python byte code into mnemonics."""
Guido van Rossum's avatar
Guido van Rossum committed
2 3

import sys
4
import types
5
import collections
6
import io
Guido van Rossum's avatar
Guido van Rossum committed
7

8 9 10
from opcode import *
from opcode import __all__ as _opcodes_all

11
__all__ = ["code_info", "dis", "disassemble", "distb", "disco",
12 13
           "findlinestarts", "findlabels", "show_code",
           "get_instructions", "Instruction", "Bytecode"] + _opcodes_all
14
del _opcodes_all
15

16 17
_have_code = (types.MethodType, types.FunctionType, types.CodeType,
              classmethod, staticmethod, type)
Benjamin Peterson's avatar
Benjamin Peterson committed
18

19 20
FORMAT_VALUE = opmap['FORMAT_VALUE']

21 22 23 24 25 26 27 28 29 30 31 32 33
def _try_compile(source, name):
    """Attempts to compile the given source, first as an expression and
       then as a statement if the first approach fails.

       Utility function to accept strings in functions that otherwise
       expect code objects
    """
    try:
        c = compile(source, name, 'eval')
    except SyntaxError:
        c = compile(source, name, 'exec')
    return c

34
def dis(x=None, *, file=None, depth=None):
35
    """Disassemble classes, methods, functions, and other compiled objects.
Tim Peters's avatar
Tim Peters committed
36 37 38

    With no argument, disassemble the last traceback.

39 40 41
    Compiled objects currently include generator objects, async generator
    objects, and coroutine objects, all of which store their code object
    in a special attribute.
Tim Peters's avatar
Tim Peters committed
42
    """
43
    if x is None:
44
        distb(file=file)
Tim Peters's avatar
Tim Peters committed
45
        return
46 47
    # Extract functions from methods.
    if hasattr(x, '__func__'):
48
        x = x.__func__
49 50
    # Extract compiled code objects from...
    if hasattr(x, '__code__'):  # ...a function, or
51
        x = x.__code__
52
    elif hasattr(x, 'gi_code'):  #...a generator object, or
53
        x = x.gi_code
54 55 56 57 58
    elif hasattr(x, 'ag_code'):  #...an asynchronous generator object, or
        x = x.ag_code
    elif hasattr(x, 'cr_code'):  #...a coroutine.
        x = x.cr_code
    # Perform the disassembly.
59
    if hasattr(x, '__dict__'):  # Class or module
60
        items = sorted(x.__dict__.items())
Tim Peters's avatar
Tim Peters committed
61
        for name, x1 in items:
Benjamin Peterson's avatar
Benjamin Peterson committed
62
            if isinstance(x1, _have_code):
63
                print("Disassembly of %s:" % name, file=file)
Tim Peters's avatar
Tim Peters committed
64
                try:
65
                    dis(x1, file=file, depth=depth)
66
                except TypeError as msg:
67 68
                    print("Sorry:", msg, file=file)
                print(file=file)
69
    elif hasattr(x, 'co_code'): # Code object
70
        _disassemble_recursive(x, file=file, depth=depth)
71
    elif isinstance(x, (bytes, bytearray)): # Raw bytecode
72
        _disassemble_bytes(x, file=file)
73
    elif isinstance(x, str):    # Source code
74
        _disassemble_str(x, file=file, depth=depth)
Tim Peters's avatar
Tim Peters committed
75
    else:
76 77
        raise TypeError("don't know how to disassemble %s objects" %
                        type(x).__name__)
Guido van Rossum's avatar
Guido van Rossum committed
78

79
def distb(tb=None, *, file=None):
Tim Peters's avatar
Tim Peters committed
80
    """Disassemble a traceback (default: last traceback)."""
81
    if tb is None:
Tim Peters's avatar
Tim Peters committed
82 83 84
        try:
            tb = sys.last_traceback
        except AttributeError:
85
            raise RuntimeError("no last traceback to disassemble") from None
Tim Peters's avatar
Tim Peters committed
86
        while tb.tb_next: tb = tb.tb_next
87
    disassemble(tb.tb_frame.f_code, tb.tb_lasti, file=file)
Guido van Rossum's avatar
Guido van Rossum committed
88

89 90 91 92
# The inspect module interrogates this dictionary to build its
# list of CO_* constants. It is also used by pretty_flags to
# turn the co_flags field into a human readable list.
COMPILER_FLAG_NAMES = {
93 94 95 96 97 98 99
     1: "OPTIMIZED",
     2: "NEWLOCALS",
     4: "VARARGS",
     8: "VARKEYWORDS",
    16: "NESTED",
    32: "GENERATOR",
    64: "NOFREE",
100 101
   128: "COROUTINE",
   256: "ITERABLE_COROUTINE",
102
   512: "ASYNC_GENERATOR",
103 104 105 106 107 108 109 110
}

def pretty_flags(flags):
    """Return pretty representation of code flags."""
    names = []
    for i in range(32):
        flag = 1<<i
        if flags & flag:
111
            names.append(COMPILER_FLAG_NAMES.get(flag, hex(flag)))
112 113 114 115 116 117 118
            flags ^= flag
            if not flags:
                break
    else:
        names.append(hex(flags))
    return ", ".join(names)

119
def _get_code_object(x):
120 121 122
    """Helper to handle methods, compiled or raw code objects, and strings."""
    # Extract functions from methods.
    if hasattr(x, '__func__'):
123
        x = x.__func__
124 125
    # Extract compiled code objects from...
    if hasattr(x, '__code__'):  # ...a function, or
126
        x = x.__code__
127
    elif hasattr(x, 'gi_code'):  #...a generator object, or
128
        x = x.gi_code
129 130 131 132 133 134
    elif hasattr(x, 'ag_code'):  #...an asynchronous generator object, or
        x = x.ag_code
    elif hasattr(x, 'cr_code'):  #...a coroutine.
        x = x.cr_code
    # Handle source code.
    if isinstance(x, str):
135
        x = _try_compile(x, "<disassembly>")
136 137
    # By now, if we don't have a code object, we can't disassemble x.
    if hasattr(x, 'co_code'):
138 139 140 141 142 143 144
        return x
    raise TypeError("don't know how to disassemble %s objects" %
                    type(x).__name__)

def code_info(x):
    """Formatted details of methods, functions, or code."""
    return _format_code_info(_get_code_object(x))
145 146 147 148 149 150 151 152 153 154

def _format_code_info(co):
    lines = []
    lines.append("Name:              %s" % co.co_name)
    lines.append("Filename:          %s" % co.co_filename)
    lines.append("Argument count:    %s" % co.co_argcount)
    lines.append("Kw-only arguments: %s" % co.co_kwonlyargcount)
    lines.append("Number of locals:  %s" % co.co_nlocals)
    lines.append("Stack size:        %s" % co.co_stacksize)
    lines.append("Flags:             %s" % pretty_flags(co.co_flags))
155
    if co.co_consts:
156
        lines.append("Constants:")
157
        for i_c in enumerate(co.co_consts):
158
            lines.append("%4d: %r" % i_c)
159
    if co.co_names:
160
        lines.append("Names:")
161
        for i_n in enumerate(co.co_names):
162
            lines.append("%4d: %s" % i_n)
163
    if co.co_varnames:
164
        lines.append("Variable names:")
165
        for i_n in enumerate(co.co_varnames):
166
            lines.append("%4d: %s" % i_n)
167
    if co.co_freevars:
168
        lines.append("Free variables:")
169
        for i_n in enumerate(co.co_freevars):
170
            lines.append("%4d: %s" % i_n)
171
    if co.co_cellvars:
172
        lines.append("Cell variables:")
173
        for i_n in enumerate(co.co_cellvars):
174 175 176
            lines.append("%4d: %s" % i_n)
    return "\n".join(lines)

177
def show_code(co, *, file=None):
178 179 180 181
    """Print details of methods, functions, or code to *file*.

    If *file* is not provided, the output is printed on stdout.
    """
182
    print(code_info(co), file=file)
183

184 185 186
_Instruction = collections.namedtuple("_Instruction",
     "opname opcode arg argval argrepr offset starts_line is_jump_target")

187 188 189 190 191 192 193 194 195
_Instruction.opname.__doc__ = "Human readable name for operation"
_Instruction.opcode.__doc__ = "Numeric code for operation"
_Instruction.arg.__doc__ = "Numeric argument to operation (if any), otherwise None"
_Instruction.argval.__doc__ = "Resolved arg value (if known), otherwise same as arg"
_Instruction.argrepr.__doc__ = "Human readable description of operation argument"
_Instruction.offset.__doc__ = "Start index of operation within bytecode sequence"
_Instruction.starts_line.__doc__ = "Line started by this opcode (if any), otherwise None"
_Instruction.is_jump_target.__doc__ = "True if other code jumps to here, otherwise False"

196 197 198
_OPNAME_WIDTH = 20
_OPARG_WIDTH = 5

199 200 201 202 203 204 205 206 207 208 209 210 211 212
class Instruction(_Instruction):
    """Details for a bytecode operation

       Defined fields:
         opname - human readable name for operation
         opcode - numeric code for operation
         arg - numeric argument to operation (if any), otherwise None
         argval - resolved arg value (if known), otherwise same as arg
         argrepr - human readable description of operation argument
         offset - start index of operation within bytecode sequence
         starts_line - line started by this opcode (if any), otherwise None
         is_jump_target - True if other code jumps to here, otherwise False
    """

213
    def _disassemble(self, lineno_width=3, mark_as_current=False, offset_width=4):
214 215 216 217
        """Format instruction details for inclusion in disassembly output

        *lineno_width* sets the width of the line number field (0 omits it)
        *mark_as_current* inserts a '-->' marker arrow as part of the line
218
        *offset_width* sets the width of the instruction offset field
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
        """
        fields = []
        # Column: Source code line number
        if lineno_width:
            if self.starts_line is not None:
                lineno_fmt = "%%%dd" % lineno_width
                fields.append(lineno_fmt % self.starts_line)
            else:
                fields.append(' ' * lineno_width)
        # Column: Current instruction indicator
        if mark_as_current:
            fields.append('-->')
        else:
            fields.append('   ')
        # Column: Jump target marker
        if self.is_jump_target:
            fields.append('>>')
        else:
            fields.append('  ')
        # Column: Instruction offset from start of code sequence
239
        fields.append(repr(self.offset).rjust(offset_width))
240
        # Column: Opcode name
241
        fields.append(self.opname.ljust(_OPNAME_WIDTH))
242 243
        # Column: Opcode argument
        if self.arg is not None:
244
            fields.append(repr(self.arg).rjust(_OPARG_WIDTH))
245 246 247
            # Column: Opcode argument details
            if self.argrepr:
                fields.append('(' + self.argrepr + ')')
248
        return ' '.join(fields).rstrip()
249 250


251
def get_instructions(x, *, first_line=None):
252 253 254 255 256
    """Iterator for the opcodes in methods, functions or code

    Generates a series of Instruction named tuples giving the details of
    each operations in the supplied code.

257 258 259 260
    If *first_line* is not None, it indicates the line number that should
    be reported for the first source line in the disassembled code.
    Otherwise, the source line information (if any) is taken directly from
    the disassembled code object.
261 262 263
    """
    co = _get_code_object(x)
    cell_names = co.co_cellvars + co.co_freevars
264
    linestarts = dict(findlinestarts(co))
265 266 267 268
    if first_line is not None:
        line_offset = first_line - co.co_firstlineno
    else:
        line_offset = 0
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
    return _get_instructions_bytes(co.co_code, co.co_varnames, co.co_names,
                                   co.co_consts, cell_names, linestarts,
                                   line_offset)

def _get_const_info(const_index, const_list):
    """Helper to get optional details about const references

       Returns the dereferenced constant and its repr if the constant
       list is defined.
       Otherwise returns the constant index and its repr().
    """
    argval = const_index
    if const_list is not None:
        argval = const_list[const_index]
    return argval, repr(argval)

def _get_name_info(name_index, name_list):
    """Helper to get optional details about named references

       Returns the dereferenced name as both value and repr if the name
       list is defined.
       Otherwise returns the name index and its repr().
    """
    argval = name_index
    if name_list is not None:
        argval = name_list[name_index]
        argrepr = argval
    else:
        argrepr = repr(argval)
    return argval, argrepr


def _get_instructions_bytes(code, varnames=None, names=None, constants=None,
                      cells=None, linestarts=None, line_offset=0):
    """Iterate over the instructions in a bytecode string.

    Generates a sequence of Instruction namedtuples giving the details of each
    opcode.  Additional information about the code's runtime environment
    (e.g. variable names, constants) can be specified using optional
    arguments.

    """
    labels = findlabels(code)
    starts_line = None
313
    for offset, op, arg in _unpack_opargs(code):
314
        if linestarts is not None:
315
            starts_line = linestarts.get(offset, None)
316 317
            if starts_line is not None:
                starts_line += line_offset
318
        is_jump_target = offset in labels
319 320
        argval = None
        argrepr = ''
321
        if arg is not None:
322
            #  Set argval to the dereferenced value of the argument when
323
            #  available, and argrepr to the string representation of argval.
324 325 326
            #    _disassemble_bytes needs the string repr of the
            #    raw name index for LOAD_GLOBAL, LOAD_CONST, etc.
            argval = arg
Tim Peters's avatar
Tim Peters committed
327
            if op in hasconst:
328
                argval, argrepr = _get_const_info(arg, constants)
Tim Peters's avatar
Tim Peters committed
329
            elif op in hasname:
330
                argval, argrepr = _get_name_info(arg, names)
Tim Peters's avatar
Tim Peters committed
331
            elif op in hasjrel:
332
                argval = offset + 2 + arg
333
                argrepr = "to " + repr(argval)
Tim Peters's avatar
Tim Peters committed
334
            elif op in haslocal:
335
                argval, argrepr = _get_name_info(arg, varnames)
Tim Peters's avatar
Tim Peters committed
336
            elif op in hascompare:
337 338
                argval = cmp_op[arg]
                argrepr = argval
Jeremy Hylton's avatar
Jeremy Hylton committed
339
            elif op in hasfree:
340
                argval, argrepr = _get_name_info(arg, cells)
341 342 343 344 345 346 347
            elif op == FORMAT_VALUE:
                argval = ((None, str, repr, ascii)[arg & 0x3], bool(arg & 0x4))
                argrepr = ('', 'str', 'repr', 'ascii')[arg & 0x3]
                if argval[1]:
                    if argrepr:
                        argrepr += ', '
                    argrepr += 'with format'
348 349 350 351 352 353 354 355 356 357
        yield Instruction(opname[op], op,
                          arg, argval, argrepr,
                          offset, starts_line, is_jump_target)

def disassemble(co, lasti=-1, *, file=None):
    """Disassemble a code object."""
    cell_names = co.co_cellvars + co.co_freevars
    linestarts = dict(findlinestarts(co))
    _disassemble_bytes(co.co_code, lasti, co.co_varnames, co.co_names,
                       co.co_consts, cell_names, linestarts, file=file)
Tim Peters's avatar
Tim Peters committed
358

359 360 361 362 363 364 365 366 367 368 369
def _disassemble_recursive(co, *, file=None, depth=None):
    disassemble(co, file=file)
    if depth is None or depth > 0:
        if depth is not None:
            depth = depth - 1
        for x in co.co_consts:
            if hasattr(x, 'co_code'):
                print(file=file)
                print("Disassembly of %r:" % (x,), file=file)
                _disassemble_recursive(x, file=file, depth=depth)

370
def _disassemble_bytes(code, lasti=-1, varnames=None, names=None,
371
                       constants=None, cells=None, linestarts=None,
372
                       *, file=None, line_offset=0):
373 374
    # Omit the line number column entirely if we have no line number info
    show_lineno = linestarts is not None
375 376 377 378 379 380 381 382 383 384 385 386 387
    if show_lineno:
        maxlineno = max(linestarts.values()) + line_offset
        if maxlineno >= 1000:
            lineno_width = len(str(maxlineno))
        else:
            lineno_width = 3
    else:
        lineno_width = 0
    maxoffset = len(code) - 2
    if maxoffset >= 10000:
        offset_width = len(str(maxoffset))
    else:
        offset_width = 4
388
    for instr in _get_instructions_bytes(code, varnames, names,
389 390
                                         constants, cells, linestarts,
                                         line_offset=line_offset):
391 392 393 394 395 396
        new_source_line = (show_lineno and
                           instr.starts_line is not None and
                           instr.offset > 0)
        if new_source_line:
            print(file=file)
        is_current_instr = instr.offset == lasti
397 398
        print(instr._disassemble(lineno_width, is_current_instr, offset_width),
              file=file)
399

400
def _disassemble_str(source, **kwargs):
401
    """Compile the source string, then disassemble the code object."""
402
    _disassemble_recursive(_try_compile(source, '<dis>'), **kwargs)
403

Tim Peters's avatar
Tim Peters committed
404
disco = disassemble                     # XXX For backwards compatibility
405

406 407
def _unpack_opargs(code):
    extended_arg = 0
408
    for i in range(0, len(code), 2):
409
        op = code[i]
Tim Peters's avatar
Tim Peters committed
410
        if op >= HAVE_ARGUMENT:
411 412 413 414 415
            arg = code[i+1] | extended_arg
            extended_arg = (arg << 8) if op == EXTENDED_ARG else 0
        else:
            arg = None
        yield (i, op, arg)
416 417 418 419 420 421 422 423 424 425

def findlabels(code):
    """Detect all offsets in a byte code which are jump targets.

    Return the list of offsets.

    """
    labels = []
    for offset, op, arg in _unpack_opargs(code):
        if arg is not None:
Tim Peters's avatar
Tim Peters committed
426
            if op in hasjrel:
427
                label = offset + 2 + arg
Tim Peters's avatar
Tim Peters committed
428
            elif op in hasjabs:
429
                label = arg
430 431 432 433
            else:
                continue
            if label not in labels:
                labels.append(label)
Tim Peters's avatar
Tim Peters committed
434
    return labels
Guido van Rossum's avatar
Guido van Rossum committed
435

436 437 438 439 440 441
def findlinestarts(code):
    """Find the offsets in a byte code which are start of lines in the source.

    Generate pairs (offset, lineno) as described in Python/compile.c.

    """
442 443
    byte_increments = code.co_lnotab[0::2]
    line_increments = code.co_lnotab[1::2]
444 445 446 447 448 449 450 451 452 453

    lastlineno = None
    lineno = code.co_firstlineno
    addr = 0
    for byte_incr, line_incr in zip(byte_increments, line_increments):
        if byte_incr:
            if lineno != lastlineno:
                yield (addr, lineno)
                lastlineno = lineno
            addr += byte_incr
454 455 456
        if line_incr >= 0x80:
            # line_increments is an array of 8-bit signed integers
            line_incr -= 0x100
457 458 459
        lineno += line_incr
    if lineno != lastlineno:
        yield (addr, lineno)
460

461 462 463
class Bytecode:
    """The bytecode operations of a piece of code

464 465
    Instantiate this with a function, method, other compiled object, string of
    code, or a code object (as returned by compile()).
466 467 468

    Iterating over this yields the bytecode operations as Instruction instances.
    """
469
    def __init__(self, x, *, first_line=None, current_offset=None):
470 471 472 473 474 475 476 477 478 479
        self.codeobj = co = _get_code_object(x)
        if first_line is None:
            self.first_line = co.co_firstlineno
            self._line_offset = 0
        else:
            self.first_line = first_line
            self._line_offset = first_line - co.co_firstlineno
        self._cell_names = co.co_cellvars + co.co_freevars
        self._linestarts = dict(findlinestarts(co))
        self._original_object = x
480
        self.current_offset = current_offset
481 482 483 484

    def __iter__(self):
        co = self.codeobj
        return _get_instructions_bytes(co.co_code, co.co_varnames, co.co_names,
485 486 487
                                       co.co_consts, self._cell_names,
                                       self._linestarts,
                                       line_offset=self._line_offset)
488 489

    def __repr__(self):
490 491
        return "{}({!r})".format(self.__class__.__name__,
                                 self._original_object)
492

493 494 495 496 497 498 499
    @classmethod
    def from_traceback(cls, tb):
        """ Construct a Bytecode from the given traceback """
        while tb.tb_next:
            tb = tb.tb_next
        return cls(tb.tb_frame.f_code, current_offset=tb.tb_lasti)

500 501 502 503
    def info(self):
        """Return formatted information about the code object."""
        return _format_code_info(self.codeobj)

504 505
    def dis(self):
        """Return a formatted view of the bytecode operations."""
506
        co = self.codeobj
507 508 509 510
        if self.current_offset is not None:
            offset = self.current_offset
        else:
            offset = -1
511 512 513 514 515 516
        with io.StringIO() as output:
            _disassemble_bytes(co.co_code, varnames=co.co_varnames,
                               names=co.co_names, constants=co.co_consts,
                               cells=self._cell_names,
                               linestarts=self._linestarts,
                               line_offset=self._line_offset,
517 518
                               file=output,
                               lasti=offset)
519
            return output.getvalue()
520 521


522
def _test():
Tim Peters's avatar
Tim Peters committed
523
    """Simple test program to disassemble a file."""
524 525 526 527 528 529 530 531
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('infile', type=argparse.FileType(), nargs='?', default='-')
    args = parser.parse_args()
    with args.infile as infile:
        source = infile.read()
    code = compile(source, args.infile.name, "exec")
Tim Peters's avatar
Tim Peters committed
532
    dis(code)
533 534

if __name__ == "__main__":
Tim Peters's avatar
Tim Peters committed
535
    _test()