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