python - 调试 CPython 操作码堆栈

标签 python ctypes bytecode cpython pdb

CPython 3.7 引入了在调试器中单步执行单个操作码的能力。但是,我不知道如何从字节码堆栈中读取变量。

比如调试的时候

def f(a, b, c):
    return a * b + c

f(2, 3, 4)

我想知道加法的输入是 6 和 4。注意 6 是如何从不接触 locals() .

到目前为止,我只能想出操作码信息,但我不知道如何获取操作码输入:

import dis
import sys


def tracefunc(frame, event, arg):
    frame.f_trace_opcodes = True
    print(event, frame.f_lineno, frame.f_lasti, frame, arg)
    if event == "call":
        dis.dis(frame.f_code)
    elif event == "opcode":
        instr = next(
            i for i in iter(dis.Bytecode(frame.f_code))
            if i.offset == frame.f_lasti
        )
        print(instr)
    print("-----------")
    return tracefunc


def f(a, b, c):
    return a * b + c


sys.settrace(tracefunc)
f(2, 3, 4)

输出:
call 19 -1 <frame at 0x7f97df618648, file 'test_trace.py', line 19, code f> None
 20           0 LOAD_FAST                0 (a)
              2 LOAD_FAST                1 (b)
              4 BINARY_MULTIPLY
              6 LOAD_FAST                2 (c)
              8 BINARY_ADD
             10 RETURN_VALUE
-----------
line 20 0 <frame at 0x7f97df618648, file 'test_trace.py', line 20, code f> None
-----------
opcode 20 0 <frame at 0x7f97df618648, file 'test_trace.py', line 20, code f> None
Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='a', argrepr='a', offset=0, starts_line=20, is_jump_target=False)
-----------
opcode 20 2 <frame at 0x7f97df618648, file 'test_trace.py', line 20, code f> None
Instruction(opname='LOAD_FAST', opcode=124, arg=1, argval='b', argrepr='b', offset=2, starts_line=None, is_jump_target=False)
-----------
opcode 20 4 <frame at 0x7f97df618648, file 'test_trace.py', line 20, code f> None
Instruction(opname='BINARY_MULTIPLY', opcode=20, arg=None, argval=None, argrepr='', offset=4, starts_line=None, is_jump_target=False)
-----------
opcode 20 6 <frame at 0x7f97df618648, file 'test_trace.py', line 20, code f> None
Instruction(opname='LOAD_FAST', opcode=124, arg=2, argval='c', argrepr='c', offset=6, starts_line=None, is_jump_target=False)
-----------
opcode 20 8 <frame at 0x7f97df618648, file 'test_trace.py', line 20, code f> None
Instruction(opname='BINARY_ADD', opcode=23, arg=None, argval=None, argrepr='', offset=8, starts_line=None, is_jump_target=False)
-----------
opcode 20 10 <frame at 0x7f97df618648, file 'test_trace.py', line 20, code f> None
Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=10, starts_line=None, is_jump_target=False)
-----------
return 20 10 <frame at 0x7f97df618648, file 'test_trace.py', line 20, code f> 10
-----------

最佳答案

TLDR

您可以使用 C 扩展、gdb 或使用脏技巧(下面的示例)检查 CPython 的操作码间状态。

背景

CPython 的字节码由 stack machine 运行。 .这意味着操作码之间的所有状态都保存在 PyObject* 的堆栈中。 s。

让我们快速浏览一下 CPython 的 frame object :

typedef struct _frame {
    PyObject_VAR_HEAD
    struct _frame *f_back;      /* previous frame, or NULL */
    PyCodeObject *f_code;       /* code segment */
    ... // More fields
    PyObject **f_stacktop;
    ... // More fields
} PyFrameObject;

PyObject **f_stacktop快结束了吗?这是指向此堆栈顶部的指针。大多数(如果不是全部?)CPython 的操作码使用该堆栈来获取参数和存储结果。

例如,让我们看一下 implementation对于 BINARY_ADD (添加两个操作数):

case TARGET(BINARY_ADD): {
    PyObject *right = POP();
    PyObject *left = TOP();
    ... // sum = right + left
    SET_TOP(sum);
    ...
}

它从堆栈中弹出两个值,将它们相加并将结果放回堆栈中。

检查堆栈

低至 C 级别 - C 扩展或 GDB

正如我们在上面看到的,CPython 的框架对象是原生的 - PyFrameObject是一个结构,frameobject.c定义允许读取(有时写入)它的一些成员的pythonic接口(interface)。

具体来说,成员 f_stacktop未在 python 中公开,因此要访问此成员并读取堆栈,您必须用 C 编写一些代码或使用 GDB。

具体来说,如果你正在编写一个调试工具库,我建议你编写一个 C 扩展,这将允许你在 C 中编写一些基本的原语(比如将当前堆栈作为 python 对象的列表),其余的python中的逻辑。

如果是一次性的,你可以试试 playing around with GDB并检查堆栈。

当你没有编译器时 - 使用纯 python

计划:找到堆栈的地址并从内存中读取存储在其中的数字 - 在 python 中!

首先,我们需要能够找到 f_stacktop 的偏移量。在框架对象中。
我安装了 python 的调试版本(在我的 ubuntu 上是 apt install python3.7-dbg )。这个包包括一个包含调试符号的 python 二进制文件(关于帮助调试器的程序的一些信息)。
dwarfdump是一个可以读取和显示调试符号的实用程序(DWARF 是一种常见的调试信息格式,主要用于 ELF 二进制文件)。
运行dwarfdump -S any=f_stacktop -Wc /usr/bin/python3.7-dbg为我们提供以下输出:
DW_TAG_member
    DW_AT_name                  f_stacktop
    DW_AT_decl_file             0x00000034 ./build-debug/../Include/frameobject.h
    DW_AT_decl_line             0x0000001c
    DW_AT_decl_column           0x00000010
    DW_AT_type                  <0x00001969>
    DW_AT_data_member_location  88
DW_AT_data_member_location听起来像 f_stacktop 的偏移量!

现在让我们编写一些代码:

#!/usr/bin/python3.7-dbg
from ctypes import sizeof, POINTER, py_object
# opname is a list of opcode names, where the indexes are the opcode numbers
from opcode import opname
import sys 

# The offset we found using dwarfdump
F_STACKTOP = 88

def get_stack(frame):
    # Getting the address of the stack by adding
    # the address of the frame and the offset of the member
    f_stacktop_addr = id(frame) + F_STACKTOP
    # Initializing a PyObject** directly from memory using ctypes
    return POINTER(py_object).from_address(f_stacktop_addr)

def tracefunc(frame, event, arg):
    frame.f_trace_opcodes = True
    if event == 'opcode':
        # frame.f_code.co_code is the raw bytecode
        opcode = frame.f_code.co_code[frame.f_lasti]
        if opname[opcode] == 'BINARY_ADD':
            stack = get_stack(frame)
            # According to the implementation of BINARY_ADD,
            # the last two items in the stack should be the addition operands
            print(f'{stack[-2]} + {stack[-1]}')
    return tracefunc

def f(a, b, c): 
    return a * b + c 

sys.settrace(tracefunc)
f(2, 3, 4)

输出 : 6 + 4 !巨大的成功! (用波拉特满意的声音说)

这段代码还不能移植,因为 F_STACKTOP在 python 二进制文件之间会有所不同。要解决这个问题,您可以使用 ctypes.Structure 创建框架对象结构并轻松获取 f_stacktop 的值成员以更便携的方式。

请注意,这样做有望使您的代码与平台无关,但不会使其与 python 实现无关。这样的代码可能仅适用于您最初编写的 CPython 版本。这是因为要创建一个 ctypes.Structure子类,您将不得不依赖 CPython 的框架对象实现(或者更具体地说,依赖于 PyFrameObject 的成员类型和顺序)。

关于python - 调试 CPython 操作码堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57142762/

相关文章:

python - 将整数(最多 2^48)安全加密为最短的 URL 安全字符串

python - Matplotlib 在方法和日期时间之间填充

python - django.db.utils.ProgrammingError : relation "blogango_blog" does not exist

python - 是否可以始终依赖 ctypes.data_as 来保留对临时对象的引用?

python - 如何在 python 中将 ctypes.c_uint32 转换为 int?

python - 如何将数组和结构传递给需要 3 个 u32 指针作为参数的 c 函数(ctypes)

python - PySpark : Optimize read/load from Delta using selected columns or partitions

Scala:使用反射来发现你的内在对象(和欲望)?

java - 如何使用method.inserAt();正确地

java - 找出使用了给定 API 的哪些类