- Notifications
You must be signed in to change notification settings - Fork 31.7k
/
Copy pathdis.py
535 lines (473 loc) · 19.4 KB
/
dis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
"""Disassembler of Python byte code into mnemonics."""
importsys
importtypes
importcollections
importio
fromopcodeimport*
fromopcodeimport__all__as_opcodes_all
__all__= ["code_info", "dis", "disassemble", "distb", "disco",
"findlinestarts", "findlabels", "show_code",
"get_instructions", "Instruction", "Bytecode"] +_opcodes_all
del_opcodes_all
_have_code= (types.MethodType, types.FunctionType, types.CodeType,
classmethod, staticmethod, type)
FORMAT_VALUE=opmap['FORMAT_VALUE']
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')
exceptSyntaxError:
c=compile(source, name, 'exec')
returnc
defdis(x=None, *, file=None, depth=None):
"""Disassemble classes, methods, functions, and other compiled objects.
With no argument, disassemble the last traceback.
Compiled objects currently include generator objects, async generator
objects, and coroutine objects, all of which store their code object
in a special attribute.
"""
ifxisNone:
distb(file=file)
return
# Extract functions from methods.
ifhasattr(x, '__func__'):
x=x.__func__
# Extract compiled code objects from...
ifhasattr(x, '__code__'): # ...a function, or
x=x.__code__
elifhasattr(x, 'gi_code'): #...a generator object, or
x=x.gi_code
elifhasattr(x, 'ag_code'): #...an asynchronous generator object, or
x=x.ag_code
elifhasattr(x, 'cr_code'): #...a coroutine.
x=x.cr_code
# Perform the disassembly.
ifhasattr(x, '__dict__'): # Class or module
items=sorted(x.__dict__.items())
forname, x1initems:
ifisinstance(x1, _have_code):
print("Disassembly of %s:"%name, file=file)
try:
dis(x1, file=file, depth=depth)
exceptTypeErrorasmsg:
print("Sorry:", msg, file=file)
print(file=file)
elifhasattr(x, 'co_code'): # Code object
_disassemble_recursive(x, file=file, depth=depth)
elifisinstance(x, (bytes, bytearray)): # Raw bytecode
_disassemble_bytes(x, file=file)
elifisinstance(x, str): # Source code
_disassemble_str(x, file=file, depth=depth)
else:
raiseTypeError("don't know how to disassemble %s objects"%
type(x).__name__)
defdistb(tb=None, *, file=None):
"""Disassemble a traceback (default: last traceback)."""
iftbisNone:
try:
tb=sys.last_traceback
exceptAttributeError:
raiseRuntimeError("no last traceback to disassemble") fromNone
whiletb.tb_next: tb=tb.tb_next
disassemble(tb.tb_frame.f_code, tb.tb_lasti, file=file)
# 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= {
1: "OPTIMIZED",
2: "NEWLOCALS",
4: "VARARGS",
8: "VARKEYWORDS",
16: "NESTED",
32: "GENERATOR",
64: "NOFREE",
128: "COROUTINE",
256: "ITERABLE_COROUTINE",
512: "ASYNC_GENERATOR",
}
defpretty_flags(flags):
"""Return pretty representation of code flags."""
names= []
foriinrange(32):
flag=1<<i
ifflags&flag:
names.append(COMPILER_FLAG_NAMES.get(flag, hex(flag)))
flags^=flag
ifnotflags:
break
else:
names.append(hex(flags))
return", ".join(names)
def_get_code_object(x):
"""Helper to handle methods, compiled or raw code objects, and strings."""
# Extract functions from methods.
ifhasattr(x, '__func__'):
x=x.__func__
# Extract compiled code objects from...
ifhasattr(x, '__code__'): # ...a function, or
x=x.__code__
elifhasattr(x, 'gi_code'): #...a generator object, or
x=x.gi_code
elifhasattr(x, 'ag_code'): #...an asynchronous generator object, or
x=x.ag_code
elifhasattr(x, 'cr_code'): #...a coroutine.
x=x.cr_code
# Handle source code.
ifisinstance(x, str):
x=_try_compile(x, "<disassembly>")
# By now, if we don't have a code object, we can't disassemble x.
ifhasattr(x, 'co_code'):
returnx
raiseTypeError("don't know how to disassemble %s objects"%
type(x).__name__)
defcode_info(x):
"""Formatted details of methods, functions, or code."""
return_format_code_info(_get_code_object(x))
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))
ifco.co_consts:
lines.append("Constants:")
fori_cinenumerate(co.co_consts):
lines.append("%4d: %r"%i_c)
ifco.co_names:
lines.append("Names:")
fori_ninenumerate(co.co_names):
lines.append("%4d: %s"%i_n)
ifco.co_varnames:
lines.append("Variable names:")
fori_ninenumerate(co.co_varnames):
lines.append("%4d: %s"%i_n)
ifco.co_freevars:
lines.append("Free variables:")
fori_ninenumerate(co.co_freevars):
lines.append("%4d: %s"%i_n)
ifco.co_cellvars:
lines.append("Cell variables:")
fori_ninenumerate(co.co_cellvars):
lines.append("%4d: %s"%i_n)
return"\n".join(lines)
defshow_code(co, *, file=None):
"""Print details of methods, functions, or code to *file*.
If *file* is not provided, the output is printed on stdout.
"""
print(code_info(co), file=file)
_Instruction=collections.namedtuple("_Instruction",
"opname opcode arg argval argrepr offset starts_line is_jump_target")
_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"
_OPNAME_WIDTH=20
_OPARG_WIDTH=5
classInstruction(_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
"""
def_disassemble(self, lineno_width=3, mark_as_current=False, offset_width=4):
"""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
*offset_width* sets the width of the instruction offset field
"""
fields= []
# Column: Source code line number
iflineno_width:
ifself.starts_lineisnotNone:
lineno_fmt="%%%dd"%lineno_width
fields.append(lineno_fmt%self.starts_line)
else:
fields.append(' '*lineno_width)
# Column: Current instruction indicator
ifmark_as_current:
fields.append('-->')
else:
fields.append(' ')
# Column: Jump target marker
ifself.is_jump_target:
fields.append('>>')
else:
fields.append(' ')
# Column: Instruction offset from start of code sequence
fields.append(repr(self.offset).rjust(offset_width))
# Column: Opcode name
fields.append(self.opname.ljust(_OPNAME_WIDTH))
# Column: Opcode argument
ifself.argisnotNone:
fields.append(repr(self.arg).rjust(_OPARG_WIDTH))
# Column: Opcode argument details
ifself.argrepr:
fields.append('('+self.argrepr+')')
return' '.join(fields).rstrip()
defget_instructions(x, *, first_line=None):
"""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.
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.
"""
co=_get_code_object(x)
cell_names=co.co_cellvars+co.co_freevars
linestarts=dict(findlinestarts(co))
iffirst_lineisnotNone:
line_offset=first_line-co.co_firstlineno
else:
line_offset=0
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
ifconst_listisnotNone:
argval=const_list[const_index]
returnargval, 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
ifname_listisnotNone:
argval=name_list[name_index]
argrepr=argval
else:
argrepr=repr(argval)
returnargval, 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
foroffset, op, argin_unpack_opargs(code):
iflinestartsisnotNone:
starts_line=linestarts.get(offset, None)
ifstarts_lineisnotNone:
starts_line+=line_offset
is_jump_target=offsetinlabels
argval=None
argrepr=''
ifargisnotNone:
# Set argval to the dereferenced value of the argument when
# available, and argrepr to the string representation of argval.
# _disassemble_bytes needs the string repr of the
# raw name index for LOAD_GLOBAL, LOAD_CONST, etc.
argval=arg
ifopinhasconst:
argval, argrepr=_get_const_info(arg, constants)
elifopinhasname:
argval, argrepr=_get_name_info(arg, names)
elifopinhasjrel:
argval=offset+2+arg
argrepr="to "+repr(argval)
elifopinhaslocal:
argval, argrepr=_get_name_info(arg, varnames)
elifopinhascompare:
argval=cmp_op[arg]
argrepr=argval
elifopinhasfree:
argval, argrepr=_get_name_info(arg, cells)
elifop==FORMAT_VALUE:
argval= ((None, str, repr, ascii)[arg&0x3], bool(arg&0x4))
argrepr= ('', 'str', 'repr', 'ascii')[arg&0x3]
ifargval[1]:
ifargrepr:
argrepr+=', '
argrepr+='with format'
yieldInstruction(opname[op], op,
arg, argval, argrepr,
offset, starts_line, is_jump_target)
defdisassemble(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)
def_disassemble_recursive(co, *, file=None, depth=None):
disassemble(co, file=file)
ifdepthisNoneordepth>0:
ifdepthisnotNone:
depth=depth-1
forxinco.co_consts:
ifhasattr(x, 'co_code'):
print(file=file)
print("Disassembly of %r:"% (x,), file=file)
_disassemble_recursive(x, file=file, depth=depth)
def_disassemble_bytes(code, lasti=-1, varnames=None, names=None,
constants=None, cells=None, linestarts=None,
*, file=None, line_offset=0):
# Omit the line number column entirely if we have no line number info
show_lineno=linestartsisnotNone
ifshow_lineno:
maxlineno=max(linestarts.values()) +line_offset
ifmaxlineno>=1000:
lineno_width=len(str(maxlineno))
else:
lineno_width=3
else:
lineno_width=0
maxoffset=len(code) -2
ifmaxoffset>=10000:
offset_width=len(str(maxoffset))
else:
offset_width=4
forinstrin_get_instructions_bytes(code, varnames, names,
constants, cells, linestarts,
line_offset=line_offset):
new_source_line= (show_linenoand
instr.starts_lineisnotNoneand
instr.offset>0)
ifnew_source_line:
print(file=file)
is_current_instr=instr.offset==lasti
print(instr._disassemble(lineno_width, is_current_instr, offset_width),
file=file)
def_disassemble_str(source, **kwargs):
"""Compile the source string, then disassemble the code object."""
_disassemble_recursive(_try_compile(source, '<dis>'), **kwargs)
disco=disassemble# XXX For backwards compatibility
def_unpack_opargs(code):
extended_arg=0
foriinrange(0, len(code), 2):
op=code[i]
ifop>=HAVE_ARGUMENT:
arg=code[i+1] |extended_arg
extended_arg= (arg<<8) ifop==EXTENDED_ARGelse0
else:
arg=None
yield (i, op, arg)
deffindlabels(code):
"""Detect all offsets in a byte code which are jump targets.
Return the list of offsets.
"""
labels= []
foroffset, op, argin_unpack_opargs(code):
ifargisnotNone:
ifopinhasjrel:
label=offset+2+arg
elifopinhasjabs:
label=arg
else:
continue
iflabelnotinlabels:
labels.append(label)
returnlabels
deffindlinestarts(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=code.co_lnotab[0::2]
line_increments=code.co_lnotab[1::2]
lastlineno=None
lineno=code.co_firstlineno
addr=0
forbyte_incr, line_incrinzip(byte_increments, line_increments):
ifbyte_incr:
iflineno!=lastlineno:
yield (addr, lineno)
lastlineno=lineno
addr+=byte_incr
ifline_incr>=0x80:
# line_increments is an array of 8-bit signed integers
line_incr-=0x100
lineno+=line_incr
iflineno!=lastlineno:
yield (addr, lineno)
classBytecode:
"""The bytecode operations of a piece of code
Instantiate this with a function, method, other compiled object, string of
code, or a code object (as returned by compile()).
Iterating over this yields the bytecode operations as Instruction instances.
"""
def__init__(self, x, *, first_line=None, current_offset=None):
self.codeobj=co=_get_code_object(x)
iffirst_lineisNone:
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
self.current_offset=current_offset
def__iter__(self):
co=self.codeobj
return_get_instructions_bytes(co.co_code, co.co_varnames, co.co_names,
co.co_consts, self._cell_names,
self._linestarts,
line_offset=self._line_offset)
def__repr__(self):
return"{}({!r})".format(self.__class__.__name__,
self._original_object)
@classmethod
deffrom_traceback(cls, tb):
""" Construct a Bytecode from the given traceback """
whiletb.tb_next:
tb=tb.tb_next
returncls(tb.tb_frame.f_code, current_offset=tb.tb_lasti)
definfo(self):
"""Return formatted information about the code object."""
return_format_code_info(self.codeobj)
defdis(self):
"""Return a formatted view of the bytecode operations."""
co=self.codeobj
ifself.current_offsetisnotNone:
offset=self.current_offset
else:
offset=-1
withio.StringIO() asoutput:
_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,
file=output,
lasti=offset)
returnoutput.getvalue()
def_test():
"""Simple test program to disassemble a file."""
importargparse
parser=argparse.ArgumentParser()
parser.add_argument('infile', type=argparse.FileType(), nargs='?', default='-')
args=parser.parse_args()
withargs.infileasinfile:
source=infile.read()
code=compile(source, args.infile.name, "exec")
dis(code)
if__name__=="__main__":
_test()