调试 CPython 操作码堆栈

Debug the CPython opcode stack

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 的字节码是 运行 by a stack machine。这意味着操作码之间的所有状态都保存在 PyObject* 的堆栈中。

让我们快速浏览一下 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 for 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 接口允许读取(有时写入)一些它的成员。

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

具体来说,如果您正在编写一个调试实用程序库,我建议您编写一个 C 扩展,这将允许您用 C 编写一些基本原语(比如将当前堆栈作为 python 个对象),以及 python.

中的其余逻辑

如果这是一次性的事情,您可以尝试 playing around with GDB 并检查堆栈。

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

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

首先,我们需要能够找到f_stacktop在frame对象中的偏移量。 我安装了 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's members' 类型和顺序)。