Python 的 sys.settrace 只能在**行級**追蹤,無法觀測字節碼級的堆棧變化、異常拋出、生成器切換等細節。本文實現一個字節碼級追蹤 API,通過向 CPython 添加自定義操作碼 DEBUG_OP 實現。
編輯 Include/opcode.h:
/* Instruction opcodes for compiled code */
/** 自定義操作碼:使用空閒值 0 **/
#define DEBUG_OP 0
#define POP_TOP 1
#define ROT_TWO 2
#define ROT_THREE 3
...
重新編譯 Python:./configure && make -j$(nproc)
編輯 Python/ceval.c 主解釋器循環:
TARGET(DEBUG_OP) {
// 1. 從幀全局區查找回調函數 'op_target'
PyObject *target = NULL;
_Py_IDENTIFIER(op_target);
target = _PyDict_GetItemId(f->f_globals, &PyId_op_target);
if (target == NULL && _PyErr_OCCURRED()) {
if (!PyErr_ExceptionMatches(PyExc_KeyError)) goto error;
PyErr_Clear();
DISPATCH(); // 無回調,直接執行下一條指令
}
// 2. 收集當前值棧內容
PyObject *stack_snapshot = PyList_New(0);
for (int i = 1; i <= STACK_LEVEL(); i++) {
PyObject *item = PEEK(i);
if (item == NULL) item = Py_None;
PyList_Append(stack_snapshot, item);
}
// 3. 調用回調: op_target(stack_list, frame)
PyObject *args = PyTuple_Pack(2, stack_snapshot, (PyObject*)f);
PyObject *result = PyObject_Call(target, args, NULL);
Py_DECREF(args);
Py_DECREF(stack_snapshot);
if (result == NULL) goto error; // 回調拋出異常
Py_DECREF(result);
DISPATCH(); // 繼續執行下一條字節碼
}
// Include/object.h
typedef struct _Py_Identifier {
struct _Py_Identifier *next;
const char* string;
PyObject *object; // 內部化後的 Unicode 對象
} _Py_Identifier;
#define _Py_IDENTIFIER(varname) _Py_static_string(PyId_##varname, #varname)
// 展開為靜態變量,首次使用時內部化字符串
優勢:避免重複創建字符串對象,字典查找用對象身份比較 (O(1))。
// Python/ceval.c
#define STACK_LEVEL() (stack_pointer - f->f_valuestack)
#define PEEK(n) (stack_pointer[-n]) // 栈頂為 1
#define TOP() PEEK(1)
#define POP() (*--stack_pointer)
#define PUSH(v) (*stack_pointer++ = (v))
goto error; // 跳轉到錯誤處理標籤,設置異常狀態並返回
DISPATCH(); // 獲取下一條指令並跳轉執行
Python 層面注入器:
import dis
import opcode
from bytecode import Bytecode, Instr, Label # pip install bytecode
def inject_debug_op(code_obj, interval=1):
"""每 interval 條指令插入一個 DEBUG_OP"""
bc = Bytecode.from_code(code_obj)
new_bc = Bytecode()
new_bc.argcount = bc.argcount
new_bc.kwonlyargcount = bc.kwonlyargcount
new_bc.flags = bc.flags
for i, instr in enumerate(bc):
new_bc.append(instr)
if i % interval == 0:
# 插入 DEBUG_OP (opcode 0)
new_bc.append(Instr("DEBUG_OP"))
return new_bc.to_code()
# 使用示例
def target_function():
x = 1
y = 2
z = x + y
return z
# 注入
import types
original_code = target_function.__code__
new_code = inject_debug_op(original_code)
target_function.__code__ = new_code
# 定義回調
def op_target(stack, frame):
print(f"[DEBUG_OP] Stack depth: {len(stack)}")
print(f" Stack: {[repr(x) for x in stack]}")
print(f" Frame: {frame.f_code.co_name} @ {frame.f_lineno}")
# 注入到全局命名空間
import builtins
builtins.op_target = op_target
# 執行
target_function()
[DEBUG_OP] Stack depth: 0
Stack: []
Frame: target_function @ 2
[DEBUG_OP] Stack depth: 1
Stack: [1]
Frame: target_function @ 3
[DEBUG_OP] Stack depth: 2
Stack: [1, 2]
Frame: target_function @ 4
[DEBUG_OP] Stack depth: 1
Stack: [3]
Frame: target_function @ 5
RAISE_VARARGS 前後棧狀態YIELD_VALUE/YIELD_FROM 棧變化| 方案 | 粒度 | 性能 | 部署難度 | 功能 |
|---|---|---|---|---|
| sys.settrace | 行級 | 中等 | 零依賴 | 覆蓋率、調試器 |
| DEBUG_OP (本文) | 指令級 | 極低 | 高 (需編譯) | 完整棧快照、異常瞬間 |
| sys.setprofile | 函數級 | 較好 | 零依賴 | 性能分析 |
| PySpy / Austin | 採樣 | 極低開銷 | 外部工具 | 生產環境分析 |
| eBPF (bpftrace) | 系統級 | 極低 | 需內核支援 | 全系統可觀測 |
字節碼級追蹤是理解 Python 執行模型的終極視角,雖生產環境受限,但在語言研究、編譯器開發、教學演示中極具價值。