Debian Codegraph @

lib-python/3/dis.py

raw symbols SCIP
1 """Disassembler of Python byte code into mnemonics."""
2
3 import sys
4 import types
5 import collections
6 import io
7
8 from opcode import *
9 from opcode import (
10 __all__ as _opcodes_all,
11 _cache_format,
12 _inline_cache_entries,
13 _nb_ops,
14 _specializations,
15 _specialized_instructions,
16 )
17
18 __all__ = ["code_info", "dis", "disassemble", "distb", "disco",
19 "findlinestarts", "findlabels", "show_code",
20 "get_instructions", "Instruction", "Bytecode"] + _opcodes_all
21 del _opcodes_all
22
23 _have_code = (types.MethodType, types.FunctionType, types.CodeType,
24 classmethod, staticmethod, type)
25
26 FORMAT_VALUE = opmap['FORMAT_VALUE']
27 FORMAT_VALUE_CONVERTERS = (
28 (None, ''),
29 (str, 'str'),
30 (repr, 'repr'),
31 (ascii, 'ascii'),
32 )
33 MAKE_FUNCTION = opmap['MAKE_FUNCTION']
34 MAKE_FUNCTION_FLAGS = ('defaults', 'kwdefaults', 'annotations', 'closure')
35
36 LOAD_CONST = opmap['LOAD_CONST']
37 LOAD_GLOBAL = opmap['LOAD_GLOBAL']
38 BINARY_OP = -1 ## opmap['BINARY_OP']
39 JUMP_BACKWARD = -1 ## opmap['JUMP_BACKWARD']
40
41 CACHE = 0 ## opmap["CACHE"]
42
43 _all_opname = list(opname)
44 _all_opmap = dict(opmap)
45 _empty_slot = [slot for slot, name in enumerate(_all_opname) if name.startswith("<")]
46 for spec_op, specialized in zip(_empty_slot, _specialized_instructions):
47 # fill opname and opmap
48 _all_opname[spec_op] = specialized
49 _all_opmap[specialized] = spec_op
50
51 deoptmap = {
52 specialized: base for base, family in _specializations.items() for specialized in family
53 }
54
55 def _try_compile(source, name):
56 """Attempts to compile the given source, first as an expression and
57 then as a statement if the first approach fails.
58
59 Utility function to accept strings in functions that otherwise
60 expect code objects
61 """
62 try:
63 c = compile(source, name, 'eval')
64 except SyntaxError:
65 c = compile(source, name, 'exec')
66 return c
67
68 def dis(x=None, *, file=None, depth=None, show_caches=False, adaptive=False):
69 """Disassemble classes, methods, functions, and other compiled objects.
70
71 With no argument, disassemble the last traceback.
72
73 Compiled objects currently include generator objects, async generator
74 objects, and coroutine objects, all of which store their code object
75 in a special attribute.
76 """
77 if x is None:
78 distb(file=file, show_caches=show_caches, adaptive=adaptive)
79 return
80 # Extract functions from methods.
81 if hasattr(x, '__func__'):
82 x = x.__func__
83 # Extract compiled code objects from...
84 if hasattr(x, '__code__'): # ...a function, or
85 x = x.__code__
86 elif hasattr(x, 'gi_code'): #...a generator object, or
87 x = x.gi_code
88 elif hasattr(x, 'ag_code'): #...an asynchronous generator object, or
89 x = x.ag_code
90 elif hasattr(x, 'cr_code'): #...a coroutine.
91 x = x.cr_code
92 # Perform the disassembly.
93 if hasattr(x, '__dict__'): # Class or module
94 items = sorted(x.__dict__.items())
95 for name, x1 in items:
96 if isinstance(x1, _have_code):
97 print("Disassembly of %s:" % name, file=file)
98 try:
99 dis(x1, file=file, depth=depth, show_caches=show_caches, adaptive=adaptive)
100 except TypeError as msg:
101 print("Sorry:", msg, file=file)
102 print(file=file)
103 elif hasattr(x, 'co_code'): # Code object
104 _disassemble_recursive(x, file=file, depth=depth, show_caches=show_caches, adaptive=adaptive)
105 elif isinstance(x, (bytes, bytearray)): # Raw bytecode
106 _disassemble_bytes(x, file=file, show_caches=show_caches)
107 elif isinstance(x, str): # Source code
108 _disassemble_str(x, file=file, depth=depth, show_caches=show_caches, adaptive=adaptive)
109 else:
110 raise TypeError("don't know how to disassemble %s objects" %
111 type(x).__name__)
112
113 def distb(tb=None, *, file=None, show_caches=False, adaptive=False):
114 """Disassemble a traceback (default: last traceback)."""
115 if tb is None:
116 try:
117 tb = sys.last_traceback
118 except AttributeError:
119 raise RuntimeError("no last traceback to disassemble") from None
120 while tb.tb_next: tb = tb.tb_next
121 disassemble(tb.tb_frame.f_code, tb.tb_lasti, file=file, show_caches=show_caches, adaptive=adaptive)
122
123 # The inspect module interrogates this dictionary to build its
124 # list of CO_* constants. It is also used by pretty_flags to
125 # turn the co_flags field into a human readable list.
126 COMPILER_FLAG_NAMES = {
127 1: "OPTIMIZED",
128 2: "NEWLOCALS",
129 4: "VARARGS",
130 8: "VARKEYWORDS",
131 16: "NESTED",
132 32: "GENERATOR",
133 64: "NOFREE",
134 128: "COROUTINE",
135 256: "ITERABLE_COROUTINE",
136 512: "ASYNC_GENERATOR",
137 }
138
139 def pretty_flags(flags):
140 """Return pretty representation of code flags."""
141 names = []
142 for i in range(32):
143 flag = 1<<i
144 if flags & flag:
145 names.append(COMPILER_FLAG_NAMES.get(flag, hex(flag)))
146 flags ^= flag
147 if not flags:
148 break
149 else:
150 names.append(hex(flags))
151 return ", ".join(names)
152
153 class _Unknown:
154 def __repr__(self):
155 return "<unknown>"
156
157 # Sentinel to represent values that cannot be calculated
158 UNKNOWN = _Unknown()
159
160 def _get_code_object(x):
161 """Helper to handle methods, compiled or raw code objects, and strings."""
162 # Extract functions from methods.
163 if hasattr(x, '__func__'):
164 x = x.__func__
165 # Extract compiled code objects from...
166 if hasattr(x, '__code__'): # ...a function, or
167 x = x.__code__
168 elif hasattr(x, 'gi_code'): #...a generator object, or
169 x = x.gi_code
170 elif hasattr(x, 'ag_code'): #...an asynchronous generator object, or
171 x = x.ag_code
172 elif hasattr(x, 'cr_code'): #...a coroutine.
173 x = x.cr_code
174 # Handle source code.
175 if isinstance(x, str):
176 x = _try_compile(x, "<disassembly>")
177 # By now, if we don't have a code object, we can't disassemble x.
178 if hasattr(x, 'co_code'):
179 return x
180 raise TypeError("don't know how to disassemble %s objects" %
181 type(x).__name__)
182
183 def _deoptop(op):
184 name = _all_opname[op]
185 return _all_opmap[deoptmap[name]] if name in deoptmap else op
186
187 def _get_code_array(co, adaptive):
188 return co._co_code_adaptive if adaptive else co.co_code
189
190 def code_info(x):
191 """Formatted details of methods, functions, or code."""
192 return _format_code_info(_get_code_object(x))
193
194 def _format_code_info(co):
195 lines = []
196 lines.append("Name: %s" % co.co_name)
197 lines.append("Filename: %s" % co.co_filename)
198 lines.append("Argument count: %s" % co.co_argcount)
199 lines.append("Positional-only arguments: %s" % co.co_posonlyargcount)
200 lines.append("Kw-only arguments: %s" % co.co_kwonlyargcount)
201 lines.append("Number of locals: %s" % co.co_nlocals)
202 lines.append("Stack size: %s" % co.co_stacksize)
203 lines.append("Flags: %s" % pretty_flags(co.co_flags))
204 if co.co_consts:
205 lines.append("Constants:")
206 for i_c in enumerate(co.co_consts):
207 lines.append("%4d: %r" % i_c)
208 if co.co_names:
209 lines.append("Names:")
210 for i_n in enumerate(co.co_names):
211 lines.append("%4d: %s" % i_n)
212 if co.co_varnames:
213 lines.append("Variable names:")
214 for i_n in enumerate(co.co_varnames):
215 lines.append("%4d: %s" % i_n)
216 if co.co_freevars:
217 lines.append("Free variables:")
218 for i_n in enumerate(co.co_freevars):
219 lines.append("%4d: %s" % i_n)
220 if co.co_cellvars:
221 lines.append("Cell variables:")
222 for i_n in enumerate(co.co_cellvars):
223 lines.append("%4d: %s" % i_n)
224 return "\n".join(lines)
225
226 def show_code(co, *, file=None):
227 """Print details of methods, functions, or code to *file*.
228
229 If *file* is not provided, the output is printed on stdout.
230 """
231 print(code_info(co), file=file)
232
233 Positions = collections.namedtuple(
234 'Positions',
235 [
236 'lineno',
237 'end_lineno',
238 'col_offset',
239 'end_col_offset',
240 ],
241 defaults=[None] * 4
242 )
243
244 _Instruction = collections.namedtuple(
245 "_Instruction",
246 [
247 'opname',
248 'opcode',
249 'arg',
250 'argval',
251 'argrepr',
252 'offset',
253 'starts_line',
254 'is_jump_target',
255 'positions'
256 ],
257 defaults=[None]
258 )
259
260 _Instruction.opname.__doc__ = "Human readable name for operation"
261 _Instruction.opcode.__doc__ = "Numeric code for operation"
262 _Instruction.arg.__doc__ = "Numeric argument to operation (if any), otherwise None"
263 _Instruction.argval.__doc__ = "Resolved arg value (if known), otherwise same as arg"
264 _Instruction.argrepr.__doc__ = "Human readable description of operation argument"
265 _Instruction.offset.__doc__ = "Start index of operation within bytecode sequence"
266 _Instruction.starts_line.__doc__ = "Line started by this opcode (if any), otherwise None"
267 _Instruction.is_jump_target.__doc__ = "True if other code jumps to here, otherwise False"
268 _Instruction.positions.__doc__ = "dis.Positions object holding the span of source code covered by this instruction"
269
270 _ExceptionTableEntry = collections.namedtuple("_ExceptionTableEntry",
271 "start end target depth lasti")
272
273 _OPNAME_WIDTH = 20
274 _OPARG_WIDTH = 5
275
276 class Instruction(_Instruction):
277 """Details for a bytecode operation
278
279 Defined fields:
280 opname - human readable name for operation
281 opcode - numeric code for operation
282 arg - numeric argument to operation (if any), otherwise None
283 argval - resolved arg value (if known), otherwise same as arg
284 argrepr - human readable description of operation argument
285 offset - start index of operation within bytecode sequence
286 starts_line - line started by this opcode (if any), otherwise None
287 is_jump_target - True if other code jumps to here, otherwise False
288 positions - Optional dis.Positions object holding the span of source code
289 covered by this instruction
290 """
291
292 def _disassemble(self, lineno_width=3, mark_as_current=False, offset_width=4):
293 """Format instruction details for inclusion in disassembly output
294
295 *lineno_width* sets the width of the line number field (0 omits it)
296 *mark_as_current* inserts a '-->' marker arrow as part of the line
297 *offset_width* sets the width of the instruction offset field
298 """
299 fields = []
300 # Column: Source code line number
301 if lineno_width:
302 if self.starts_line is not None:
303 lineno_fmt = "%%%dd" % lineno_width
304 fields.append(lineno_fmt % self.starts_line)
305 else:
306 fields.append(' ' * lineno_width)
307 # Column: Current instruction indicator
308 if mark_as_current:
309 fields.append('-->')
310 else:
311 fields.append(' ')
312 # Column: Jump target marker
313 if self.is_jump_target:
314 fields.append('>>')
315 else:
316 fields.append(' ')
317 # Column: Instruction offset from start of code sequence
318 fields.append(repr(self.offset).rjust(offset_width))
319 # Column: Opcode name
320 fields.append(self.opname.ljust(_OPNAME_WIDTH))
321 # Column: Opcode argument
322 if self.arg is not None:
323 fields.append(repr(self.arg).rjust(_OPARG_WIDTH))
324 # Column: Opcode argument details
325 if self.argrepr:
326 fields.append('(' + self.argrepr + ')')
327 return ' '.join(fields).rstrip()
328
329
330 def get_instructions(x, *, first_line=None, show_caches=False, adaptive=False):
331 """Iterator for the opcodes in methods, functions or code
332
333 Generates a series of Instruction named tuples giving the details of
334 each operations in the supplied code.
335
336 If *first_line* is not None, it indicates the line number that should
337 be reported for the first source line in the disassembled code.
338 Otherwise, the source line information (if any) is taken directly from
339 the disassembled code object.
340 """
341 co = _get_code_object(x)
342 linestarts = dict(findlinestarts(co))
343 if first_line is not None:
344 line_offset = first_line - co.co_firstlineno
345 else:
346 line_offset = 0
347 try:
348 varname_from_oparg = co._varname_from_oparg
349 except AttributeError:
350 varname_from_oparg = None
351 return _get_instructions_bytes(_get_code_array(co, adaptive),
352 varname_from_oparg,
353 co.co_names, co.co_consts,
354 linestarts, line_offset,
355 co_positions=co.co_positions(),
356 show_caches=show_caches)
357
358 def _get_const_value(op, arg, co_consts):
359 """Helper to get the value of the const in a hasconst op.
360
361 Returns the dereferenced constant if this is possible.
362 Otherwise (if it is a LOAD_CONST and co_consts is not
363 provided) returns the dis.UNKNOWN sentinel.
364 """
365 assert op in hasconst
366
367 argval = UNKNOWN
368 if op == LOAD_CONST:
369 if co_consts is not None:
370 argval = co_consts[arg]
371 return argval
372
373 def _get_const_info(op, arg, co_consts):
374 """Helper to get optional details about const references
375
376 Returns the dereferenced constant and its repr if the value
377 can be calculated.
378 Otherwise returns the sentinel value dis.UNKNOWN for the value
379 and an empty string for its repr.
380 """
381 argval = _get_const_value(op, arg, co_consts)
382 argrepr = repr(argval) if argval is not UNKNOWN else ''
383 return argval, argrepr
384
385 def _get_name_info(name_index, get_name, **extrainfo):
386 """Helper to get optional details about named references
387
388 Returns the dereferenced name as both value and repr if the name
389 list is defined.
390 Otherwise returns the sentinel value dis.UNKNOWN for the value
391 and an empty string for its repr.
392 """
393 if get_name is not None:
394 argval = get_name(name_index, **extrainfo)
395 return argval, argval
396 else:
397 return UNKNOWN, ''
398
399 def _parse_varint(iterator):
400 b = next(iterator)
401 val = b & 63
402 while b&64:
403 val <<= 6
404 b = next(iterator)
405 val |= b&63
406 return val
407
408 def _parse_exception_table(code):
409 try:
410 co_exceptiontable = code.co_exceptiontable
411 except AttributeError:
412 co_exceptiontable = []
413 iterator = iter(co_exceptiontable)
414 entries = []
415 try:
416 while True:
417 start = _parse_varint(iterator)*2
418 length = _parse_varint(iterator)*2
419 end = start + length
420 target = _parse_varint(iterator)*2
421 dl = _parse_varint(iterator)
422 depth = dl >> 1
423 lasti = bool(dl&1)
424 entries.append(_ExceptionTableEntry(start, end, target, depth, lasti))
425 except StopIteration:
426 return entries
427
428 def _is_backward_jump(op):
429 return 'JUMP_BACKWARD' in opname[op]
430
431 def _get_instructions_bytes(code, varname_from_oparg=None,
432 names=None, co_consts=None,
433 linestarts=None, line_offset=0,
434 exception_entries=(), co_positions=None,
435 show_caches=False):
436 """Iterate over the instructions in a bytecode string.
437
438 Generates a sequence of Instruction namedtuples giving the details of each
439 opcode. Additional information about the code's runtime environment
440 (e.g. variable names, co_consts) can be specified using optional
441 arguments.
442
443 """
444 co_positions = iter(co_positions) or iter(())
445 get_name = None if names is None else names.__getitem__
446 labels = set(findlabels(code))
447 for start, end, target, _, _ in exception_entries:
448 for i in range(start, end):
449 labels.add(target)
450 starts_line = None
451 for offset, op, arg in _unpack_opargs(code):
452 if linestarts is not None:
453 starts_line = linestarts.get(offset, None)
454 if starts_line is not None:
455 starts_line += line_offset
456 is_jump_target = offset in labels
457 argval = None
458 argrepr = ''
459 positions = Positions(*next(co_positions, ()))
460 deop = _deoptop(op)
461 if arg is not None:
462 # Set argval to the dereferenced value of the argument when
463 # available, and argrepr to the string representation of argval.
464 # _disassemble_bytes needs the string repr of the
465 # raw name index for LOAD_GLOBAL, LOAD_CONST, etc.
466 argval = arg
467 if deop in hasconst:
468 argval, argrepr = _get_const_info(deop, arg, co_consts)
469 elif deop in hasname:
470 # pypy change: PyPy3.11 did not change LOAD_GLOBAL semantics
471 if deop == LOAD_GLOBAL and not "__pypy__" in sys.builtin_module_names:
472 argval, argrepr = _get_name_info(arg//2, get_name)
473 if (arg & 1) and argrepr:
474 argrepr = "NULL + " + argrepr
475 else:
476 argval, argrepr = _get_name_info(arg, get_name)
477 elif deop in hasjabs:
478 argval = arg*2
479 argrepr = "to " + repr(argval)
480 elif deop in hasjrel:
481 signed_arg = -arg if _is_backward_jump(deop) else arg
482 argval = offset + 2 + signed_arg*2
483 argrepr = "to " + repr(argval)
484 elif deop in haslocal or deop in hasfree:
485 argval, argrepr = _get_name_info(arg, varname_from_oparg)
486 elif deop in hascompare:
487 argval = cmp_op[arg]
488 argrepr = argval
489 elif deop == FORMAT_VALUE:
490 argval, argrepr = FORMAT_VALUE_CONVERTERS[arg & 0x3]
491 argval = (argval, bool(arg & 0x4))
492 if argval[1]:
493 if argrepr:
494 argrepr += ', '
495 argrepr += 'with format'
496 elif deop == MAKE_FUNCTION:
497 argrepr = ', '.join(s for i, s in enumerate(MAKE_FUNCTION_FLAGS)
498 if arg & (1<<i))
499 elif deop == BINARY_OP:
500 _, argrepr = _nb_ops[arg]
501 yield Instruction(_all_opname[op], op,
502 arg, argval, argrepr,
503 offset, starts_line, is_jump_target, positions)
504 caches = _inline_cache_entries[deop]
505 if not caches:
506 continue
507 if not show_caches:
508 # We still need to advance the co_positions iterator:
509 for _ in range(caches):
510 next(co_positions, ())
511 continue
512 for name, size in _cache_format[opname[deop]].items():
513 for i in range(size):
514 offset += 2
515 # Only show the fancy argrepr for a CACHE instruction when it's
516 # the first entry for a particular cache value and the
517 # instruction using it is actually quickened:
518 if i == 0 and op != deop:
519 data = code[offset: offset + 2 * size]
520 argrepr = f"{name}: {int.from_bytes(data, sys.byteorder)}"
521 else:
522 argrepr = ""
523 yield Instruction(
524 "CACHE", CACHE, 0, None, argrepr, offset, None, False,
525 Positions(*next(co_positions, ()))
526 )
527
528 def disassemble(co, lasti=-1, *, file=None, show_caches=False, adaptive=False):
529 """Disassemble a code object."""
530 linestarts = dict(findlinestarts(co))
531 exception_entries = _parse_exception_table(co)
532 try:
533 varname_from_oparg = co._varname_from_oparg
534 except AttributeError:
535 varname_from_oparg = None
536 _disassemble_bytes(_get_code_array(co, adaptive),
537 lasti, varname_from_oparg,
538 co.co_names, co.co_consts, linestarts, file=file,
539 exception_entries=exception_entries,
540 co_positions=co.co_positions(), show_caches=show_caches)
541
542 def _disassemble_recursive(co, *, file=None, depth=None, show_caches=False, adaptive=False):
543 disassemble(co, file=file, show_caches=show_caches, adaptive=adaptive)
544 if depth is None or depth > 0:
545 if depth is not None:
546 depth = depth - 1
547 for x in co.co_consts:
548 if hasattr(x, 'co_code'):
549 print(file=file)
550 print("Disassembly of %r:" % (x,), file=file)
551 _disassemble_recursive(
552 x, file=file, depth=depth, show_caches=show_caches, adaptive=adaptive
553 )
554
555 def _disassemble_bytes(code, lasti=-1, varname_from_oparg=None,
556 names=None, co_consts=None, linestarts=None,
557 *, file=None, line_offset=0, exception_entries=(),
558 co_positions=None, show_caches=False):
559 # Omit the line number column entirely if we have no line number info
560 show_lineno = bool(linestarts)
561 if show_lineno:
562 maxlineno = max(linestarts.values()) + line_offset
563 if maxlineno >= 1000:
564 lineno_width = len(str(maxlineno))
565 else:
566 lineno_width = 3
567 else:
568 lineno_width = 0
569 maxoffset = len(code) - 2
570 if maxoffset >= 10000:
571 offset_width = len(str(maxoffset))
572 else:
573 offset_width = 4
574 for instr in _get_instructions_bytes(code, varname_from_oparg, names,
575 co_consts, linestarts,
576 line_offset=line_offset,
577 exception_entries=exception_entries,
578 co_positions=co_positions,
579 show_caches=show_caches):
580 new_source_line = (show_lineno and
581 instr.starts_line is not None and
582 instr.offset > 0)
583 if new_source_line:
584 print(file=file)
585 is_current_instr = instr.offset == lasti
586 print(instr._disassemble(lineno_width, is_current_instr, offset_width),
587 file=file)
588 if exception_entries:
589 print("ExceptionTable:", file=file)
590 for entry in exception_entries:
591 lasti = " lasti" if entry.lasti else ""
592 end = entry.end-2
593 print(f" {entry.start} to {end} -> {entry.target} [{entry.depth}]{lasti}", file=file)
594
595 def _disassemble_str(source, **kwargs):
596 """Compile the source string, then disassemble the code object."""
597 _disassemble_recursive(_try_compile(source, '<dis>'), **kwargs)
598
599 disco = disassemble # XXX For backwards compatibility
600
601
602 # Rely on C `int` being 32 bits for oparg
603 _INT_BITS = 32
604 # Value for c int when it overflows
605 _INT_OVERFLOW = 2 ** (_INT_BITS - 1)
606
607 def _unpack_opargs(code):
608 extended_arg = 0
609 caches = 0
610 for i in range(0, len(code), 2):
611 # Skip inline CACHE entries:
612 if caches:
613 caches -= 1
614 continue
615 op = code[i]
616 deop = _deoptop(op)
617 caches = _inline_cache_entries[deop]
618 if deop >= HAVE_ARGUMENT:
619 arg = code[i+1] | extended_arg
620 extended_arg = (arg << 8) if deop == EXTENDED_ARG else 0
621 # The oparg is stored as a signed integer
622 # If the value exceeds its upper limit, it will overflow and wrap
623 # to a negative integer
624 if extended_arg >= _INT_OVERFLOW:
625 extended_arg -= 2 * _INT_OVERFLOW
626 else:
627 arg = None
628 extended_arg = 0
629 yield (i, op, arg)
630
631 def findlabels(code):
632 """Detect all offsets in a byte code which are jump targets.
633
634 Return the list of offsets.
635
636 """
637 labels = []
638 for offset, op, arg in _unpack_opargs(code):
639 if arg is not None:
640 if op in hasjrel:
641 if _is_backward_jump(op):
642 arg = -arg
643 label = offset + 2 + arg*2
644 elif op in hasjabs:
645 label = arg*2
646 else:
647 continue
648 if label not in labels:
649 labels.append(label)
650 return labels
651
652 def findlinestarts(code):
653 """Find the offsets in a byte code which are start of lines in the source.
654
655 Generate pairs (offset, lineno)
656 """
657 lastline = None
658 for start, end, line in code.co_lines():
659 if line is not None and line != lastline:
660 lastline = line
661 yield start, line
662 return
663
664 def _find_imports(co):
665 """Find import statements in the code
666
667 Generate triplets (name, level, fromlist) where
668 name is the imported module and level, fromlist are
669 the corresponding args to __import__.
670 """
671 IMPORT_NAME = opmap['IMPORT_NAME']
672 LOAD_CONST = opmap['LOAD_CONST']
673
674 consts = co.co_consts
675 names = co.co_names
676 opargs = [(op, arg) for _, op, arg in _unpack_opargs(co.co_code)
677 if op != EXTENDED_ARG]
678 for i, (op, oparg) in enumerate(opargs):
679 if op == IMPORT_NAME and i >= 2:
680 from_op = opargs[i-1]
681 level_op = opargs[i-2]
682 if (from_op[0] in hasconst and level_op[0] in hasconst):
683 level = _get_const_value(level_op[0], level_op[1], consts)
684 fromlist = _get_const_value(from_op[0], from_op[1], consts)
685 yield (names[oparg], level, fromlist)
686
687 def _find_store_names(co):
688 """Find names of variables which are written in the code
689
690 Generate sequence of strings
691 """
692 STORE_OPS = {
693 opmap['STORE_NAME'],
694 opmap['STORE_GLOBAL']
695 }
696
697 names = co.co_names
698 for _, op, arg in _unpack_opargs(co.co_code):
699 if op in STORE_OPS:
700 yield names[arg]
701
702
703 class Bytecode:
704 """The bytecode operations of a piece of code
705
706 Instantiate this with a function, method, other compiled object, string of
707 code, or a code object (as returned by compile()).
708
709 Iterating over this yields the bytecode operations as Instruction instances.
710 """
711 def __init__(self, x, *, first_line=None, current_offset=None, show_caches=False, adaptive=False):
712 self.codeobj = co = _get_code_object(x)
713 if first_line is None:
714 self.first_line = co.co_firstlineno
715 self._line_offset = 0
716 else:
717 self.first_line = first_line
718 self._line_offset = first_line - co.co_firstlineno
719 self._linestarts = dict(findlinestarts(co))
720 self._original_object = x
721 self.current_offset = current_offset
722 self.exception_entries = _parse_exception_table(co)
723 self.show_caches = show_caches
724 self.adaptive = adaptive
725
726 def __iter__(self):
727 co = self.codeobj
728 try:
729 varname_from_oparg = co._varname_from_oparg
730 except AttributeError:
731 varname_from_oparg = None
732 return _get_instructions_bytes(_get_code_array(co, self.adaptive),
733 varname_from_oparg,
734 co.co_names, co.co_consts,
735 self._linestarts,
736 line_offset=self._line_offset,
737 exception_entries=self.exception_entries,
738 co_positions=co.co_positions(),
739 show_caches=self.show_caches)
740
741 def __repr__(self):
742 return "{}({!r})".format(self.__class__.__name__,
743 self._original_object)
744
745 @classmethod
746 def from_traceback(cls, tb, *, show_caches=False, adaptive=False):
747 """ Construct a Bytecode from the given traceback """
748 while tb.tb_next:
749 tb = tb.tb_next
750 return cls(
751 tb.tb_frame.f_code, current_offset=tb.tb_lasti, show_caches=show_caches, adaptive=adaptive
752 )
753
754 def info(self):
755 """Return formatted information about the code object."""
756 return _format_code_info(self.codeobj)
757
758 def dis(self):
759 """Return a formatted view of the bytecode operations."""
760 co = self.codeobj
761 if self.current_offset is not None:
762 offset = self.current_offset
763 else:
764 offset = -1
765 with io.StringIO() as output:
766 try:
767 varname_from_oparg = co._varname_from_oparg
768 except AttributeError:
769 varname_from_oparg = None
770 _disassemble_bytes(_get_code_array(co, self.adaptive),
771 varname_from_oparg=varname_from_oparg,
772 names=co.co_names, co_consts=co.co_consts,
773 linestarts=self._linestarts,
774 line_offset=self._line_offset,
775 file=output,
776 lasti=offset,
777 exception_entries=self.exception_entries,
778 co_positions=co.co_positions(),
779 show_caches=self.show_caches)
780 return output.getvalue()
781
782
783 def main():
784 import argparse
785
786 parser = argparse.ArgumentParser()
787 parser.add_argument('infile', type=argparse.FileType('rb'), nargs='?', default='-')
788 args = parser.parse_args()
789 with args.infile as infile:
790 source = infile.read()
791 code = compile(source, args.infile.name, "exec")
792 dis(code)
793
794 if __name__ == "__main__":
795 main()