从底层理解Python的执行

最近我在学习 Python 的运行模型。我对 Python 的一些内部机制很是好奇,比如 Python 是怎么实现类似 YIELDVALUE、YIELDFROM 这样的操作码的;对于 递推式构造列表(List Comprehensions)、生成器表达式(generator expressions)以及其他一些有趣的 Python 特性是怎么编译的;从字节码的层面来看,当异常抛出的时候都发生了什么事情。翻阅 CPython 的代码对于解答这些问题当然是很有帮助的,但我仍然觉得以这样的方式来做的话对于理解字节码的执行和堆栈的变化还是缺少点什么。GDB 是个好选择,但是我懒,而且只想使用一些比较高阶的接口写点 Python 代码来完成这件事。

所以呢,我的目标就是创建一个字节码级别的追踪 API,类似 sys.setrace 所提供的那样,但相对而言会有更好的粒度。这充分锻炼了我编写 Python 实现的 C 代码的编码能力。我们所需要的有如下几项,在这篇文章中所用的 Python 版本为 3.5。

  • 一个新的 Cpython 解释器操作码
  • 一种将操作码注入到 Python 字节码的方法
  • 一些用于处理操作码的 Python 代码

一个新的 Cpython 操作码

新操作码:DEBUG_OP

这个新的操作码 DEBUG_OP 是我第一次尝试写 CPython 实现的 C 代码,我将尽可能的让它保持简单。 我们想要达成的目的是,当我们的操作码被执行的时候我能有一种方式来调用一些 Python 代码。同时,我们也想能够追踪一些与执行上下文有关的数据。我们的操作码会把这些信息当作参数传递给我们的回调函数。通过操作码能辨识出的有用信息如下:

  • 堆栈的内容
  • 执行 DEBUG_OP 的帧对象信息

所以呢,我们的操作码需要做的事情是:

  • 找到回调函数
  • 创建一个包含堆栈内容的列表
  • 调用回调函数,并将包含堆栈内容的列表和当前帧作为参数传递给它

听起来挺简单的,现在开始动手吧!声明:下面所有的解释说明和代码是经过了大量段错误调试之后总结得到的结论。首先要做的是给操作码定义一个名字和相应的值,因此我们需要在Include/opcode.h中添加代码。

[py] view plaincopy
 
  1. /** My own comments begin by '**' **/  
  2. /** From: Includes/opcode.h **/  
  3.   
  4. /* Instruction opcodes for compiled code */  
  5.   
  6. /** We just have to define our opcode with a free value  
  7.     0 was the first one I found **/  
  8. #define DEBUG_OP                0  
  9.   
  10. #define POP_TOP                 1  
  11. #define ROT_TWO                 2  
  12. #define ROT_THREE               3  

这部分工作就完成了,现在我们去编写操作码真正干活的代码。 

实现 DEBUG_OP

在考虑如何实现DEBUG_OP之前我们需要了解的是DEBUG_OP提供的接口将长什么样。 拥有一个可以调用其他代码的新操作码是相当酷眩的,但是究竟它将调用哪些代码捏?这个操作码如何找到回调函数的捏?我选择了一种最简单的方法:在帧的全局区域写死函数名。那么问题就变成了,我该怎么从字典中找到一个固定的 C 字符串?为了回答这个问题我们来看看在 Python 的 main loop 中使用到的和上下文管理相关的标识符__enter____exit__。

我们可以看到这两标识符被使用在操作码SETUP_WITH中:

[py] view plaincopy
 
  1. /** From: Python/ceval.c **/  
  2. TARGET(SETUP_WITH) {  
  3. _Py_IDENTIFIER(__exit__);  
  4. _Py_IDENTIFIER(__enter__);  
  5. PyObject *mgr = TOP();  
  6. PyObject *exit = special_lookup(mgr, &PyId___exit__), *enter;  
  7. PyObject *res;  

现在,看一眼宏_Py_IDENTIFIER的定义 

[py] view plaincopy
 
  1. /** From: Include/object.h **/  
  2.   
  3. /********************* String Literals ****************************************/  
  4. /* This structure helps managing static strings. The basic usage goes like this:  
  5.    Instead of doing  
  6.   
  7.        r = PyObject_CallMethod(o, "foo", "args", ...);  
  8.   
  9.    do  
  10.   
  11.        _Py_IDENTIFIER(foo);  
  12.        ...  
  13.        r = _PyObject_CallMethodId(o, &PyId_foo, "args", ...);  
  14.   
  15.    PyId_foo is a static variable, either on block level or file level. On first  
  16.    usage, the string "foo" is interned, and the structures are linked. On interpreter  
  17.    shutdown, all strings are released (through _PyUnicode_ClearStaticStrings).  
  18.   
  19.    Alternatively, _Py_static_string allows to choose the variable name.  
  20.    _PyUnicode_FromId returns a borrowed reference to the interned string.  
  21.    _PyObject_{Get,Set,Has}AttrId are __getattr__ versions using _Py_Identifier*.  
  22. */  
  23. typedef struct _Py_Identifier {  
  24.     struct _Py_Identifier *next;  
  25.     const char* string;  
  26.     PyObject *object;  
  27. } _Py_Identifier;  
  28.   
  29. #define _Py_static_string_init(value) { 0, value, 0 }  
  30. #define _Py_static_string(varname, value)  static _Py_Identifier varname = _Py_static_string_init(value)  
  31. #define _Py_IDENTIFIER(varname) _Py_static_string(PyId_##varname, #varname)  

嗯,注释部分已经说明得很清楚了。通过一番查找,我们发现了可以用来从字典找固定字符串的函数_PyDict_GetItemId,所以我们操作码的查找部分的代码就是长这样滴。

[py] view plaincopy
 
  1.  /** Our callback function will be named op_target **/  
  2. PyObject *target = NULL;  
  3. _Py_IDENTIFIER(op_target);  
  4. target = _PyDict_GetItemId(f->f_globals, &PyId_op_target);  
  5. if (target == NULL && _PyErr_OCCURRED()) {  
  6.     if (!PyErr_ExceptionMatches(PyExc_KeyError))  
  7.         goto error;  
  8.     PyErr_Clear();  
  9.     DISPATCH();  
  10. }  

为了方便理解,对这一段代码做一些说明:

  • f是当前的帧,f->f_globals是它的全局区域
  • 如果我们没有找到op_target,我们将会检查这个异常是不是KeyError
  • goto error;是一种在 main loop 中抛出异常的方法
  • PyErr_Clear()抑制了当前异常的抛出,而DISPATCH()触发了下一个操作码的执行

下一步就是收集我们想要的堆栈信息。 

[py] view plaincopy
 
  1. /** This code create a list with all the values on the current stack **/  
  2. PyObject *value = PyList_New(0);  
  3. for (i = 1 ; i <= STACK_LEVEL(); i++) {  
  4.     tmp = PEEK(i);  
  5.     if (tmp == NULL) {  
  6.         tmp = Py_None;  
  7.     }  
  8.     PyList_Append(value, tmp);  
  9. }  

最后一步就是调用我们的回调函数!我们用call_function来搞定这件事,我们通过研究操作码CALL_FUNCTION的实现来学习怎么使用call_function 。

[py] view plaincopy
 
  1. /** From: Python/ceval.c **/  
  2. TARGET(CALL_FUNCTION) {  
  3.     PyObject **sp, *res;  
  4.     /** stack_pointer is a local of the main loop.  
  5.         It's the pointer to the stacktop of our frame **/  
  6.     sp = stack_pointer;  
  7.     res = call_function(&sp, oparg);  
  8.     /** call_function handles the args it consummed on the stack for us **/  
  9.     stack_pointer = sp;  
  10.     PUSH(res);  
  11.     /** Standard exception handling **/  
  12.     if (res == NULL)  
  13.         goto error;  
  14.     DISPATCH();  
  15. }  

有了上面这些信息,我们终于可以捣鼓出一个操作码DEBUG_OP的草稿了:

[py] view plaincopy
 
  1. TARGET(DEBUG_OP) {  
  2.     PyObject *value = NULL;  
  3.     PyObject *target = NULL;  
  4.     PyObject *res = NULL;  
  5.     PyObject **sp = NULL;  
  6.     PyObject *tmp;  
  7.     int i;  
  8.     _Py_IDENTIFIER(op_target);  
  9.   
  10.     target = _PyDict_GetItemId(f->f_globals, &PyId_op_target);  
  11.     if (target == NULL && _PyErr_OCCURRED()) {  
  12.         if (!PyErr_ExceptionMatches(PyExc_KeyError))  
  13.             goto error;  
  14.         PyErr_Clear();  
  15.         DISPATCH();  
  16.     }  
  17.     value = PyList_New(0);  
  18.     Py_INCREF(target);  
  19.     for (i = 1 ; i <= STACK_LEVEL(); i++) {  
  20.         tmp = PEEK(i);  
  21.         if (tmp == NULL)  
  22.             tmp = Py_None;  
  23.         PyList_Append(value, tmp);  
  24.     }  
  25.   
  26.     PUSH(target);  
  27.     PUSH(value);  
  28.     Py_INCREF(f);  
  29.     PUSH(f);  
  30.     sp = stack_pointer;  
  31.     res = call_function(&sp, 2);  
  32.     stack_pointer = sp;  
  33.     if (res == NULL)  
  34.         goto error;  
  35.     Py_DECREF(res);  
  36.     DISPATCH();  
  37. }  

在编写 CPython 实现的 C 代码方面我确实没有什么经验,有可能我漏掉了些细节。如果您有什么建议还请您纠正,我期待您的反馈。

编译它,成了!

一切看起来很顺利,但是当我们尝试去使用我们定义的操作码DEBUG_OP的时候却失败了。自从 2008 年之后,Python 使用预先写好的 goto(你也可以从 这里获取更多的讯息)。故,我们需要更新下 goto jump table,我们在 Python/opcode_targets.h 中做如下修改。

[py] view plaincopy
 
  1. /** From: Python/opcode_targets.h **/  
  2. /** Easy change since DEBUG_OP is the opcode number 1 **/  
  3. static void *opcode_targets[256] = {  
  4.     //&&_unknown_opcode,  
  5.     &&TARGET_DEBUG_OP,  
  6.     &&TARGET_POP_TOP,  
  7.     /** ... **/  

这就完事了,我们现在就有了一个可以工作的新操作码。唯一的问题就是这货虽然存在,但是没有被人调用过。接下来,我们将DEBUG_OP注入到函数的字节码中。 

在 Python 字节码中注入操作码 DEBUG_OP

有很多方式可以在 Python 字节码中注入新的操作码:

  • 使用 peephole optimizer, Quarkslab就是这么干的
  • 在生成字节码的代码中动些手脚
  • 在运行时直接修改函数的字节码(这就是我们将要干的事儿)

为了创造出一个新操作码,有了上面的那一堆 C 代码就够了。现在让我们回到原点,开始理解奇怪甚至神奇的 Python!

我们将要做的事儿有:

  • 得到我们想要追踪函数的 code object
  • 重写字节码来注入DEBUG_OP
  • 将新生成的 code object 替换回去

和 code object 有关的小贴士

如果你从没听说过 code object,这里有一个简单的 介绍网路上也有一些相关的 文档可供查阅,可以直接Ctrl+F查找 code object

还有一件事情需要注意的是在这篇文章所指的环境中 code object 是不可变的:

[py] view plaincopy
 
  1. Python 3.4.2 (default, Oct  2014, 10:45:20)  
  2. [GCC 4.9.1] on linux  
  3. Type "help", "copyright", "credits" or "license" for more information.  
  4. >>> x = lambda y : 2  
  5. >>> x.__code__  
  6. <code object <lambda> at 0x7f481fd88390, file "<stdin>", line 1>  
  7. >>> x.__code__.co_name  
  8. '<lambda>'  
  9. >>> x.__code__.co_name = 'truc'  
  10. Traceback (most recent call last):  
  11.   File "<stdin>", line 1, in <module>  
  12. AttributeError: readonly attribute  
  13. >>> x.__code__.co_consts = ('truc',)  
  14. Traceback (most recent call last):  
  15.   File "<stdin>", line 1, in <module>  
  16. AttributeError: readonly attribute  

但是不用担心,我们将会找到方法绕过这个问题的。 

使用的工具

为了修改字节码我们需要一些工具:

  • dis模块用来反编译和分析字节码
  • dis.BytecodePython 3.4 新增的一个特性,对于反编译和分析字节码特别有用
  • 一个能够简单修改 code object 的方法

dis.Bytecode反编译 code bject 能告诉我们一些有关操作码、参数和上下文的信息。

[py] view plaincopy
 
  1. # Python3.4  
  2. >>> import dis  
  3. >>> f = lambda x: x + 3  
  4. >>> for i in dis.Bytecode(f.__code__): print (i)  
  5. ...  
  6. Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='x', argrepr='x', offset=0, starts_line=1, is_jump_target=False)  
  7. Instruction(opname='LOAD_CONST', opcode=100, arg=1, argval=3, argrepr='3', offset=3, starts_line=None, is_jump_target=False)  
  8. Instruction(opname='BINARY_ADD', opcode=23, arg=None, argval=None, argrepr='', offset=6, starts_line=None, is_jump_target=False)  
  9. Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=7, starts_line=None, is_jump_target=False)  

为了能够修改 code object,我定义了一个很小的类用来复制 code object,同时能够按我们的需求修改相应的值,然后重新生成一个新的 code object。

[py] view plaincopy
 
  1. class MutableCodeObject(object):  
  2.     args_name = ("co_argcount", "co_kwonlyargcount", "co_nlocals", "co_stacksize", "co_flags", "co_code",  
  3.                   "co_consts", "co_names", "co_varnames", "co_filename", "co_name", "co_firstlineno",  
  4.                    "co_lnotab", "co_freevars", "co_cellvars")  
  5.   
  6.     def __init__(self, initial_code):  
  7.         self.initial_code = initial_code  
  8.         for attr_name in self.args_name:  
  9.             attr = getattr(self.initial_code, attr_name)  
  10.             if isinstance(attr, tuple):  
  11.                 attr = list(attr)  
  12.             setattr(self, attr_name, attr)  
  13.   
  14.     def get_code(self):  
  15.         args = []  
  16.         for attr_name in self.args_name:  
  17.             attr = getattr(self, attr_name)  
  18.             if isinstance(attr, list):  
  19.                 attr = tuple(attr)  
  20.             args.append(attr)  
  21.         return self.initial_code.__class__(*args)  

这个类用起来很方便,解决了上面提到的 code object 不可变的问题。

[py] view plaincopy
 
  1. >>> x = lambda y : 2  
  2. >>> m = MutableCodeObject(x.__code__)  
  3. >>> m  
  4. <new_code.MutableCodeObject object at 0x7f3f0ea546a0>  
  5. >>> m.co_consts  
  6. [None, 2]  
  7. >>> m.co_consts[1] = '3'  
  8. >>> m.co_name = 'truc'  
  9. >>> m.get_code()  
  10. <code object truc at 0x7f3f0ea2bc90, file "<stdin>", line 1>  

测试我们的新操作码

我们现在拥有了注入DEBUG_OP的所有工具,让我们来验证下我们的实现是否可用。我们将我们的操作码注入到一个最简单的函数中:

[py] view plaincopy
 
  1. from new_code import MutableCodeObject  
  2.   
  3. def op_target(*args):  
  4.     print("WOOT")  
  5.     print("op_target called with args <{0}>".format(args))  
  6.   
  7. def nop():  
  8.     pass  
  9.   
  10. new_nop_code = MutableCodeObject(nop.__code__)  
  11. new_nop_code.co_code = b"x00" + new_nop_code.co_code[0:3] + b"x00" + new_nop_code.co_code[-1:]  
  12. new_nop_code.co_stacksize += 3  
  13.   
  14. nop.__code__ = new_nop_code.get_code()  
  15.   
  16. import dis  
  17. dis.dis(nop)  
  18. nop()  
  19.   
  20.   
  21. # Don't forget that ./python is our custom Python implementing DEBUG_OP  
  22. hakril@computer ~/python/CPython3.5 % ./python proof.py  
  23.   8           0 <0>  
  24.               1 LOAD_CONST               0 (None)  
  25.               4 <0>  
  26.               5 RETURN_VALUE  
  27. WOOT  
  28. op_target called with args <([], <frame object at 0x7fde9eaebdb0>)>  
  29. WOOT  
  30. op_target called with args <([None], <frame object at 0x7fde9eaebdb0>)>  

看起来它成功了!有一行代码需要说明一下new_nop_code.co_stacksize += 3

  • co_stacksize 表示 code object 所需要的堆栈的大小
  • 操作码DEBUG_OP往堆栈中增加了三项,所以我们需要为这些增加的项预留些空间

现在我们可以将我们的操作码注入到每一个 Python 函数中了!

重写字节码

正如我们在上面的例子中所看到的那样,重写 Pyhton 的字节码似乎 so easy。为了在每一个操作码之间注入我们的操作码,我们需要获取每一个操作码的偏移量,然后将我们的操作码注入到这些位置上(把我们操作码注入到参数上是有坏处大大滴)。这些偏移量也很容易获取,使用dis.Bytecode ,就像这样 。

[py] view plaincopy
 
  1. def add_debug_op_everywhere(code_obj):  
  2.     # We get every instruction offset in the code object  
  3.     offsets = [instr.offset for instr in dis.Bytecode(code_obj)]  
  4.     # And insert a DEBUG_OP at every offset  
  5.     return insert_op_debug_list(code_obj, offsets)  
  6.   
  7. def insert_op_debug_list(code, offsets):  
  8.     # We insert the DEBUG_OP one by one  
  9.     for nb, off in enumerate(sorted(offsets)):  
  10.         # Need to ajust the offsets by the number of opcodes already inserted before  
  11.         # That's why we sort our offsets!  
  12.         code = insert_op_debug(code, off + nb)  
  13.     return code  
  14.   
  15. # Last problem: what does insert_op_debug looks like?  

基于上面的例子,有人可能会想我们的insert_op_debug会在指定的偏移量增加一个"x00",这尼玛是个坑啊!我们第一个DEBUG_OP注入的例子中被注入的函数是没有任何的分支的,为了能够实现完美一个函数注入函数insert_op_debug我们需要考虑到存在分支操作码的情况。 

Python 的分支一共有两种:

  • 绝对分支:看起来是类似这样子的Instruction_Pointer = argument(instruction)
  • 相对分支:看起来是类似这样子的Instruction_Pointer += argument(instruction)
    • 相对分支总是向前的

我们希望这些分支在我们插入操作码之后仍然能够正常工作,为此我们需要修改一些指令参数。以下是其逻辑流程:

  • 对于每一个在插入偏移量之前的相对分支而言
    • 如果目标地址是严格大于我们的插入偏移量的话,将指令参数增加 1
    • 如果相等,则不需要增加 1 就能够在跳转操作和目标地址之间执行我们的操作码DEBUG_OP
    • 如果小于,插入我们的操作码的话并不会影响到跳转操作和目标地址之间的距离
  • 对于 code object 中的每一个绝对分支而言
    • 如果目标地址是严格大于我们的插入偏移量的话,将指令参数增加 1
    • 如果相等,那么不需要任何修改,理由和相对分支部分是一样的
    • 如果小于,插入我们的操作码的话并不会影响到跳转操作和目标地址之间的距离

下面是实现:

[py] view plaincopy
 
  1. # Helper  
  2. def bytecode_to_string(bytecode):  
  3.     if bytecode.arg is not None:  
  4.         return struct.pack("<Bh", bytecode.opcode, bytecode.arg)  
  5.     return struct.pack("<B", bytecode.opcode)  
  6.   
  7. # Dummy class for bytecode_to_string  
  8. class DummyInstr:  
  9.     def __init__(self, opcode, arg):  
  10.         self.opcode = opcode  
  11.         self.arg = arg  
  12.   
  13. def insert_op_debug(code, offset):  
  14.     opcode_jump_rel = ['FOR_ITER', 'JUMP_FORWARD', 'SETUP_LOOP', 'SETUP_WITH', 'SETUP_EXCEPT', 'SETUP_FINALLY']  
  15.     opcode_jump_abs = ['POP_JUMP_IF_TRUE', 'POP_JUMP_IF_FALSE', 'JUMP_ABSOLUTE']  
  16.     res_codestring = b""  
  17.     inserted = False  
  18.     for instr in dis.Bytecode(code):  
  19.         if instr.offset == offset:  
  20.             res_codestring += b"x00"  
  21.             inserted = True  
  22.         if instr.opname in opcode_jump_rel and not inserted: #relative jump are always forward  
  23.             if offset < instr.offset + 3 + instr.arg: # inserted beetwen jump and dest: add 1 to dest (3 for size)  
  24.                 #If equal: jump on DEBUG_OP to get info before exec instr  
  25.                 res_codestring += bytecode_to_string(DummyInstr(instr.opcode, instr.arg + 1))  
  26.                 continue  
  27.         if instr.opname in opcode_jump_abs:  
  28.             if instr.arg > offset:  
  29.                 res_codestring += bytecode_to_string(DummyInstr(instr.opcode, instr.arg + 1))  
  30.                 continue  
  31.         res_codestring += bytecode_to_string(instr)  
  32.     # replace_bytecode just replaces the original code co_code  
  33.     return replace_bytecode(code, res_codestring)  

让我们看一下效果如何:

[py] view plaincopy
 
  1. >>> def lol(x):  
  2. ...     for i in range(10):  
  3. ...         if x == i:  
  4. ...             break  
  5.   
  6. >>> dis.dis(lol)  
  7. 101           0 SETUP_LOOP              36 (to 39)  
  8.               3 LOAD_GLOBAL              0 (range)  
  9.               6 LOAD_CONST               1 (10)  
  10.               9 CALL_FUNCTION            1 (1 positional, 0 keyword pair)  
  11.              12 GET_ITER  
  12.         >>   13 FOR_ITER                22 (to 38)  
  13.              16 STORE_FAST               1 (i)  
  14.   
  15. 102          19 LOAD_FAST                0 (x)  
  16.              22 LOAD_FAST                1 (i)  
  17.              25 COMPARE_OP               2 (==)  
  18.              28 POP_JUMP_IF_FALSE       13  
  19.   
  20. 103          31 BREAK_LOOP  
  21.              32 JUMP_ABSOLUTE           13  
  22.              35 JUMP_ABSOLUTE           13  
  23.         >>   38 POP_BLOCK  
  24.         >>   39 LOAD_CONST               0 (None)  
  25.              42 RETURN_VALUE  
  26. >>> lol.__code__ = transform_code(lol.__code__, add_debug_op_everywhere, add_stacksize=3)  
  27.   
  28.   
  29. >>> dis.dis(lol)  
  30. 101           0 <0>  
  31.               1 SETUP_LOOP              50 (to 54)  
  32.               4 <0>  
  33.               5 LOAD_GLOBAL              0 (range)  
  34.               8 <0>  
  35.               9 LOAD_CONST               1 (10)  
  36.              12 <0>  
  37.              13 CALL_FUNCTION            1 (1 positional, 0 keyword pair)  
  38.              16 <0>  
  39.              17 GET_ITER  
  40.         >>   18 <0>  
  41.   
  42. 102          19 FOR_ITER                30 (to 52)  
  43.              22 <0>  
  44.              23 STORE_FAST               1 (i)  
  45.              26 <0>  
  46.              27 LOAD_FAST                0 (x)  
  47.              30 <0>  
  48.   
  49. 103          31 LOAD_FAST                1 (i)  
  50.              34 <0>  
  51.              35 COMPARE_OP               2 (==)  
  52.              38 <0>  
  53.              39 POP_JUMP_IF_FALSE       18  
  54.              42 <0>  
  55.              43 BREAK_LOOP  
  56.              44 <0>  
  57.              45 JUMP_ABSOLUTE           18  
  58.              48 <0>  
  59.              49 JUMP_ABSOLUTE           18  
  60.         >>   52 <0>  
  61.              53 POP_BLOCK  
  62.         >>   54 <0>  
  63.              55 LOAD_CONST               0 (None)  
  64.              58 <0>  
  65.              59 RETURN_VALUE  
  66.   
  67. # Setup the simplest handler EVER  
  68. >>> def op_target(stack, frame):  
  69. ...     print (stack)  
  70.   
  71. # GO  
  72. >>> lol(2)  
  73. []  
  74. []  
  75. [<class 'range'>]  
  76. [10, <class 'range'>]  
  77. [range(0, 10)]  
  78. [<range_iterator object at 0x7f1349afab80>]  
  79. [0, <range_iterator object at 0x7f1349afab80>]  
  80. [<range_iterator object at 0x7f1349afab80>]  
  81. [2, <range_iterator object at 0x7f1349afab80>]  
  82. [0, 2, <range_iterator object at 0x7f1349afab80>]  
  83. [False, <range_iterator object at 0x7f1349afab80>]  
  84. [<range_iterator object at 0x7f1349afab80>]  
  85. [1, <range_iterator object at 0x7f1349afab80>]  
  86. [<range_iterator object at 0x7f1349afab80>]  
  87. [2, <range_iterator object at 0x7f1349afab80>]  
  88. [1, 2, <range_iterator object at 0x7f1349afab80>]  
  89. [False, <range_iterator object at 0x7f1349afab80>]  
  90. [<range_iterator object at 0x7f1349afab80>]  
  91. [2, <range_iterator object at 0x7f1349afab80>]  
  92. [<range_iterator object at 0x7f1349afab80>]  
  93. [2, <range_iterator object at 0x7f1349afab80>]  
  94. [2, 2, <range_iterator object at 0x7f1349afab80>]  
  95. [True, <range_iterator object at 0x7f1349afab80>]  
  96. [<range_iterator object at 0x7f1349afab80>]  
  97. []  
  98. [None]  

甚好!现在我们知道了如何获取堆栈信息和 Python 中每一个操作对应的帧信息。上面结果所展示的结果目前而言并不是很实用。在最后一部分中让我们对注入做进一步的封装。 

增加 Python 封装

正如您所见到的,所有的底层接口都是好用的。我们最后要做的一件事是让 op_target 更加方便使用(这部分相对而言比较空泛一些,毕竟在我看来这不是整个项目中最有趣的部分)。

首先我们来看一下帧的参数所能提供的信息,如下所示:

  • f_code当前帧将执行的 code object
  • f_lasti当前的操作(code object 中的字节码字符串的索引)

经过我们的处理我们可以得知DEBUG_OP之后要被执行的操作码,这对我们聚合数据并展示是相当有用的。

新建一个用于追踪函数内部机制的类:

  • 改变函数自身的co_code
  • 设置回调函数作为op_debug的目标函数

一旦我们知道下一个操作,我们就可以分析它并修改它的参数。举例来说我们可以增加一个auto-follow-called-functions的特性。

[py] view plaincopy
 
  1. def op_target(l, f, exc=None):  
  2.     if op_target.callback is not None:  
  3.         op_target.callback(l, f, exc)  
  4.   
  5. class Trace:  
  6.     def __init__(self, func):  
  7.         self.func = func  
  8.   
  9.     def call(self, *args, **kwargs):  
  10.         self.add_func_to_trace(self.func)  
  11.         # Activate Trace callback for the func call  
  12.         op_target.callback = self.callback  
  13.         try:  
  14.             res = self.func(*args, **kwargs)  
  15.         except Exception as e:  
  16.             res = e  
  17.         op_target.callback = None  
  18.         return res  
  19.   
  20.     def add_func_to_trace(self, f):  
  21.         # Is it code? is it already transformed?  
  22.         if not hasattr(f ,"op_debug") and hasattr(f, "__code__"):  
  23.             f.__code__ = transform_code(f.__code__, transform=add_everywhere, add_stacksize=ADD_STACK)  
  24.             f.__globals__['op_target'] = op_target  
  25.             f.op_debug = True  
  26.   
  27.     def do_auto_follow(self, stack, frame):  
  28.         # Nothing fancy: FrameAnalyser is just the wrapper that gives the next executed instruction  
  29.         next_instr = FrameAnalyser(frame).next_instr()  
  30.         if "CALL" in next_instr.opname:  
  31.             arg = next_instr.arg  
  32.             f_index = (arg & 0xff) + (2 * (arg >> 8))  
  33.             called_func = stack[f_index]  
  34.   
  35.             # If call target is not traced yet: do it  
  36.             if not hasattr(called_func, "op_debug"):  
  37.                 self.add_func_to_trace(called_func)  

现在我们实现一个 Trace 的子类,在这个子类中增加 callback 和 doreport 这两个方法。callback 方法将在每一个操作之后被调用。doreport 方法将我们收集到的信息打印出来。

这是一个伪函数追踪器实现:

[py] view plaincopy
 
  1. class DummyTrace(Trace):  
  2.     def __init__(self, func):  
  3.         self.func = func  
  4.         self.data = collections.OrderedDict()  
  5.         self.last_frame = None  
  6.         self.known_frame = []  
  7.         self.report = []  
  8.   
  9.     def callback(self, stack, frame, exc):  
  10.         if frame not in self.known_frame:  
  11.             self.known_frame.append(frame)  
  12.             self.report.append(" === Entering New Frame {0} ({1}) ===".format(frame.f_code.co_name, id(frame)))  
  13.             self.last_frame = frame  
  14.         if frame != self.last_frame:  
  15.             self.report.append(" === Returning to Frame {0} {1}===".format(frame.f_code.co_name, id(frame)))  
  16.             self.last_frame = frame  
  17.   
  18.         self.report.append(str(stack))  
  19.         instr = FrameAnalyser(frame).next_instr()  
  20.         offset = str(instr.offset).rjust(8)  
  21.         opname = str(instr.opname).ljust(20)  
  22.         arg = str(instr.arg).ljust(10)  
  23.         self.report.append("{0}  {1} {2} {3}".format(offset, opname, arg, instr.argval))  
  24.         self.do_auto_follow(stack, frame)  
  25.   
  26.     def do_report(self):  
  27.         print(" ".join(self.report))  

这里有一些实现的例子和使用方法。格式有些不方便观看,毕竟我并不擅长于搞这种对用户友好的报告的事儿。

  • 例1自动追踪堆栈信息和已经执行的指令
  • 例2上下文管理

递推式构造列表(List Comprehensions)的追踪示例 。

  • 例3伪追踪器的输出
  • 例4输出收集的堆栈信息

总结

这个小项目是一个了解 Python 底层的良好途径,包括解释器的 main loop,Python 实现的 C 代码编程、Python 字节码。通过这个小工具我们可以看到 Python 一些有趣构造函数的字节码行为,例如生成器、上下文管理和递推式构造列表。

这里是这个小项目的完整代码。更进一步的,我们还可以做的是修改我们所追踪的函数的堆栈。我虽然不确定这个是否有用,但是可以肯定是这一过程是相当有趣的。

原文链接: Understanding Python execution from inside: A Python assembly tracer 

原文地址:https://www.cnblogs.com/jackyzzy/p/4554691.html