PHP hooks

coldplay.xixi
Release: 2023-04-09 11:42:02
forward
3139 people have browsed it

PHP hooks

Hooks provided by PHP

PHP and Zend Engine provide many different hooks for extensions that allow extension developers Control the PHP runtime in a way that PHP userland cannot provide.

This chapter will show various hooks and common use cases from extension hooks to them.

The general pattern for hooking into PHP functionality is to extend override function pointers provided by PHP core. The extension function then typically does its own work and calls the original PHP core functions. Using this pattern, different extensions can override the same hook without causing conflicts.

Related learning recommendations: PHP programming from entry to proficiency

Hooking to the execution of functions

## Execution of #userland and internal functions is handled by two functions in the Zend engine, which you can replace with your own implementation. The main use cases for extensions that cover this hook are general function-level profiling, debugging, and aspect-oriented programming.

The hook is defined in

Zend/zend_execute.h:

ZEND_API extern void (*zend_execute_ex)(zend_execute_data *execute_data);ZEND_API extern void (*zend_execute_internal)(zend_execute_data *execute_data, zval *return_value);
Copy after login

If you want to overwrite these function pointers, you must do this in Minit because of the Other decisions are made ahead of time based on the fact that the pointer is overwritten.

The usual pattern for overwriting is this:

static void (*original_zend_execute_ex) (zend_execute_data *execute_data);static void (*original_zend_execute_internal) (zend_execute_data *execute_data, zval *return_value);void my_execute_internal(zend_execute_data *execute_data, zval *return_value);void my_execute_ex (zend_execute_data *execute_data);PHP_MINIT_FUNCTION(my_extension){
    REGISTER_INI_ENTRIES();

    original_zend_execute_internal = zend_execute_internal;
    zend_execute_internal = my_execute_internal;

    original_zend_execute_ex = zend_execute_ex;
    zend_execute_ex = my_execute_ex;

    return SUCCESS;}PHP_MSHUTDOWN_FUNCTION(my_extension){
    zend_execute_internal = original_zend_execute_internal;
    zend_execute_ex = original_zend_execute_ex;

    return SUCCESS;}
Copy after login

One drawback of overriding

zend_execute_ex is that it changes the behavior of the Zend Virtual Machine runtime to use recursion instead of Handles calls without leaving the interpreter loop. Additionally, PHP engines that do not override zend_execute_ex may also generate more optimized function call opcodes.

These hooks are very performance sensitive, depending on the complexity of the original function encapsulation code.

Override internal functions

When overriding execution hooks, the extension can log

each function call, you can also override userland, core and Individual function pointers to extension functions (and methods). It has better performance characteristics if the extension only needs access to specific internal function calls.

#if PHP_VERSION_ID < 70200typedef void (*zif_handler)(INTERNAL_FUNCTION_PARAMETERS);#endif
zif_handler original_handler_var_dump;ZEND_NAMED_FUNCTION(my_overwrite_var_dump){
    // 如果我们想调用原始函数
    original_handler_var_dump(INTERNAL_FUNCTION_PARAM_PASSTHRU);}PHP_MINIT_FUNCTION(my_extension){
    zend_function *original;

    original = zend_hash_str_find_ptr(EG(function_table), "var_dump", sizeof("var_dump")-1);

    if (original != NULL) {
        original_handler_var_dump = original->internal_function.handler;
        original->internal_function.handler = my_overwrite_var_dump;
    }}
Copy after login

When overriding a class method, the function table can be found on

zend_class_entry:

zend_class_entry *ce = zend_hash_str_find_ptr(CG(class_table), "PDO", sizeof("PDO")-1);if (ce != NULL) {
    original = zend_hash_str_find_ptr(&ce->function_table, "exec", sizeof("exec")-1);

    if (original != NULL) {
        original_handler_pdo_exec = original->internal_function.handler;
        original->internal_function.handler = my_overwrite_pdo_exec;
    }}
Copy after login

Modify the Abstract Syntax Tree (AST)

When PHP 7 compiles PHP code, it first converts it into an abstract syntax tree (AST), and then finally generates opcodes that are persisted in Opcache.

zend_ast_processThe hook is called by every compiled script and allows you to modify the AST after it has been parsed and created.

This is one of the most complex hooks to use because it requires complete knowledge of the AST. Creating an invalid AST here may cause unexpected behavior or crashes.

Better take a look at a sample extension that uses this hook:

    Google Stackdriver PHP Debugger Extension
  • Stackdriver-based proof-of-concept with AST

Familiarity with script/file compilation

Whenever a user script calls

include/require or its corresponding include_once/require_once, the PHP kernel will call this function at the pointer zend_compile_file to handle this request. The parameter is a file handle and the result is zend_op_array.

zend_op_array * my_extension_compile_file(zend_file_handle * file_handle,int类型);
Copy after login

There are two extensions in PHP core that implement this hook: dtrace and opcache.

- If you use the environment variable

USE_ZEND_DTRACE to start a PHP script and compile PHP with dtrace support, the dtrace_compile_file is used for Zend/zend_dtrace.c . - Opcache stores the op array in shared memory for better performance, so whenever a script is compiled, its final op array is served from cache rather than recompiled. You can find this implementation in
ext/opcache/ZendAccelerator.c. - The default implementation named
compile_file is part of the scanner code in Zend/zend_language_scanner.l.

Use cases for implementing this hook are Opcode Accelerating, PHP code encryption/decryption, debugging or profiling.

You can replace this hook at any time while the PHP process is executing, and all PHP scripts compiled after the replacement will be handled by the hook's implementation.

It is very important to always call the original function pointer, otherwise PHP will no longer be able to compile the script and Opcache will no longer work.

此处的扩展覆盖顺序也很重要,因为您需要知道是要在Opcache之前还是之后注册钩子,因为Opcache如果在其共享内存缓存中找到操作码数组条目,则不会调用原始函数指针。 Opcache将其钩子注册为启动后钩子,该钩子在扩展的minit阶段之后运行,因此默认情况下,缓存脚本时将不再调用该钩子。

调用错误处理程序时的通知

与PHP用户区set_error_handler()函数类似,扩展可以通过实现zend_error_cb钩子将自身注册为错误处理程序:

ZEND_API void(* zend_error_cb)(int类型,const char * error_filename,const uint32_t error_lineno,const char * format,va_list args);
Copy after login

type变量对应于E _ *错误常量,该常量在PHP用户区中也可用。

PHP核心和用户态错误处理程序之间的关系很复杂:

1.如果未注册任何用户级错误处理程序,则始终调用zend_error_cb
2.如果注册了userland错误处理程序,则对于E_ERRORE_PARSEE_CORE_ERRORE_CORE_WARNINGE_COMPILE_ERROR的所有错误E_COMPILE_WARNING始终调用zend_error_cb挂钩。
3.对于所有其他错误,仅在用户态处理程序失败或返回false时调用zend_error_cb

另外,由于Xdebug自身复杂的实现,它以不调用以前注册的内部处理程序的方式覆盖错误处理程序。

因此,覆盖此挂钩不是很可靠。

再次覆盖应该以尊重原始处理程序的方式进行,除非您想完全替换它:

void(* original_zend_error_cb)(int类型,const char * error_filename,const uint error_lineno,const char * format,va_list args);void my_error_cb(int类型,const char * error_filename,const uint error_lineno,const char * format,va_list args){
    //我的特殊错误处理

    original_zend_error_cb(type,error_filename,error_lineno,format,args);}PHP_MINIT_FUNCTION(my_extension){
    original_zend_error_cb = zend_error_cb;
    zend_error_cb = my_error_cb;

    return SUCCESS;}PHP_MSHUTDOWN(my_extension){
    zend_error_cb = original_zend_error_cb;}
Copy after login

该挂钩主要用于为异常跟踪或应用程序性能管理软件实施集中式异常跟踪。

引发异常时的通知

每当PHP Core或Userland代码引发异常时,都会调用zend_throw_exception_hook并将异常作为参数。

这个钩子的签名非常简单:

void my_throw_exception_hook(zval * exception){
    if(original_zend_throw_exception_hook!= NULL){
        original_zend_throw_exception_hook(exception);
    }}
Copy after login

该挂钩没有默认实现,如果未被扩展覆盖,则指向NULL

static void(* original_zend_throw_exception_hook)(zval * ex);void my_throw_exception_hook(zval * exception);PHP_MINIT_FUNCTION(my_extension){
    original_zend_throw_exception_hook = zend_throw_exception_hook;
    zend_throw_exception_hook = my_throw_exception_hook;

    return SUCCESS;}
Copy after login

如果实现此挂钩,请注意无论是否捕获到异常,都会调用此挂钩。将异常临时存储在此处,然后将其与错误处理程序挂钩的实现结合起来以检查异常是否未被捕获并导致脚本停止,仍然有用。

实现此挂钩的用例包括调试,日志记录和异常跟踪。

挂接到eval()

PHPeval不是内部函数,而是一种特殊的语言构造。因此,您无法通过zend_execute_internal或通过覆盖其函数指针来连接它。

挂钩到eval的用例并不多,您可以将其用于概要分析或出于安全目的。如果更改其行为,请注意可能需要评估其他扩展名。一个示例是Xdebug,它使用它执行断点条件。

extern ZEND_API zend_op_array *(* zend_compile_string)(zval * source_string,char * filename);
Copy after login

挂入垃圾收集器

当可收集对象的数量达到一定阈值时,引擎本身会调用gc_collect_cycles()或隐式地触发PHP垃圾收集器。

为了使您了解垃圾收集器的工作方式或分析其性能,可以覆盖执行垃圾收集操作的函数指针挂钩。从理论上讲,您可以在此处实现自己的垃圾收集算法,但是如果有必要对引擎进行其他更改,则这可能实际上并不可行。

int(* original_gc_collect_cycles)(无效);int my_gc_collect_cycles(无效){
    original_gc_collect_cycles();}PHP_MINIT_FUNCTION(my_extension){
    original_gc_collect_cycles = gc_collect_cycles;
    gc_collect_cycles = my_gc_collect_cycles;

    return SUCCESS;}
Copy after login

覆盖中断处理程序

当执行器全局EG(vm_interrupt)设置为1时,将调用一次中断处理程序。在执行用户域代码期间,将在常规检查点对它进行检查。引擎使用此挂钩通过信号处理程序实现PHP执行超时,该信号处理程序在达到超时持续时间后将中断设置为1。

当更安全地清理或实现自己的超时处理时,这有助于将信号处理推迟到运行时执行的后期。通过设置此挂钩,您不会意外禁用PHP的超时检查,因为它具有自定义处理的优先级,该优先级高于对zend_interrupt_function的任何覆盖。

ZEND_API void(* original_interrupt_function)(zend_execute_data * execute_data);void my_interrupt_function(zend_execute_data * execute_data){
    if(original_interrupt_function!= NULL){
        original_interrupt_function(execute_data);
    }}PHP_MINIT_FUNCTION(my_extension){
    original_interrupt_function = zend_interrupt_function;
    zend_interrupt_function = my_interrupt_function;

    return SUCCESS;}
Copy after login

##替换操作码处理程序

TODO

The above is the detailed content of PHP hooks. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template