"""Disassembler of Python byte code into mnemonics."""
from opcode import __all__ as _opcodes_all
__all__ = ["dis", "disassemble", "distb", "disco",
"findlinestarts", "findlabels"] + _opcodes_all
_have_code = (types.MethodType, types.FunctionType, types.CodeType,
"""Disassemble classes, methods, functions, or code.
With no argument, disassemble the last traceback.
if isinstance(x, types.InstanceType):
if hasattr(x, 'im_func'):
if hasattr(x, 'func_code'):
if hasattr(x, '__dict__'):
items = x.__dict__.items()
if isinstance(x1, _have_code):
print "Disassembly of %s:" % name
elif hasattr(x, 'co_code'):
"don't know how to disassemble %s objects" % \
"""Disassemble a traceback (default: last traceback)."""
raise RuntimeError, "no last traceback to disassemble"
while tb.tb_next: tb = tb.tb_next
disassemble(tb.tb_frame.f_code, tb.tb_lasti)
def disassemble(co, lasti=-1):
"""Disassemble a code object."""
labels = findlabels(code)
linestarts = dict(findlinestarts(co))
print "%3d" % linestarts[i],
if i == lasti: print '-->',
if i in labels: print '>>',
print opname[op].ljust(20),
oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg
extended_arg = oparg*65536L
print repr(oparg).rjust(5),
print '(' + repr(co.co_consts[oparg]) + ')',
print '(' + co.co_names[oparg] + ')',
print '(to ' + repr(i + oparg) + ')',
print '(' + co.co_varnames[oparg] + ')',
print '(' + cmp_op[oparg] + ')',
free = co.co_cellvars + co.co_freevars
print '(' + free[oparg] + ')',
def disassemble_string(code, lasti=-1, varnames=None, names=None,
labels = findlabels(code)
if i == lasti: print '-->',
if i in labels: print '>>',
print opname[op].ljust(15),
oparg = ord(code[i]) + ord(code[i+1])*256
print repr(oparg).rjust(5),
print '(' + repr(constants[oparg]) + ')',
print '(' + names[oparg] + ')',
print '(to ' + repr(i + oparg) + ')',
print '(' + varnames[oparg] + ')',
print '(' + cmp_op[oparg] + ')',
disco = disassemble # XXX For backwards compatibility
"""Detect all offsets in a byte code which are jump targets.
Return the list of offsets.
oparg = ord(code[i]) + ord(code[i+1])*256
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.
byte_increments = [ord(c) for c in code.co_lnotab[0::2]]
line_increments = [ord(c) for c in code.co_lnotab[1::2]]
lineno = code.co_firstlineno
for byte_incr, line_incr in zip(byte_increments, line_increments):
"""Simple test program to disassemble a file."""
sys.stderr.write("usage: python dis.py [-|file]\n")
code = compile(source, fn, "exec")
if __name__ == "__main__":