Python_Reversing.md

April 23, 2018 · View on GitHub

<- .languages[Python Reversing] ->


PVM (Python Virtual Machine)


  • PVM is a stack-based virtual machine that stores operands in an upwardly-growing stack
  • In stack-based execution, an operation is performed by popping operands from the stack, operates on them, and then storing the result back to the stack
  • Advantages of Stack-Based Virtual Machine
    • Instructions are shorter than instructions in register-based virtual machine since operands don’t need to be explicitly stated because they are on the stack, thus resulting in shorter overall bytecode
    • Easier to implement since it doesn’t have to worry about register allocation

The 3 Tuples Associated With Function Object


  • Local variables and parameters are stored in <object name>.__code__.co_varnames
  • Global variables that it uses are stored in <object name>.__code__.co_names
  • Constants it uses are stored in <object name>.__code__.co_consts

Python Bytecode Instructions


  • For full instruction set, check out the Official Python Documentation
  • An instruction consists of an opcode and possibly an oparg. Opcode is the instruction and oparg is the index that resolves to the actual operands
    • Some instructions, such as BINARY_ADD, doesn't require an oparg since the operands it needs are on the stack
    • Other instructions, such as those for LOAD/STORE, require an oparg to index a tuple for the operand. The specific tuple is referenced in the latter half of the opcode
      • LOAD/STORE_CONST: uses oparg to index the <object name>.__code__.co_consts tuple
      • LOAD/STORE_FAST: uses oparg to index the <object name>.__code__.co_varnames tuple
      • LOAD/STORE_GLOBAL: uses oparg to index the <object name>.__code__.co_names tuple
      • Load will push the value it indexed onto the stack and store will store the value at the top of the stack into the indexed object

C++ Reversing <- RERM[.languages] -> ELF Files