PHP HOOK OPCode 是通过
int zend_set_user_opcode_handler(zend_uchar opcode, opcode_handler_t handler)
接口替换了 PHP 内置的 OPCode 的 handler (函数指针),那 PHP 是如何执行到我们替换后的 handler 的呢?
一、zend_user_opcodes 和 zend_user_opcode_handlers
以 PHP 5.1 版本为例,zend_set_user_opcode_handler() 接口的实现如下:
ZEND_API int zend_set_user_opcode_handler(zend_uchar opcode, opcode_handler_t handler)
{
if (opcode != ZEND_USER_OPCODE) {
zend_user_opcodes[opcode] = ZEND_USER_OPCODE;
zend_user_opcode_handlers[opcode] = handler;
return SUCCESS;
}
return FAILURE;
}
这里面用到了两个静态数组 zend_user_opcodes 和 zend_user_opcode_handlers,这两个数组的声明和初始化是由 zend_vm_gen.php 脚本根据 zend_vm_def.h 生成的,具体生成过程可参考
PHP内核生成zend_vm_opcodes.h - 知乎 (zhihu.com)
生成的 zend_cm_execute.h 文件里有这两个数组的声明和初始化,如下:
static opcode_handler_t zend_user_opcode_handlers[256] = {(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t)NULL,(opcode_handler_t

本文深入探讨了PHP HOOK的实现原理,通过分析`zend_set_user_opcode_handler`接口,以及`zend_user_opcodes`、`zend_user_opcode_handlers`和`zend_opcode_handlers`之间的关系,揭示了如何在PHP内核层面替换OPCode处理函数,实现自定义的HOOK机制。

6243

被折叠的 条评论
为什么被折叠?



