lisachenko / z-engine
提供对原生PHP结构直接访问的库
Requires
- php: 8.0.*
- ext-ffi: *
Requires (Dev)
- phpunit/phpunit: ^8.5.15 || ^9.0.0
README
你是否曾经梦想过模拟一个final类或重定义final方法?或者可能在运行时与现有类进行交互?Z-Engine
是一个PHP7.4库,它为PHP提供API。忘掉所有现有的限制,使用这个库在运行时通过声明新方法、向类添加新接口以及安装自己的系统钩子(如opcode编译、对象初始化等)来转换你的现有代码。
⚠️在1.0.0版本发布前,不要在生产环境中使用!
它是如何工作的?
如你所知,PHP 7.4包含一个名为FFI的新功能。它允许加载共享库(.dll或.so),调用C函数以及在纯PHP中访问C数据结构,无需深入了解Zend扩展API,也无需学习第三“中间”语言。
Z-Engine
使用FFI来访问PHP本身的内部结构。这个想法听起来非常疯狂,但竟然可行!Z-Engine
加载原生PHP结构(如zend_class_entry
、zval
等)的定义,并在运行时对其进行操作。当然,这是危险的,因为FFI允许在非常低的级别上与结构进行操作。因此,你应该预计会发生段错误、内存泄漏和其他不良情况。
先决条件和初始化
由于这个库依赖于FFI
,它需要PHP>=7.4和启用FFI
扩展。它应该在没有任何麻烦的情况下在CLI模式下工作,而对于Web模式,需要激活preload
模式。此外,当前版本仅限于x64非线程安全版本的PHP。
要安装此库,只需通过composer
添加即可
composer require lisachenko/z-engine
要激活preload
模式,请将Core::preload()
调用添加到您的脚本中,该脚本由opcache.preload
指定。此调用将在服务器预加载期间执行,并由库用于在每次请求期间跳过不必要的C头文件处理。
下一步是用简短的Core::init()
调用初始化库本身
use ZEngine\Core; include __DIR__.'/vendor/autoload.php'; Core::init();
现在您可以使用以下示例进行测试
<?php declare(strict_types=1); use ZEngine\Reflection\ReflectionClass; include __DIR__.'/vendor/autoload.php'; final class FinalClass {} $refClass = new ReflectionClass(FinalClass::class); $refClass->setFinal(false); eval('class TestClass extends FinalClass {}'); // Should be created
要了解您可以使用此库做什么,请参阅库测试作为示例。
ReflectionClass
库提供对经典反射API的扩展,通过ReflectionClass
操作类的内部结构
setFinal(bool $isFinal = true): void
使指定的类变为final或非finalsetAbstract(bool $isAbstract = true): void
使指定的类变为abstract或非abstract。即使它包含接口或抽象类中未实现的方法。setStartLine(int $newStartLine): void
更新关于类起始行的元信息setEndLine(int $newEndLine): void
更新关于类结束行的元信息setFileName(string $newFileName): void
为此类设置新文件名setParent(string $newParent)
[WIP] 为此类配置新的父类removeParentClass(): void
[WIP] 删除父类removeTraits(string ...$traitNames): void
[WIP] 从类中删除现有的特性addTraits(string ...$traitNames): void
[WIP] 向类中添加新的特性removeMethods(string ...$methodNames): void
从类中删除方法列表addMethod(string $methodName, \Closure $method): ReflectionMethod
向类中添加新的方法removeInterfaces(string ...$interfaceNames): void
从类中移除一系列接口名称。addInterfaces(string ...$interfaceNames): void
向指定的类添加一系列接口。
此外,所有返回 ReflectionMethod
或 ReflectionClass
的方法都被装饰,以返回具有对原生结构低级访问的扩展对象。
ReflectionMethod
ReflectionMethods
包含用于操作现有方法定义的方法。
setFinal(bool $isFinal = true): void
将指定方法设置为final或非final。setAbstract(bool $isAbstract = true): void
将指定方法设置为抽象或非抽象。setPublic(): void
将指定方法设置为public。setProtected(): void
将指定方法设置为protected。setPrivate(): void
将指定方法设置为private。setStatic(bool $isStatic = true): void
声明方法为static或非static。setDeclaringClass(string $className): void
更改此方法的声明类名称。setDeprecated(bool $isDeprecated = true): void
声明此方法为已弃用或非已弃用。redefine(\Closure $newCode): void
使用闭包定义重新定义此方法。getOpCodes(): iterable
: [WIP] 返回此方法的指令列表。
ObjectStore API
PHP中的每个对象都有自己的唯一标识符,可以通过 spl_object_id($object)
获取。有时我们正在寻找通过其标识符获取对象的方法。不幸的是,PHP不提供此类API,而内部存在一个存储在全局 executor_globals
变量(即EG)中的 zend_objects_store
结构实例。
该库通过 Core::$executor->objectStore
提供了一个 ObjectStore
API,该API实现了 ArrayAccess
和 Countable
接口。这意味着您可以通过对象句柄访问此存储来获取任何现有对象。
use ZEngine\Core; $instance = new stdClass(); $handle = spl_object_id($instance); $objectEntry = Core::$executor->objectStore[$handle]; var_dump($objectEntry);
Object Extensions API
借助 z-engine
库,可以在不深入了解PHP引擎实现的情况下为您的类重载标准操作符。例如,假设您想定义原生矩阵操作符并使用它。
<?php use ZEngine\ClassExtension\ObjectCastInterface; use ZEngine\ClassExtension\ObjectCompareValuesInterface; use ZEngine\ClassExtension\ObjectCreateInterface; use ZEngine\ClassExtension\ObjectCreateTrait; use ZEngine\ClassExtension\ObjectDoOperationInterface; class Matrix implements ObjectCreateInterface, ObjectCompareValuesInterface, ObjectDoOperationInterface, ObjectCastInterface { use ObjectCreateTrait; // ... } $a = new Matrix([10, 20, 30]); $b = new Matrix([1, 2, 3]); $c = $a + $b; // Matrix([11, 22, 33]) $c *= 2; // Matrix([22, 44, 66])
有两种方法可以激活自定义处理程序。第一种方法是实现几个系统接口,如 ObjectCastInterface
、ObjectCompareValuesInterface
、ObjectCreateInterface
和 ObjectDoOperationInterface
。之后,您应该创建此包提供的 ReflectionClass
实例,并调用 installExtensionHandlers
方法来安装扩展。
use ZEngine\Reflection\ReflectionClass as ReflectionClassEx; // ... initialization logic $refClass = new ReflectionClassEx(Matrix::class); $refClass->installExtensionHandlers();
如果您无法访问代码(例如,供应商),则仍然可以定义自定义处理程序。您需要显式定义回调作为闭包,并通过 ReflectionClass
中的 set***Handler()
方法分配它们。
use ZEngine\ClassExtension\ObjectCreateTrait; use ZEngine\Reflection\ReflectionClass as ReflectionClassEx; $refClass = new ReflectionClassEx(Matrix::class); $handler = Closure::fromCallable([ObjectCreateTrait::class, '__init']); $refClass->setCreateObjectHandler($handler); $refClass->setCompareValuesHandler(function ($left, $right) { if (is_object($left)) { $left = spl_object_id($left); } if (is_object($right)) { $right = spl_object_id($right); } // Just for example, object with bigger object_id is considered bigger that object with smaller object_id return $left <=> $right; });
库提供以下接口
第一个是 ObjectCastInterface
,它提供处理将类实例转换为标量的钩子。典型示例如下:1) 显式的 $value = (int) $objectInstance
或隐式的:$value = 10 + $objectInstance;
,在这种情况下没有安装 do_operation
处理程序。请注意,此处理程序不处理转换为 array
类型的转换,因为它以不同的方式实现。
<?php use ZEngine\ClassExtension\Hook\CastObjectHook; /** * Interface ObjectCastInterface allows to cast given object to scalar values, like integer, floats, etc */ interface ObjectCastInterface { /** * Performs casting of given object to another value * * @param CastObjectHook $hook Instance of current hook * * @return mixed Casted value */ public static function __cast(CastObjectHook $hook); }
要获取转换类型,您应检查 $hook->getCastType()
方法,它将返回类型的整数值。可能的值作为公共常量在 ReflectionValue
类中声明。例如 ReflectionValue::IS_LONG
。
下一个是 ObjectCompareValuesInterface
接口,用于控制比较逻辑。例如,您可以比较两个对象或甚至比较对象与标量值:if ($object > 10 || $object < $anotherObject)
<?php use ZEngine\ClassExtension\Hook\CompareValuesHook; /** * Interface ObjectCompareValuesInterface allows to perform comparison of objects */ interface ObjectCompareValuesInterface { /** * Performs comparison of given object with another value * * @param CompareValuesHook $hook Instance of current hook * * @return int Result of comparison: 1 is greater, -1 is less, 0 is equal */ public static function __compare(CompareValuesHook $hook): int; }
处理器应检查通过调用$hook->getFirst()
和$hook->getSecond()
方法可以接收到的参数(其中之一应返回你的类的实例)并返回整数结果-1..1。其中1表示更大,-1表示更小,0表示相等。
接口ObjectDoOperationInterface
是最强大的一种,因为它让你控制应用于你的对象的数学运算符(例如ADD、SUB、MUL、DIV、POW等)。
<?php use ZEngine\ClassExtension\Hook\DoOperationHook; /** * Interface ObjectDoOperationInterface allows to perform math operations (aka operator overloading) on object */ interface ObjectDoOperationInterface { /** * Performs an operation on given object * * @param DoOperationHook $hook Instance of current hook * * @return mixed Result of operation value */ public static function __doOperation(DoOperationHook $hook); }
此处理器通过$hook->getOpcode()
接收一个操作码(参见OpCode::*
常量)和两个参数(其中之一是类的实例)通过$hook->getFirst()
和$hook->getSecond()
返回该操作的值。在此处理器中,你可以返回你对象的新的实例,以便有一个不可变对象的实例链。
重要提示:你必须首先安装create_object
处理器,以便在运行时安装钩子。另外,你不能为内部对象安装create_object
处理器。
有一个额外的方法叫做setInterfaceGetsImplementedHandler
,它对于安装接口的特殊处理器非常有用。interface_gets_implemented
回调使用与create_object
处理器相同的内存槽,并在任何类实现此接口时被调用。这为自动类扩展注册提供了有趣的选择,例如,如果类实现了ObjectCreateInterface
,则在回调中自动调用它的ReflectionClass->installExtensionHandlers()
。
抽象语法树API
正如你所知,PHP7使用抽象语法树来简化未来语言语法的开发,通过使用源代码的抽象模型。不幸的是,这些信息没有返回到用户级别。有几个PHP扩展,如nikic/php-ast和sgolemon/astkit,它们提供了对底层AST结构的低级绑定。Z-Engine
通过Compiler::parseString(string $source, string $fileName = '')
方法提供了访问AST的途径。此方法将返回实现NodeInterface
的树的最顶层节点。PHP有四种类型的AST节点,它们是:声明节点(类、方法等)、列表节点(可以包含任意数量的子节点)、简单节点(包含最多4个子节点,取决于类型)和可以存储任何值的特殊值节点类(通常是字符串或数字)。
以下是解析简单PHP代码的示例
use ZEngine\Core; $ast = Core::$compiler->parseString('echo "Hello, world!", PHP_EOL;', 'hi.php'); echo $ast->dump();
输出将如下所示
1: AST_STMT_LIST
1: AST_STMT_LIST
1: AST_ECHO
1: AST_ZVAL string('Hello, world!')
1: AST_ECHO
1: AST_CONST
1: AST_ZVAL attrs(0001) string('PHP_EOL')
节点提供简单的API,通过调用Node->replaceChild(int $index, ?Node $node)
来变异子节点。你可以在运行时创建自己的节点,或者使用Compiler::parseString(string $source, string $fileName = '')
的结果作为你的代码的替换。
修改抽象语法树
当PHP 7编译PHP代码时,它会将其转换为抽象语法树(AST),然后再最终生成持久化在Opcache中的Opcodes。对于每个编译的脚本都会调用zend_ast_process
钩子,这允许你在AST解析和创建后修改AST。
要安装zend_ast_process
钩子,请调用静态方法Core::setASTProcessHandler(Closure $callback)
,它接受一个回调,该回调将在AST处理期间被调用,并将接收一个AstProcessHook $hook
作为参数。你可以通过$hook->getAST(): NodeInterface
方法访问顶级节点项。
use ZEngine\Core; use ZEngine\System\Hook\AstProcessHook; Core::setASTProcessHandler(function (AstProcessHook $hook) { $ast = $hook->getAST(); echo "Parsed AST:", PHP_EOL, $ast->dump(); // Let's modify Yes to No ) echo $ast->getChild(0)->getChild(0)->getChild(0)->getValue()->setNativeValue('No'); }); eval('echo "Yes";'); // Parsed AST: // 1: AST_STMT_LIST // 1: AST_STMT_LIST // 1: AST_ECHO // 1: AST_ZVAL string('Yes') // No
你可以看到,评估结果已从"是"更改为"否",因为我们已经调整了我们的回调中给出的AST。但请注意,这是最复杂的钩子之一,因为它需要完美理解AST的可能性。在此处创建无效的AST可能导致奇怪的行为或崩溃。
在运行时创建PHP扩展
Z-Engine库最有趣的部分是使用PHP语言本身创建自己的PHP扩展。你不需要花费大量时间学习C语言;相反,你可以使用现成的API,从PHP本身创建自己的扩展模块!
当然,并非所有功能都可以在PHP中实现为扩展,例如,更改解析器语法或更改opcache的逻辑——对于这些,你将不得不深入研究引擎本身的代码。
让我们通过一个示例模块来创建一个全局变量模块,它是apcu的类似物,以便在请求完成后这些变量不会被清除。人们认为PHP有“无共享”的概念,因此无法在请求边界之外生存,因为当请求完成时,PHP会自动释放所有分配给对象的内存。然而,PHP本身可以处理全局变量,并且它们存储在通过指针 zend_module_entry.globals_ptr
加载的模块中。
因此,如果我们能在PHP中注册模块并为其分配全局内存,PHP就不会清除它,我们的模块就能在请求边界之外生存。
技术上,每个模块都表示以下结构
struct _zend_module_entry {
unsigned short size;
unsigned int zend_api;
unsigned char zend_debug;
unsigned char zts;
const struct _zend_ini_entry *ini_entry;
const struct _zend_module_dep *deps;
const char *name;
const struct _zend_function_entry *functions;
int (*module_startup_func)(int type, int module_number);
int (*module_shutdown_func)(int type, int module_number);
int (*request_startup_func)(int type, int module_number);
int (*request_shutdown_func)(int type, int module_number);
void (*info_func)(zend_module_entry *zend_module);
const char *version;
size_t globals_size;
#ifdef ZTS
ts_rsrc_id* globals_id_ptr;
#endif
#ifndef ZTS
void* globals_ptr;
#endif
void (*globals_ctor)(void *global);
void (*globals_dtor)(void *global);
int (*post_deactivate_func)(void);
int module_started;
unsigned char type;
void *handle;
int module_number;
const char *build_id;
};
你可以看到,我们可以定义几个回调,并且有几个字段包含关于zts、调试、API版本等的元信息,这些信息被PHP用来检查当前环境是否可以加载此模块。
从PHP方面来看,你应该从包含模块注册和启动通用逻辑的AbstractModule
类扩展你的模块类,并实现所有来自ModuleInterface
的必需方法。
让我们看看我们的简单模块
use ZEngine\EngineExtension\AbstractModule; class SimpleCountersModule extends AbstractModule { /** * Returns the target thread-safe mode for this module * * Use ZEND_THREAD_SAFE as default if your module does not depend on thread-safe mode. */ public static function targetThreadSafe(): bool { return ZEND_THREAD_SAFE; } /** * Returns the target debug mode for this module * * Use ZEND_DEBUG_BUILD as default if your module does not depend on debug mode. */ public static function targetDebug(): bool { return ZEND_DEBUG_BUILD; } /** * Returns the target API version for this module * * @see zend_modules.h:ZEND_MODULE_API_NO */ public static function targetApiVersion(): int { return 20190902; } /** * Returns true if this module should be persistent or false if temporary */ public static function targetPersistent(): bool { return true; } /** * Returns globals type (if present) or null if module doesn't use global memory */ public static function globalType(): ?string { return 'unsigned int[10]'; } }
我们的SimpleCountersModule
声明它将使用一个包含10个无符号整数的数组。它还提供了有关所需环境的某些信息(调试/zts/API版本)。一个重要的选项是,通过从targetPersistent()
方法返回true来标记我们的模块持久化。现在我们可以注册它并使用它了
$module = new SimpleCountersModule(); if (!$module->isModuleRegistered()) { $module->register(); $module->startup(); } $data = $module->getGlobals(); var_dump($data);
注意,在后续请求中模块将被注册,这就是为什么你不应该调用两次register。真正酷的是,模块的全局变量是真正的全局变量!它们将在请求之间被保留。尝试更新每个项以查看我们的数组在请求之间值是否增加
$index = mt_rand(0, 9); // If you have several workers, you should use worker pid to avoid race conditions $data[$index] = $data[$index] + 1; // We are increasing global counter by one /* Example of var_dump after several requests... object(FFI\CData:uint32_t[10])#35 (10) { [0]=> int(1) [1]=> int(1) [2]=> int(1) [3]=> int(3) [4]=> int(1) [5]=> int(1) [6]=> int(1) [7]=> int(2) [8]=> int(2) [9]=> int(2) }*/
当然,模块可以声明任何复杂的全局结构并按需使用。如果模块需要一些初始化,那么你可以在模块中实现ControlModuleGlobalsInterface
,并在模块启动过程中调用此回调。这可能对于注册额外的钩子、类扩展等或全局变量的初始化(填充预定义值、从数据库/文件系统等恢复状态)很有用
行为准则
本项目遵循贡献者公约行为准则。通过参与,你应遵守此准则。请报告任何不可接受的行为。
许可证
此库根据MIT许可证授权。
创建和维护此库对我来说是无休止的艰苦工作。这就是为什么只有一个简单的要求:请向世界回馈一些东西。无论是代码还是对这个项目的财务支持,完全取决于你。