Skip to content

bug(opcache): a write_property handler installed from an interface_gets_implemented hook never fires when opcache is enabled #238

Closed

Description

@lisachenko

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 fired

Hypothesis (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; only opcache.enable_cli varied

Downstream symptom tracked in lisachenko/immutable-object.

Activity

  1. added
    bugSomething isn't working
    opcacheIssue is related to opcache integration. Either doesn't work well or behaves incorrect.
    on Aug 19, 2026
  2. lisachenko commented on Aug 19, 2026

    @lisachenko
    OwnerAuthor

    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_handlers block does survive — it is simply keyed to a zend_class_entry that 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:

    1. The compiled, unlinked entry is persisted into SHM and is ZEND_ACC_IMMUTABLE. zend_do_link_class() cannot write to it, so it links a mutable process-local copy (lazy class load).
    2. interface_gets_implemented is called with that temporary copy. This is the entry $hook->getClass() wraps, and the one every handler installed inside the callback is installed on.
    3. When linking finishes, opcache's inheritance cache takes over: the linked entry is copied into shared memory, the SHM copy becomes the live class, and the temporary is discarded.

    Everything that is a plain field of zend_class_entry — create_object among them — is carried into the SHM copy by that struct copy, so the create_object trampoline still fires. z-engine's object-handlers block is not a field of the class entry: ReflectionClass::$objectHandlers is a static map keyed by class-entry address. The address changed, so getObjectHandlers() misses, allocates a pristine copy of std_object_handlers, and newInstanceRaw() hands the new object that virgin table.

    Address instrumentation across the three points (matches the table already gathered downstream):

                                     opcache.enable_cli=1     opcache.enable_cli=0
    [interface_gets_implemented]     0x7f652cfecd70           0x7f7c07a853b0
    [create_object]                  0x55e3191946c8           0x7f7c07a853b0
    [runtime lookup]                 0x55e3191946c8           0x7f7c07a853b0
    

    ce_flags confirm what the two entries are — hook time 0x441200 (ZEND_ACC_CACHED, not linked, not immutable = the lazy copy), live entry 0x441288 (ZEND_ACC_LINKED | ZEND_ACC_IMMUTABLE = the SHM inheritance-cache copy).

    Direct proof, from ReflectionClass::$objectHandlers after the run

    Dumping the private map plus std_object_handlers after $o->p = 42 (PHP 8.5.9, opcache on):

    block for ce=0x7f18b2de8cf8 -> handlers=0x557487425aa0  write_property=0xf5158d4cfa1e0ff3   <- our trampoline
    block for ce=0x557443f91be0 -> handlers=0x557487425aa0  write_property=0xf1894955fa1e0ff3   <- == std_object_handlers
    std handlers                                            write_property=0xf1894955fa1e0ff3
    

    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 new time 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

    • "The handlers block does not survive into shared memory." It survives untouched; nothing about it is persisted or copied in the first place. The failure is a lookup miss, not a lost allocation.
    • Clearing the opcache flags on the entry from inside the callback. Clearing ZEND_ACC_CACHED | ZEND_ACC_CACHEABLE | ZEND_ACC_IMMUTABLE on the entry the hook receives changes nothing — the cacheability decision is latched in a C local in zend_do_link_class() before the callback runs. Verified on both minors: the entry still moves.
    • The link path. include vs. 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 generated engine.h for both 8.4 and 8.5, and in stubs/zend-engine-structs.php). It is a plain pointer field, so the struct copy into the inheritance cache carries it, and zend_objects_new() reads it.

    I verified this end to end on both minors. Installing only setWritePropertyHandler() from the interface callback — no create_object at all — and stamping the allocated block into $ce->default_object_handlers:

    --- stamp=0 opcache=0 --- (no output)
    --- stamp=0 opcache=1 --- (no output)
    --- stamp=1 opcache=0 --- write_property FIRED
    --- stamp=1 opcache=1 --- write_property FIRED     <- survives the relocation
    

    So the shape of the fix in ReflectionClass::getObjectHandlers() is roughly: on a miss, before allocating, look at $classType->default_object_handlers and 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 from std_object_handlers, and publish it into the field.

    Three judgement calls belong to you, which is why I am not opening a patch PR:

    1. It changes a documented contract. Today "the create_object handler is required for all other handlers" — publishing the block makes setWritePropertyHandler() alone effective, and changes what obj->handlers points at for classes that previously had non-create_object handlers installed silently doing nothing.
    2. Classes whose defaults are not 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.
    3. Writing the field on an immutable entry. The direct-install path (repro5) operates on an entry with ce_flags=0x401288, i.e. ZEND_ACC_IMMUTABLE — the handler installers are the one mutation family that does not go through ensureWritableEntry() / copyOutOfSharedMemory(), so z-engine already writes create_object straight 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 keep rawStructure pointing at the temporary entry the engine discarded, so uninstall() / 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

    • Re-keying the map by class name. Fixes the reported symptom with a smaller blast radius, but it keeps the association in userland bookkeeping and needs a zend_string read inside an FFI callback; default_object_handlers is what the engine provides for this.
    • Intercepting zend_inheritance_cache_add (a ZEND_API extern function 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 to tools/generator/symbols.php and regenerating engine.h for 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.0 tags with ffi.enable=1 -d opcache.jit=off, varying only opcache.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_handlers route is the one you want, it belongs on the 8.4 branch first and cascades to master; the field and its stub exist identically on both lines, so the port should be textual.


    Generated by Claude Code

  3. lisachenko commented on Aug 19, 2026

    @lisachenko
    OwnerAuthor

    Decision (agreed with the maintainer)

    Route discussion concluded as C now + B follow-up:

    1. Now (lands with the opcache CI/bug-collection effort, 8.4 → cascade to master): a loud guard. Handler installation (setXxxHandler(), installExtensionHandlers()) on a class entry that is a lazy-linking temporary — ZEND_ACC_CACHED set, ZEND_ACC_LINKED clear, the only state an interface_gets_implemented hook ever observes under opcache — throws SharedMemoryException instead of silently installing handlers that die with the temporary. A new public ReflectionClass::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.

    2. Follow-up — feat(opcache): decline inheritance-cache publication for classes that receive handlers during linking #241: the actual fix. Intercept zend_inheritance_cache_add (hookable ZEND_API function 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.

    3. 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingopcacheIssue is related to opcache integration. Either doesn't work well or behaves incorrect.

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions