Movatterモバイル変換


[0]ホーム

URL:


Navigation

31.12.dis — Disassembler for Python bytecode

Source code:Lib/dis.py


Thedis module supports the analysis of CPythonbytecode bydisassembling it. The CPython bytecode which this module takes as aninput is defined in the fileInclude/opcode.h and used by the compilerand the interpreter.

CPython implementation detail: Bytecode is an implementation detail of the CPython interpreter. Noguarantees are made that bytecode will not be added, removed, or changedbetween versions of Python. Use of this module should not be considered towork across Python VMs or Python releases.

Example: Given the functionmyfunc():

defmyfunc(alist):returnlen(alist)

the following command can be used to get the disassembly ofmyfunc():

>>>dis.dis(myfunc)  2           0 LOAD_GLOBAL              0 (len)              3 LOAD_FAST                0 (alist)              6 CALL_FUNCTION            1              9 RETURN_VALUE

(The “2” is a line number).

Thedis module defines the following functions and constants:

dis.code_info(x)

Return a formatted multi-line string with detailed code object informationfor the supplied function, method, source code string or code object.

Note that the exact contents of code info strings are highly implementationdependent and they may change arbitrarily across Python VMs or Pythonreleases.

New in version 3.2.

dis.show_code(x)

Print detailed code object information for the supplied function, method,source code string or code object to stdout.

This is a convenient shorthand forprint(code_info(x)), intended forinteractive exploration at the interpreter prompt.

New in version 3.2.

dis.dis(x=None)

Disassemble thex object.x can denote either a module, a class, amethod, a function, a code object, a string of source code or a byte sequenceof raw bytecode. For a module, it disassembles all functions. For a class,it disassembles all methods. For a code object or sequence of raw bytecode,it prints one line per bytecode instruction. Strings are first compiled tocode objects with thecompile() built-in function before beingdisassembled. If no object is provided, this function disassembles the lasttraceback.

dis.distb(tb=None)

Disassemble the top-of-stack function of a traceback, using the lasttraceback if none was passed. The instruction causing the exception isindicated.

dis.disassemble(code,lasti=-1)
dis.disco(code,lasti=-1)

Disassemble a code object, indicating the last instruction iflasti wasprovided. The output is divided in the following columns:

  1. the line number, for the first instruction of each line
  2. the current instruction, indicated as-->,
  3. a labelled instruction, indicated with>>,
  4. the address of the instruction,
  5. the operation code name,
  6. operation parameters, and
  7. interpretation of the parameters in parentheses.

The parameter interpretation recognizes local and global variable names,constant values, branch targets, and compare operators.

dis.findlinestarts(code)

This generator function uses theco_firstlineno andco_lnotabattributes of the code objectcode to find the offsets which are starts oflines in the source code. They are generated as(offset,lineno) pairs.

dis.findlabels(code)

Detect all offsets in the code objectcode which are jump targets, andreturn a list of these offsets.

dis.opname

Sequence of operation names, indexable using the bytecode.

dis.opmap

Dictionary mapping operation names to bytecodes.

dis.cmp_op

Sequence of all compare operation names.

dis.hasconst

Sequence of bytecodes that have a constant parameter.

dis.hasfree

Sequence of bytecodes that access a free variable.

dis.hasname

Sequence of bytecodes that access an attribute by name.

dis.hasjrel

Sequence of bytecodes that have a relative jump target.

dis.hasjabs

Sequence of bytecodes that have an absolute jump target.

dis.haslocal

Sequence of bytecodes that access a local variable.

dis.hascompare

Sequence of bytecodes of Boolean operations.

31.12.1. Python Bytecode Instructions

The Python compiler currently generates the following bytecode instructions.

General instructions

NOP

Do nothing code. Used as a placeholder by the bytecode optimizer.

POP_TOP

Removes the top-of-stack (TOS) item.

ROT_TWO

Swaps the two top-most stack items.

ROT_THREE

Lifts second and third stack item one position up, moves top down to positionthree.

DUP_TOP

Duplicates the reference on top of the stack.

DUP_TOP_TWO

Duplicates the two references on top of the stack, leaving them in thesame order.

Unary operations

Unary operations take the top of the stack, apply the operation, and push theresult back on the stack.

UNARY_POSITIVE

ImplementsTOS=+TOS.

UNARY_NEGATIVE

ImplementsTOS=-TOS.

UNARY_NOT

ImplementsTOS=notTOS.

UNARY_INVERT

ImplementsTOS=~TOS.

GET_ITER

ImplementsTOS=iter(TOS).

Binary operations

Binary operations remove the top of the stack (TOS) and the second top-moststack item (TOS1) from the stack. They perform the operation, and put theresult back on the stack.

BINARY_POWER

ImplementsTOS=TOS1**TOS.

BINARY_MULTIPLY

ImplementsTOS=TOS1*TOS.

BINARY_FLOOR_DIVIDE

ImplementsTOS=TOS1//TOS.

BINARY_TRUE_DIVIDE

ImplementsTOS=TOS1/TOS.

BINARY_MODULO

ImplementsTOS=TOS1%TOS.

BINARY_ADD

ImplementsTOS=TOS1+TOS.

BINARY_SUBTRACT

ImplementsTOS=TOS1-TOS.

BINARY_SUBSCR

ImplementsTOS=TOS1[TOS].

BINARY_LSHIFT

ImplementsTOS=TOS1<<TOS.

BINARY_RSHIFT

ImplementsTOS=TOS1>>TOS.

BINARY_AND

ImplementsTOS=TOS1&TOS.

BINARY_XOR

ImplementsTOS=TOS1^TOS.

BINARY_OR

ImplementsTOS=TOS1|TOS.

In-place operations

In-place operations are like binary operations, in that they remove TOS andTOS1, and push the result back on the stack, but the operation is done in-placewhen TOS1 supports it, and the resulting TOS may be (but does not have to be)the original TOS1.

INPLACE_POWER

Implements in-placeTOS=TOS1**TOS.

INPLACE_MULTIPLY

Implements in-placeTOS=TOS1*TOS.

INPLACE_FLOOR_DIVIDE

Implements in-placeTOS=TOS1//TOS.

INPLACE_TRUE_DIVIDE

Implements in-placeTOS=TOS1/TOS.

INPLACE_MODULO

Implements in-placeTOS=TOS1%TOS.

INPLACE_ADD

Implements in-placeTOS=TOS1+TOS.

INPLACE_SUBTRACT

Implements in-placeTOS=TOS1-TOS.

INPLACE_LSHIFT

Implements in-placeTOS=TOS1<<TOS.

INPLACE_RSHIFT

Implements in-placeTOS=TOS1>>TOS.

INPLACE_AND

Implements in-placeTOS=TOS1&TOS.

INPLACE_XOR

Implements in-placeTOS=TOS1^TOS.

INPLACE_OR

Implements in-placeTOS=TOS1|TOS.

STORE_SUBSCR

ImplementsTOS1[TOS]=TOS2.

DELETE_SUBSCR

ImplementsdelTOS1[TOS].

Miscellaneous opcodes

PRINT_EXPR

Implements the expression statement for the interactive mode. TOS is removedfrom the stack and printed. In non-interactive mode, an expression statement isterminated withPOP_STACK.

BREAK_LOOP

Terminates a loop due to abreak statement.

CONTINUE_LOOP(target)

Continues a loop due to acontinue statement.target is theaddress to jump to (which should be aFOR_ITER instruction).

SET_ADD(i)

Callsset.add(TOS1[-i],TOS). Used to implement set comprehensions.

LIST_APPEND(i)

Callslist.append(TOS[-i],TOS). Used to implement list comprehensions.

MAP_ADD(i)

Callsdict.setitem(TOS1[-i],TOS,TOS1). Used to implement dictcomprehensions.

For all of the SET_ADD, LIST_APPEND and MAP_ADD instructions, while theadded value or key/value pair is popped off, the container object remains onthe stack so that it is available for further iterations of the loop.

RETURN_VALUE

Returns with TOS to the caller of the function.

YIELD_VALUE

PopsTOS and yields it from agenerator.

YIELD_FROM

PopsTOS and delegates to it as a subiterator from agenerator.

New in version 3.3.

IMPORT_STAR

Loads all symbols not starting with'_' directly from the module TOS to thelocal namespace. The module is popped after loading all names. This opcodeimplementsfrommoduleimport*.

POP_BLOCK

Removes one block from the block stack. Per frame, there is a stack of blocks,denoting nested loops, try statements, and such.

POP_EXCEPT

Removes one block from the block stack. The popped block must be an exceptionhandler block, as implicitly created when entering an except handler.In addition to popping extraneous values from the frame stack, thelast three popped values are used to restore the exception state.

END_FINALLY

Terminates afinally clause. The interpreter recalls whether theexception has to be re-raised, or whether the function returns, and continueswith the outer-next block.

LOAD_BUILD_CLASS

Pushesbuiltins.__build_class__() onto the stack. It is later calledbyCALL_FUNCTION to construct a class.

SETUP_WITH(delta)

This opcode performs several operations before a with block starts. First,it loads__exit__() from the context manager and pushes it ontothe stack for later use byWITH_CLEANUP. Then,__enter__() is called, and a finally block pointing todeltais pushed. Finally, the result of calling the enter method is pushed ontothe stack. The next opcode will either ignore it (POP_TOP), orstore it in (a) variable(s) (STORE_FAST,STORE_NAME, orUNPACK_SEQUENCE).

WITH_CLEANUP

Cleans up the stack when awith statement block exits. TOS isthe context manager’s__exit__() bound method. Below TOS are 1–3values indicating how/why the finally clause was entered:

  • SECOND =None
  • (SECOND, THIRD) = (WHY_{RETURN,CONTINUE}), retval
  • SECOND =WHY_*; no retval below it
  • (SECOND, THIRD, FOURTH) = exc_info()

In the last case,TOS(SECOND,THIRD,FOURTH) is called, otherwiseTOS(None,None,None). In addition, TOS is removed from the stack.

If the stack represents an exception,and the function call returnsa ‘true’ value, this information is “zapped” and replaced with a singleWHY_SILENCED to preventEND_FINALLY from re-raising the exception.(But non-local gotos will still be resumed.)

STORE_LOCALS

Pops TOS from the stack and stores it as the current frame’sf_locals.This is used in class construction.

All of the following opcodes expect arguments. An argument is two bytes, withthe more significant byte last.

STORE_NAME(namei)

Implementsname=TOS.namei is the index ofname in the attributeco_names of the code object. The compiler tries to useSTORE_FASTorSTORE_GLOBAL if possible.

DELETE_NAME(namei)

Implementsdelname, wherenamei is the index intoco_namesattribute of the code object.

UNPACK_SEQUENCE(count)

Unpacks TOS intocount individual values, which are put onto the stackright-to-left.

UNPACK_EX(counts)

Implements assignment with a starred target: Unpacks an iterable in TOS intoindividual values, where the total number of values can be smaller than thenumber of items in the iterable: one the new values will be a list of allleftover items.

The low byte ofcounts is the number of values before the list value, thehigh byte ofcounts the number of values after it. The resulting valuesare put onto the stack right-to-left.

STORE_ATTR(namei)

ImplementsTOS.name=TOS1, wherenamei is the index of name inco_names.

DELETE_ATTR(namei)

ImplementsdelTOS.name, usingnamei as index intoco_names.

STORE_GLOBAL(namei)

Works asSTORE_NAME, but stores the name as a global.

DELETE_GLOBAL(namei)

Works asDELETE_NAME, but deletes a global name.

LOAD_CONST(consti)

Pushesco_consts[consti] onto the stack.

LOAD_NAME(namei)

Pushes the value associated withco_names[namei] onto the stack.

BUILD_TUPLE(count)

Creates a tuple consumingcount items from the stack, and pushes the resultingtuple onto the stack.

BUILD_LIST(count)

Works asBUILD_TUPLE, but creates a list.

BUILD_SET(count)

Works asBUILD_TUPLE, but creates a set.

BUILD_MAP(count)

Pushes a new dictionary object onto the stack. The dictionary is pre-sizedto holdcount entries.

LOAD_ATTR(namei)

Replaces TOS withgetattr(TOS,co_names[namei]).

COMPARE_OP(opname)

Performs a Boolean operation. The operation name can be found incmp_op[opname].

IMPORT_NAME(namei)

Imports the moduleco_names[namei]. TOS and TOS1 are popped and providethefromlist andlevel arguments of__import__(). The moduleobject is pushed onto the stack. The current namespace is not affected:for a proper import statement, a subsequentSTORE_FAST instructionmodifies the namespace.

IMPORT_FROM(namei)

Loads the attributeco_names[namei] from the module found in TOS. Theresulting object is pushed onto the stack, to be subsequently stored by aSTORE_FAST instruction.

JUMP_FORWARD(delta)

Increments bytecode counter bydelta.

POP_JUMP_IF_TRUE(target)

If TOS is true, sets the bytecode counter totarget. TOS is popped.

POP_JUMP_IF_FALSE(target)

If TOS is false, sets the bytecode counter totarget. TOS is popped.

JUMP_IF_TRUE_OR_POP(target)

If TOS is true, sets the bytecode counter totarget and leaves TOSon the stack. Otherwise (TOS is false), TOS is popped.

JUMP_IF_FALSE_OR_POP(target)

If TOS is false, sets the bytecode counter totarget and leavesTOS on the stack. Otherwise (TOS is true), TOS is popped.

JUMP_ABSOLUTE(target)

Set bytecode counter totarget.

FOR_ITER(delta)

TOS is aniterator. Call its__next__() method.If this yields a new value, push it on the stack (leaving the iterator belowit). If the iterator indicates it is exhaustedTOS is popped, and thebyte code counter is incremented bydelta.

LOAD_GLOBAL(namei)

Loads the global namedco_names[namei] onto the stack.

SETUP_LOOP(delta)

Pushes a block for a loop onto the block stack. The block spans from thecurrent instruction with a size ofdelta bytes.

SETUP_EXCEPT(delta)

Pushes a try block from a try-except clause onto the block stack.delta pointsto the first except block.

SETUP_FINALLY(delta)

Pushes a try block from a try-except clause onto the block stack.delta pointsto the finally block.

STORE_MAP

Store a key and value pair in a dictionary. Pops the key and value while leavingthe dictionary on the stack.

LOAD_FAST(var_num)

Pushes a reference to the localco_varnames[var_num] onto the stack.

STORE_FAST(var_num)

Stores TOS into the localco_varnames[var_num].

DELETE_FAST(var_num)

Deletes localco_varnames[var_num].

LOAD_CLOSURE(i)

Pushes a reference to the cell contained in sloti of the cell and freevariable storage. The name of the variable isco_cellvars[i] ifi isless than the length ofco_cellvars. Otherwise it isco_freevars[i-len(co_cellvars)].

LOAD_DEREF(i)

Loads the cell contained in sloti of the cell and free variable storage.Pushes a reference to the object the cell contains on the stack.

STORE_DEREF(i)

Stores TOS into the cell contained in sloti of the cell and free variablestorage.

DELETE_DEREF(i)

Empties the cell contained in sloti of the cell and free variable storage.Used by thedel statement.

RAISE_VARARGS(argc)

Raises an exception.argc indicates the number of parameters to the raisestatement, ranging from 0 to 3. The handler will find the traceback as TOS2,the parameter as TOS1, and the exception as TOS.

CALL_FUNCTION(argc)

Calls a function. The low byte ofargc indicates the number of positionalparameters, the high byte the number of keyword parameters. On the stack, theopcode finds the keyword parameters first. For each keyword argument, the valueis on top of the key. Below the keyword parameters, the positional parametersare on the stack, with the right-most parameter on top. Below the parameters,the function object to call is on the stack. Pops all function arguments, andthe function itself off the stack, and pushes the return value.

MAKE_FUNCTION(argc)

Pushes a new function object on the stack. From bottom to top, the consumedstack must consist of

  • argc&0xFF default argument objects in positional order
  • (argc>>8)&0xFF pairs of name and default argument, with the namejust below the object on the stack, for keyword-only parameters
  • (argc>>16)&0x7FFF parameter annotation objects
  • a tuple listing the parameter names for the annotations (only if there areony annotation objects)
  • the code associated with the function (at TOS1)
  • thequalified name of the function (at TOS)
MAKE_CLOSURE(argc)

Creates a new function object, sets its__closure__ slot, and pushes it onthe stack. TOS is thequalified name of the function, TOS1 is thecode associated with the function, and TOS2 is the tuple containing cells forthe closure’s free variables. The function also hasargc default parameters,which are found below the cells.

BUILD_SLICE(argc)

Pushes a slice object on the stack.argc must be 2 or 3. If it is 2,slice(TOS1,TOS) is pushed; if it is 3,slice(TOS2,TOS1,TOS) ispushed. See theslice() built-in function for more information.

EXTENDED_ARG(ext)

Prefixes any opcode which has an argument too big to fit into the default twobytes.ext holds two additional bytes which, taken together with thesubsequent opcode’s argument, comprise a four-byte argument,ext being the twomost-significant bytes.

CALL_FUNCTION_VAR(argc)

Calls a function.argc is interpreted as inCALL_FUNCTION. The top elementon the stack contains the variable argument list, followed by keyword andpositional arguments.

CALL_FUNCTION_KW(argc)

Calls a function.argc is interpreted as inCALL_FUNCTION. The top elementon the stack contains the keyword arguments dictionary, followed by explicitkeyword and positional arguments.

CALL_FUNCTION_VAR_KW(argc)

Calls a function.argc is interpreted as inCALL_FUNCTION. The topelement on the stack contains the keyword arguments dictionary, followed by thevariable-arguments tuple, followed by explicit keyword and positional arguments.

HAVE_ARGUMENT

This is not really an opcode. It identifies the dividing line between opcodeswhich don’t take arguments<HAVE_ARGUMENT and those which do>=HAVE_ARGUMENT.

Table Of Contents

Previous topic

31.11.compileall — Byte-compile Python libraries

Next topic

31.13.pickletools — Tools for pickle developers

This Page

Quick search

Enter search terms or a module, class or function name.

Navigation

©Copyright 1990-2017, Python Software Foundation.
The Python Software Foundation is a non-profit corporation.Please donate.
Last updated on Sep 19, 2017.Found a bug?
Created usingSphinx 1.2.

[8]ページ先頭

©2009-2025 Movatter.jp