| 1 |
"""Disassembler of Python byte code into mnemonics. |
| 2 |
|
| 3 |
Comes from standard library, modified for the purpose of having a structured |
| 4 |
view on things |
| 5 |
""" |
| 6 |
|
| 7 |
from __future__ import print_function |
| 8 |
|
| 9 |
import sys |
| 10 |
import types |
| 11 |
import inspect |
| 12 |
|
| 13 |
from opcode import * |
| 14 |
from opcode import __all__ as _opcodes_all |
| 15 |
|
| 16 |
__all__ = ["dis","disassemble","distb","disco"] + _opcodes_all |
| 17 |
del _opcodes_all |
| 18 |
|
| 19 |
class Opcode(object): |
| 20 |
""" An abstract base class for all opcode implementations |
| 21 |
""" |
| 22 |
def __init__(self, pos, lineno, arg=None, argstr=''): |
| 23 |
self.pos = pos |
| 24 |
self.arg = arg |
| 25 |
self.argstr = argstr |
| 26 |
self.lineno = lineno |
| 27 |
self.line_starts_here = False |
| 28 |
|
| 29 |
def __str__(self): |
| 30 |
if self.arg is None: |
| 31 |
return "%s" % (self.__class__.__name__,) |
| 32 |
return "%s (%s)" % (self.__class__.__name__, self.arg) |
| 33 |
|
| 34 |
def __repr__(self): |
| 35 |
if self.arg is None: |
| 36 |
return "<%s at %d>" % (self.__class__.__name__, self.pos) |
| 37 |
return "<%s (%s) at %d>" % (self.__class__.__name__, self.arg, self.pos) |
| 38 |
|
| 39 |
class CodeRepresentation(object): |
| 40 |
""" Representation of opcodes |
| 41 |
""" |
| 42 |
def __init__(self, opcodes, co, source): |
| 43 |
self.opcodes = opcodes |
| 44 |
self.co = co |
| 45 |
self.map = {} |
| 46 |
current_lineno = None |
| 47 |
for opcode in opcodes: |
| 48 |
self.map[opcode.pos] = opcode |
| 49 |
if opcode.lineno != current_lineno: |
| 50 |
opcode.line_starts_here = True |
| 51 |
current_lineno = opcode.lineno |
| 52 |
self.source = source.split("\n") |
| 53 |
|
| 54 |
def get_opcode_from_info(self, info): |
| 55 |
return self.map[info.bytecode_no] |
| 56 |
|
| 57 |
@property |
| 58 |
def filename(self): |
| 59 |
return self.co.co_filename |
| 60 |
|
| 61 |
@property |
| 62 |
def startlineno(self): |
| 63 |
return self.co.co_firstlineno |
| 64 |
|
| 65 |
@property |
| 66 |
def name(self): |
| 67 |
return self.co.co_name |
| 68 |
|
| 69 |
def match_name(self, opcode_name): |
| 70 |
return self.__class__.__name__ == opcode_name |
| 71 |
|
| 72 |
|
| 73 |
def _setup(): |
| 74 |
for opcode in opname: |
| 75 |
if not opcode.startswith('<'): |
| 76 |
class O(Opcode): |
| 77 |
pass |
| 78 |
opcode = opcode.replace('+', '_') |
| 79 |
O.__name__ = opcode |
| 80 |
globals()[opcode] = O |
| 81 |
|
| 82 |
_setup() |
| 83 |
|
| 84 |
def dis(x=None): |
| 85 |
"""Disassemble classes, methods, functions, or code. |
| 86 |
|
| 87 |
With no argument, disassemble the last traceback. |
| 88 |
|
| 89 |
""" |
| 90 |
if x is None: |
| 91 |
distb() |
| 92 |
return |
| 93 |
if type(x) is types.InstanceType: |
| 94 |
x = x.__class__ |
| 95 |
if hasattr(x, 'im_func'): |
| 96 |
x = x.im_func |
| 97 |
if hasattr(x, 'func_code'): |
| 98 |
x = x.__code__ |
| 99 |
if hasattr(x, '__dict__'): |
| 100 |
xxx |
| 101 |
items = sorted(x.__dict__.items()) |
| 102 |
for name, x1 in items: |
| 103 |
if type(x1) in (types.MethodType, |
| 104 |
types.FunctionType, |
| 105 |
types.CodeType, |
| 106 |
types.ClassType): |
| 107 |
print("Disassembly of %s:" % name) |
| 108 |
try: |
| 109 |
dis(x1) |
| 110 |
except TypeError as msg: |
| 111 |
print("Sorry:", msg) |
| 112 |
print() |
| 113 |
elif hasattr(x, 'co_code'): |
| 114 |
return disassemble(x) |
| 115 |
elif isinstance(x, str): |
| 116 |
return disassemble_string(x) |
| 117 |
else: |
| 118 |
raise TypeError("don't know how to disassemble %s objects" % \ |
| 119 |
type(x).__name__) |
| 120 |
|
| 121 |
def distb(tb=None): |
| 122 |
"""Disassemble a traceback (default: last traceback).""" |
| 123 |
if tb is None: |
| 124 |
try: |
| 125 |
tb = sys.last_traceback |
| 126 |
except AttributeError: |
| 127 |
raise RuntimeError("no last traceback to disassemble") |
| 128 |
while tb.tb_next: tb = tb.tb_next |
| 129 |
disassemble(tb.tb_frame.f_code, tb.tb_lasti) |
| 130 |
|
| 131 |
def disassemble(co, lasti=-1): |
| 132 |
"""Disassemble a code object.""" |
| 133 |
source = inspect.getsource(co) |
| 134 |
code = co.co_code |
| 135 |
labels = findlabels(code) |
| 136 |
linestarts = dict(findlinestarts(co)) |
| 137 |
n = len(code) |
| 138 |
i = 0 |
| 139 |
extended_arg = 0 |
| 140 |
free = None |
| 141 |
res = [] |
| 142 |
lastline = co.co_firstlineno |
| 143 |
while i < n: |
| 144 |
c = code[i] |
| 145 |
op = ord(c) |
| 146 |
if i in linestarts: |
| 147 |
lastline = linestarts[i] |
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
|
| 156 |
|
| 157 |
|
| 158 |
|
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
pos = i |
| 163 |
i = i + 1 |
| 164 |
if op >= HAVE_ARGUMENT: |
| 165 |
oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg |
| 166 |
opargstr = str(oparg) |
| 167 |
extended_arg = 0 |
| 168 |
i = i+2 |
| 169 |
if op == EXTENDED_ARG: |
| 170 |
extended_arg = oparg*65536 |
| 171 |
if op in hasconst: |
| 172 |
opargstr = repr(co.co_consts[oparg]) |
| 173 |
elif op in hasname: |
| 174 |
opargstr = co.co_names[oparg] |
| 175 |
elif op in hasjrel: |
| 176 |
opargstr = 'to ' + repr(i + oparg) |
| 177 |
elif op in haslocal: |
| 178 |
opargstr = co.co_varnames[oparg] |
| 179 |
elif op in hascompare: |
| 180 |
opargstr = cmp_op[oparg] |
| 181 |
elif op in hasfree: |
| 182 |
if free is None: |
| 183 |
free = co.co_cellvars + co.co_freevars |
| 184 |
opargstr = free[oparg] |
| 185 |
else: |
| 186 |
oparg = None |
| 187 |
opargstr = '' |
| 188 |
opcls = globals()[opname[op].replace('+', '_')] |
| 189 |
res.append(opcls(pos, lastline, oparg, opargstr)) |
| 190 |
return CodeRepresentation(res, co, source) |
| 191 |
|
| 192 |
def disassemble_string(code, lasti=-1, varnames=None, names=None, |
| 193 |
constants=None): |
| 194 |
labels = findlabels(code) |
| 195 |
n = len(code) |
| 196 |
i = 0 |
| 197 |
while i < n: |
| 198 |
c = code[i] |
| 199 |
op = ord(c) |
| 200 |
if i == lasti: |
| 201 |
xxx |
| 202 |
print('-->', end=' ') |
| 203 |
else: |
| 204 |
xxx |
| 205 |
print(' ', end=' ') |
| 206 |
if i in labels: |
| 207 |
xxx |
| 208 |
print('>>', end=' ') |
| 209 |
else: |
| 210 |
xxx |
| 211 |
print(' ', end=' ') |
| 212 |
xxxx |
| 213 |
print(repr(i).rjust(4), end=' ') |
| 214 |
print(opname[op].ljust(15), end=' ') |
| 215 |
i = i+1 |
| 216 |
if op >= HAVE_ARGUMENT: |
| 217 |
oparg = ord(code[i]) + ord(code[i+1])*256 |
| 218 |
i = i+2 |
| 219 |
xxx |
| 220 |
print(repr(oparg).rjust(5), end=' ') |
| 221 |
if op in hasconst: |
| 222 |
if constants: |
| 223 |
xxx |
| 224 |
print('(' + repr(constants[oparg]) + ')', end=' ') |
| 225 |
else: |
| 226 |
xxx |
| 227 |
print('(%d)'%oparg, end=' ') |
| 228 |
elif op in hasname: |
| 229 |
if names is not None: |
| 230 |
xxx |
| 231 |
print('(' + names[oparg] + ')', end=' ') |
| 232 |
else: |
| 233 |
xxx |
| 234 |
print('(%d)'%oparg, end=' ') |
| 235 |
elif op in hasjrel: |
| 236 |
xxx |
| 237 |
print('(to ' + repr(i + oparg) + ')', end=' ') |
| 238 |
elif op in haslocal: |
| 239 |
if varnames: |
| 240 |
xxx |
| 241 |
print('(' + varnames[oparg] + ')', end=' ') |
| 242 |
else: |
| 243 |
xxx |
| 244 |
print('(%d)' % oparg, end=' ') |
| 245 |
elif op in hascompare: |
| 246 |
xxx |
| 247 |
print('(' + cmp_op[oparg] + ')', end=' ') |
| 248 |
xxx |
| 249 |
print() |
| 250 |
|
| 251 |
disco = disassemble |
| 252 |
|
| 253 |
def findlabels(code): |
| 254 |
"""Detect all offsets in a byte code which are jump targets. |
| 255 |
|
| 256 |
Return the list of offsets. |
| 257 |
|
| 258 |
""" |
| 259 |
labels = [] |
| 260 |
n = len(code) |
| 261 |
i = 0 |
| 262 |
while i < n: |
| 263 |
c = code[i] |
| 264 |
op = ord(c) |
| 265 |
i = i+1 |
| 266 |
if op >= HAVE_ARGUMENT: |
| 267 |
oparg = ord(code[i]) + ord(code[i+1])*256 |
| 268 |
i = i+2 |
| 269 |
label = -1 |
| 270 |
if op in hasjrel: |
| 271 |
label = i+oparg |
| 272 |
elif op in hasjabs: |
| 273 |
label = oparg |
| 274 |
if label >= 0: |
| 275 |
if label not in labels: |
| 276 |
labels.append(label) |
| 277 |
return labels |
| 278 |
|
| 279 |
def findlinestarts(code): |
| 280 |
"""Find the offsets in a byte code which are start of lines in the source. |
| 281 |
|
| 282 |
Generate pairs (offset, lineno) as described in Python/compile.c. |
| 283 |
|
| 284 |
""" |
| 285 |
byte_increments = [ord(c) for c in code.co_lnotab[0::2]] |
| 286 |
line_increments = [ord(c) for c in code.co_lnotab[1::2]] |
| 287 |
|
| 288 |
lastlineno = None |
| 289 |
lineno = code.co_firstlineno |
| 290 |
addr = 0 |
| 291 |
for byte_incr, line_incr in zip(byte_increments, line_increments): |
| 292 |
if byte_incr: |
| 293 |
if lineno != lastlineno: |
| 294 |
yield (addr, lineno) |
| 295 |
lastlineno = lineno |
| 296 |
addr += byte_incr |
| 297 |
lineno += line_incr |
| 298 |
if lineno != lastlineno: |
| 299 |
yield (addr, lineno) |
| 300 |
|
| 301 |
def _test(): |
| 302 |
"""Simple test program to disassemble a file.""" |
| 303 |
if sys.argv[1:]: |
| 304 |
if sys.argv[2:]: |
| 305 |
sys.stderr.write("usage: python dis.py [-|file]\n") |
| 306 |
sys.exit(2) |
| 307 |
fn = sys.argv[1] |
| 308 |
if not fn or fn == "-": |
| 309 |
fn = None |
| 310 |
else: |
| 311 |
fn = None |
| 312 |
if fn is None: |
| 313 |
f = sys.stdin |
| 314 |
else: |
| 315 |
f = open(fn) |
| 316 |
source = f.read() |
| 317 |
if fn is not None: |
| 318 |
f.close() |
| 319 |
else: |
| 320 |
fn = "<stdin>" |
| 321 |
code = compile(source, fn, "exec") |
| 322 |
dis(code) |