Repository navigation
Description
Summary
When handlers are installed on an implementor from inside an interface_gets_implemented hook, the write_property handler silently never fires if opcache is enabled. The interface hook itself fires, and the create_object handler installed in the same callback fires — only write_property is lost.
There is no error, warning or crash: property writes just take effect as if no handler existed. Any package that gates writes this way (e.g. lisachenko/immutable-object) silently stops enforcing anything.
Reproduced on both supported lines: PHP 8.4.19 + z-engine 8.4.2 and PHP 8.5.9 + z-engine 8.5.0.
Observed behaviour
opcache.jit=off, ffi.enable=1, varying only opcache.enable_cli:
| PHP / z-engine | opcache | link path | interface hook | create_object |
write_property |
|---|---|---|---|---|---|
| 8.4.19 / 8.4.2 | off | include | fired | fired | fired |
| 8.4.19 / 8.4.2 | off | autoload | fired | fired | fired |
| 8.4.19 / 8.4.2 | on | include | fired | fired | NOT fired |
| 8.4.19 / 8.4.2 | on | autoload | fired | fired | NOT fired |
| 8.5.9 / 8.5.0 | off | include | fired | fired | fired |
| 8.5.9 / 8.5.0 | off | autoload | fired | fired | fired |
| 8.5.9 / 8.5.0 | on | include | fired | fired | NOT fired |
| 8.5.9 / 8.5.0 | on | autoload | fired | fired | NOT fired |
The link path (plain include vs autoloader callback) makes no difference; opcache.enable_cli is the only variable that changes the outcome.
Scope: only the interface-hook path is affected
Installing the same two handlers directly on an already-declared class, with no interface hook involved, works under opcache on both minors:
php8.4 opcache=1 direct install | create_object: fired | write_property: fired
php8.5 opcache=1 direct install | create_object: fired | write_property: fired
That is consistent with the sibling packages being unaffected — native-php-matrix, scalar-objects and native-php-coroutines install their handlers on named classes and their suites pass with opcache enabled.
Reproducer
<?php
declare(strict_types=1);
use ZEngine\ClassExtension\Hook\CreateObjectHook;
use ZEngine\ClassExtension\Hook\InterfaceGetsImplementedHook;
use ZEngine\ClassExtension\Hook\WritePropertyHook;
use ZEngine\Core;
use ZEngine\Reflection\ReflectionClass;
include __DIR__ . '/vendor/autoload.php';
Core::init();
interface Marker {}
$GLOBALS['log'] = [];
(new ReflectionClass(Marker::class))->setInterfaceGetsImplementedHandler(
static function (InterfaceGetsImplementedHook $hook): int {
$GLOBALS['log'][] = 'interface-hook';
$class = $hook->getClass();
$class->setCreateObjectHandler(static function (CreateObjectHook $h): object {
$GLOBALS['log'][] = 'create-object';
return $h->proceed();
});
$class->setWritePropertyHandler(static function (WritePropertyHook $h) {
$GLOBALS['log'][] = 'write-property';
return $h->getValue();
});
return Core::SUCCESS;
}
);
include __DIR__ . '/Implementor.php'; // class Implementor implements Marker { public $p = 1; }
$o = new Implementor();
$o->p = 42;
$fired = static fn (string $n): string => in_array($n, $GLOBALS['log'], true) ? 'fired' : 'NOT fired';
printf("iface: %s | create_object: %s | write_property: %s\n",
$fired('interface-hook'), $fired('create-object'), $fired('write-property'));php -d ffi.enable=1 -d opcache.jit=off -d opcache.enable_cli=0 repro.php
# iface: fired | create_object: fired | write_property: fired
php -d ffi.enable=1 -d opcache.jit=off -d opcache.enable_cli=1 repro.php
# iface: fired | create_object: fired | write_property: NOT firedHypothesis (not verified — offered only as a starting point)
create_object is a plain field on the class entry, while the other handlers live in the zend_object_handlers block z-engine allocates and attaches. During interface linking under opcache the class entry is on its way into shared memory, so the field write survives while the attached handlers block does not — the object ends up with the stock handler table. Someone with the opcache/SHM paths in hand can confirm or discard this quickly; the reproducer above is the cheap way to test a candidate fix.
Why this is worth more than a documentation note
The existing documented property — "op_arrays compiled before the hook was installed are served as-is until invalidated" — leaves a hook inert, which is visible. This leaves it installed but ineffective, which is not: the consumer sees a successfully installed handler, no diagnostic of any kind, and writes that quietly go through. Even a loud failure at install time would be a large improvement over the current silence.
Environment
- PHP 8.4.19 (NTS) and PHP 8.5.9 (NTS), linux-x64
- z-engine 8.4.2 and 8.5.0 (stable tags)
ffi.enable=1,opcache.jit=off; onlyopcache.enable_clivaried
Downstream symptom tracked in lisachenko/immutable-object.
Activity
lisachenko commentedon Aug 19, 2026
Diagnosis: the class entry the interface hook is handed is a throw-away copy, and only the address-keyed handler table notices
Confirmed on both lines (PHP 8.4.19 / z-engine 8.4.2 and PHP 8.5.9 / z-engine 8.5.0). The hypothesis in the report is close but not what happens: the
zend_object_handlersblock does survive — it is simply keyed to azend_class_entrythat nothing ever looks up again.Mechanism
Under opcache, a class that is linked at runtime against an interface from another (cached) file is not linked in place:
ZEND_ACC_IMMUTABLE.zend_do_link_class()cannot write to it, so it links a mutable process-local copy (lazy class load).interface_gets_implementedis called with that temporary copy. This is the entry$hook->getClass()wraps, and the one every handler installed inside the callback is installed on.Everything that is a plain field of
zend_class_entry—create_objectamong them — is carried into the SHM copy by that struct copy, so thecreate_objecttrampoline still fires. z-engine's object-handlers block is not a field of the class entry:ReflectionClass::$objectHandlersis a static map keyed by class-entry address. The address changed, sogetObjectHandlers()misses, allocates a pristine copy ofstd_object_handlers, andnewInstanceRaw()hands the new object that virgin table.Address instrumentation across the three points (matches the table already gathered downstream):
ce_flagsconfirm what the two entries are — hook time0x441200(ZEND_ACC_CACHED, not linked, not immutable = the lazy copy), live entry0x441288(ZEND_ACC_LINKED | ZEND_ACC_IMMUTABLE= the SHM inheritance-cache copy).Direct proof, from
ReflectionClass::$objectHandlersafter the runDumping the private map plus
std_object_handlersafter$o->p = 42(PHP 8.5.9, opcache on):Two blocks, one class. The first is keyed to the discarded temporary entry and holds the hook; the second was allocated for the SHM entry at
newtime and is byte-identical to the stock table. Identical result on PHP 8.4.19. With opcache off there is exactly one entry in the map and the handler fires.Ruled out
ZEND_ACC_CACHED | ZEND_ACC_CACHEABLE | ZEND_ACC_IMMUTABLEon the entry the hook receives changes nothing — the cacheability decision is latched in a C local inzend_do_link_class()before the callback runs. Verified on both minors: the entry still moves.includevs. autoloader callback is irrelevant, as reported.opcache.jit. Off throughout.Reproduction gotcha worth recording
The bug can look intermittent.
opcache.file_update_protection(default 2s) refuses to cache a file whose mtime is younger than that, and the inheritance cache also declines when a dependency is not itself in SHM. So a freshly written reproducer, or a freshly written file declaring the interface, will pass — the entry is never relocated. Let the files age past 2 seconds before drawing conclusions; after that it is 100% deterministic here.What a fix has to do
The association between class and handler block must travel with the class entry instead of being kept beside it in an address-keyed PHP array. The engine already provides the field for exactly that:
zend_class_entry.default_object_handlers(present in the generatedengine.hfor both 8.4 and 8.5, and instubs/zend-engine-structs.php). It is a plain pointer field, so the struct copy into the inheritance cache carries it, andzend_objects_new()reads it.I verified this end to end on both minors. Installing only
setWritePropertyHandler()from the interface callback — nocreate_objectat all — and stamping the allocated block into$ce->default_object_handlers:So the shape of the fix in
ReflectionClass::getObjectHandlers()is roughly: on a miss, before allocating, look at$classType->default_object_handlersand adopt it if it is a block we own (identity set keyed by block address); otherwise allocate, seed the copy from the class's existing default handlers rather than unconditionally fromstd_object_handlers, and publish it into the field.Three judgement calls belong to you, which is why I am not opening a patch PR:
create_objecthandler is required for all other handlers" — publishing the block makessetWritePropertyHandler()alone effective, and changes whatobj->handlerspoints at for classes that previously had non-create_objecthandlers installed silently doing nothing.std_object_handlers(a user class extending an internal one) must seed from the existing pointer, or their instances lose the parent's handler table.repro5) operates on an entry withce_flags=0x401288, i.e.ZEND_ACC_IMMUTABLE— the handler installers are the one mutation family that does not go throughensureWritableEntry()/copyOutOfSharedMemory(), so z-engine already writescreate_objectstraight into shared memory there. That is pre-existing, not introduced by a fix, but a fix that publishes one more field into SHM should be a deliberate decision, not a side effect.Residual hazard, independent of any of the above
Whichever route is taken, the entry that ends up in opcache's inheritance cache holds
create_object= the address of a process-local libffi trampoline. In CLI that is harmless. In a persistent, multi-process SAPI the inheritance-cache entry is shared and outlives the request that created it, so another worker (or a later request) can reach a trampoline that does not exist in its address space. Relatedly, the hook objects keeprawStructurepointing at the temporary entry the engine discarded, souninstall()/Core::shutdown()restores the pointer on an entry the engine no longer uses. If the conclusion is that installing class-entry handlers during interface linking cannot be made sound under opcache, then the honest fix is the loud failure the report asks for rather than the silent one — but that decision needs the FPM/multi-worker view, which I could not exercise here.Alternatives considered and set aside
zend_stringread inside an FFI callback;default_object_handlersis what the engine provides for this.zend_inheritance_cache_add(aZEND_API externfunction pointer, so hookable) to either re-home the handlers onto the SHM copy or decline caching for hooked classes. This is the only route that also removes the residual hazard above — declining the cache keeps the linked entry process-local and mutable, at the cost of not caching that one class. It requires adding the symbol totools/generator/symbols.phpand regeneratingengine.hfor all 14 platform targets, which cannot be done or validated from this environment.Verification notes
All measurements above were taken against the released
8.4.2/8.5.0tags withffi.enable=1 -d opcache.jit=off, varying onlyopcache.enable_cli. No segfault or bus error was observed at any point. The full test suite was not run — the environment has no network route to Packagist for the dev dependencies — which is the other reason this is a diagnosis rather than a patch.If the
default_object_handlersroute is the one you want, it belongs on the8.4branch first and cascades tomaster; the field and its stub exist identically on both lines, so the port should be textual.Generated by Claude Code
lisachenko commentedon Aug 19, 2026
Decision (agreed with the maintainer)
Route discussion concluded as C now + B follow-up:
Now (lands with the opcache CI/bug-collection effort,
8.4→ cascade tomaster): a loud guard. Handler installation (setXxxHandler(),installExtensionHandlers()) on a class entry that is a lazy-linking temporary —ZEND_ACC_CACHEDset,ZEND_ACC_LINKEDclear, the only state aninterface_gets_implementedhook ever observes under opcache — throwsSharedMemoryExceptioninstead of silently installing handlers that die with the temporary. A new publicReflectionClass::isLazyLinkingCopy()lets hook authors probe instead of catching. Documented in the hot-swap opcache support matrix. This converts the silent failure this issue reports into the loud one it asks for as a minimum.Follow-up — feat(opcache): decline inheritance-cache publication for classes that receive handlers during linking #241: the actual fix. Intercept
zend_inheritance_cache_add(hookableZEND_APIfunction pointer) and decline inheritance-cache publication for classes that received handlers during linking. The linked entry then stays process-local and mutable, the handlers fire, and the multi-worker hazard disappears by construction (no process-local trampoline address is ever published into shared memory). Needs a new generator symbol + header regeneration for all platform targets, hence a separate ticket.Rejected — publishing the handler block via
ce->default_object_handlers(the route sketched in the diagnosis above): verified to work in CLI, but it writes into the SHM entry, changes the documented "create_object required first" contract, and leaves the FPM hazard — the shared inheritance-cache entry would carry a process-local libffi trampoline address reachable from sibling workers. Not shippable for multi-worker SAPIs, and a CLI-only carve-out was judged not worth the contract change given feat(opcache): decline inheritance-cache publication for classes that receive handlers during linking #241 removes the hazard entirely.This issue stays open until #241 lands (the guard makes the breakage loud, not fixed).
Generated by Claude Code