Repository navigation
fix: keep a PHP# change to a static List, Map or Set - #103
Conversation
A changing method on a static field was lost. `Log.events.add(event)`
on a `private static List<string> events` left the list empty, so
`Log::note("a"); Log::note("b"); var_dump(Log::seen());` printed
`array(0) {}`. The program ran and was wrong.
The receiver of a PHP# method call is marked so the VM makes a
Sharp\Collection that changes the array where it lives. Since 70bd2f3
only a property fetch carried the mark. A static property fell through to
the receiver cast, which keeps a slot only for a local, so the method
changed a copy and threw it away. Every changing method on every static
collection was lost: List add and set, Map delete, Set remove. Set add
and clear lower to plain PHP and kept working.
The static property fetch now carries the mark:
- The compiler marks the FETCH_STATIC_PROP_R of a PHP# receiver, as it
marks FETCH_OBJ_R
- The VM makes a Sharp\Collection that changes the static property
through its slot, which also holds for a parent's static reached
through a child
- A private(set) or protected(set) static the caller may not set keeps a
copy, and a change throws PHP's "Cannot modify private(set) property",
as the property receiver does through write_property
- Type inference sees the marked fetch may become an object, and both
JITs leave a marked fetch to the VM
Fixtures:
- static_collections.phpt fails on master in all 19 --passes modes and
passes on this branch. collection_methods.phpt covers every kind of
place but a static field, so nothing caught it
Zend/
├── zend_compile.c* <- marks a static property receiver
├── zend_compile.h* <- registers the mark on FETCH_STATIC_PROP_R
├── zend_vm_def.h* <- a marked static fetch makes a Sharp\Collection
├── zend_vm_execute.h* <- regenerated from zend_vm_def.h
├── Optimizer/
│ └── zend_inference.c* <- a marked static fetch may become an object
└── tests/sharp/
├── StaticCollections.sharp <- added, every changing method on static fields
└── static_collections.phpt <- added, each form as a row
ext/
├── opcache/jit/
│ ├── zend_jit.c* <- leaves a marked static fetch to the VM
│ └── zend_jit_trace.c* <- the same for traces
└── sharp/
├── php_sharp.h* <- sharp_collection_of_static_property
└── sharp.c* <- a static receiver changes its slot or throws
Both JITs left every marked static property fetch to the VM, so `Foo.bar.baz()` on an object held in a static field lost its inline fetch. The instance receiver keeps its fetch inline when the declared type of the property rules out an array, and the static receiver did not follow that rule. Both receivers now share one rule: - zend_jit_sharp_receiver_may_be_array checks a static property fetch as it checks a property fetch: the VM runs it only when the declared type may hold an array - zend_get_known_static_property_info finds the static property as zend_jit_fetch_static_prop found it, and that function now calls it - zend_jit_fetch_static_prop masks the mark off the cache slot, as the property fetch does Fixtures: - static_collections.phpt calls a method twice on an object held in a static field, beside the collection rows ext/opcache/jit/ ├── zend_jit.c* <- one receiver rule for both fetches ├── zend_jit_ir.c* <- finds the static property through the shared lookup, masks the mark └── zend_jit_trace.c* <- the same rule for traces Zend/tests/sharp/ ├── StaticCollections.sharp* <- an object in a static field └── static_collections.phpt* <- its row
|
Review verdict: CHANGES NEEDED Head reviewed: Change 1: the
|
| Form | Program | master prints | head prints |
|---|---|---|---|
add on a List |
Shelf.items = []; Shelf.items.add("a"); Shelf.items.add("b"); |
[] |
["a","b"] |
set on a List |
Shelf.items = ["a","b"]; Shelf.items.set(0, "z"); |
["a","b"] |
["z","b"] |
delete on a Map |
Shelf.stock = ["tea": 1, "pie": 2]; Shelf.stock.delete("tea"); |
{"tea":1,"pie":2} |
{"pie":2} |
remove on a Set |
add("old"); add("new"); Shelf.tags.remove("old"); |
["old","new"] |
["new"] |
| Parent's static through a child | Annex.shared.add("child") (shared declared in Shelf) |
[] |
["child"] |
| Parent's name inside the child | Shelf.shared.add("parent") in Annex |
[] |
["parent"] |
| Through a grandchild | Wing.shared.add("grandchild") |
[] |
["grandchild"] |
| From another class | Outside runs Shelf.items.add("outside") |
[] |
["outside"] |
protected(set) through a subclass |
SubLedger.lines.add("sub") |
not run | ["sub"] |
| Object in a static | Shelf.counter.bump() twice |
2 |
2 |
| Nullable object in a static | Shelf.counter?.bump() ?? -1, null then object |
[-1, 1] |
[-1, 1] |
Two forms from the task cannot be written in PHP# at the pinned Mago (625c278), so they cannot run:
- Through
static::: PHP# spells itSelf.lines.add(line). The checker refuses it witherror[semantics]: This expression is not supported yet in PHP#.The engine sends astatic::fetch to the same VM helper, because both JITs inline only a constant class,selforparent. - A static in a trait:
public class Journal : Keepswith a plain PHP traitKeepsis refused witherror[invalid-implement]: Class Journal cannot implement non-interface type Keeps. PHP copies a trait's static into the using class, soJournal.keptwould compile to the same constant-class fetch as the "From another class" row.
Plain PHP and PHP# sharing one static
Shelf.items is public, so plain PHP reads and writes it while PHP# changes it.
| Form | Program | master prints | head prints |
|---|---|---|---|
| Same array in another static | Shelf.items = ["one"]; Shelf.backup = Shelf.items; Shelf.items.add("two"); then [backup, items] |
[["one"],["one"]] |
[["one"],["one","two"]] |
| Same array in a local | const snapshot = Shelf.items; Shelf.items.add("two"); then [snapshot, items] |
[["one"],["one"]] |
[["one"],["one","two"]] |
| Plain PHP copies | Lib\Peek::$held = Shelf::$items; $local = Shelf::$items; then PHP# adds |
["one"], ["one"], [] |
["one"], ["one"], ["outside"] |
| Plain PHP reference | $ref = &Shelf::$items; then PHP# addTwice(), then var_dump($ref) |
[] |
["a","b"] |
| Plain PHP appends in the argument | Shelf.items.add(Peek.append()), and append() runs Shelf::$items[] = "appended" |
["one","appended"] |
["one","appended","x"] |
| Plain PHP replaces in the argument | Shelf.items.add(Peek.replace()), and replace() runs Shelf::$items = ["replaced"] |
["replaced"] |
["replaced","x"] |
Copy-on-write holds: the second static and the local keep their old array. The last two rows match the instance receiver, which also changes the slot after its arguments run.
Adds stay in place, with no copy per call. 50,000 adds take 6.4 ms, 100,000 take 11.4 ms, and 200,000 take 22.7 ms under the tracing JIT (Demo\Log::note in a loop).
Probe fixture, harness and test
Zend/tests/sharp/ReviewProbe.sharp:
namespace Probe;
import Lib.Peek;
public class Shelf
{
public static List<string> items { get; set; } = [];
public static List<string> backup { get; set; } = [];
protected static List<string> shared = [];
private static Map<string, int> stock = [:];
private static Set<string> tags = [];
private static Counter? counter = null;
public static List<string> addTwice() { Shelf.items = []; Shelf.items.add("a"); Shelf.items.add("b"); return Shelf.items; }
public static List<string> setFirst() { Shelf.items = ["a", "b"]; Shelf.items.set(0, "z"); return Shelf.items; }
public static Map<string, int> deleteKey() { Shelf.stock = ["tea": 1, "pie": 2]; Shelf.stock.delete("tea"); return Shelf.stock; }
public static List<string> removeTag() { Shelf.tags = []; Shelf.tags.add("old"); Shelf.tags.add("new"); Shelf.tags.remove("old"); return Shelf.tags.toList(); }
public static List<List<string>> sharedWithStatic() { Shelf.items = ["one"]; Shelf.backup = Shelf.items; Shelf.items.add("two"); return [Shelf.backup, Shelf.items]; }
public static List<List<string>> sharedWithLocal() { Shelf.items = ["one"]; const snapshot = Shelf.items; Shelf.items.add("two"); return [snapshot, Shelf.items]; }
public static List<string> appendDuringArgument() { Shelf.items = ["one"]; Shelf.items.add(Peek.append()); return Shelf.items; }
public static List<string> replaceDuringArgument() { Shelf.items = ["one"]; Shelf.items.add(Peek.replace()); return Shelf.items; }
public static List<string> sharedView() => Shelf.shared;
public static int countTwice() { Shelf.counter = new Counter(); Shelf.counter.bump(); return Shelf.counter.bump(); }
public static int countMaybe(bool make) { Shelf.counter = make ? new Counter() : null; return Shelf.counter?.bump() ?? -1; }
}
public class Annex : Shelf
{
public static List<string> putThroughChild() { Annex.shared = []; Annex.shared.add("child"); return Shelf.sharedView(); }
public static List<string> putThroughParent() { Shelf.shared = []; Shelf.shared.add("parent"); return Annex.sharedView(); }
}
public class Wing : Annex
{
public static List<string> putThroughGrandchild() { Wing.shared = []; Wing.shared.add("grandchild"); return Shelf.sharedView(); }
}
public class Ledger { public static List<string> lines { get; protected set; } = []; }
public class SubLedger : Ledger
{
public static List<string> write(string line) { SubLedger.lines = []; SubLedger.lines.add(line); return Ledger.lines; }
}
public class Outside
{
public static List<string> addFromOutside() { Shelf.items = []; Shelf.items.add("outside"); return Shelf.items; }
}
public class Counter
{
public int ticks { get; private set; } = 0;
public int bump() { this.ticks += 1; return this.ticks; }
}
Zend/tests/sharp/harness/ReviewProbe.inc:
<?php declare(strict_types=1);
namespace Lib;
final class Peek
{
/** @var list<string> */
public static array $held = [];
public static function append(): string { \Probe\Shelf::$items[] = "appended"; return "x"; }
public static function replace(): string { \Probe\Shelf::$items = ["replaced"]; return "x"; }
}Zend/tests/sharp/review_probes.phpt runs every row 3 times and prints the last round, as static_collections.phpt does:
for ($round = 0; $round < 3; $round++) {
ob_start();
echo "add\n"; attempt(fn () => Probe\Shelf::addTwice());
echo "set\n"; attempt(fn () => Probe\Shelf::setFirst());
echo "delete\n"; attempt(fn () => Probe\Shelf::deleteKey());
echo "remove\n"; attempt(fn () => Probe\Shelf::removeTag());
echo "child\n"; attempt(fn () => Probe\Annex::putThroughChild());
echo "parent name in child\n"; attempt(fn () => Probe\Annex::putThroughParent());
echo "grandchild\n"; attempt(fn () => Probe\Wing::putThroughGrandchild());
echo "other class\n"; attempt(fn () => Probe\Outside::addFromOutside());
echo "shared with static\n"; attempt(fn () => Probe\Shelf::sharedWithStatic());
echo "shared with local\n"; attempt(fn () => Probe\Shelf::sharedWithLocal());
echo "plain PHP copy\n";
Probe\Shelf::$items = ["one"];
Lib\Peek::$held = Probe\Shelf::$items;
$local = Probe\Shelf::$items;
Probe\Outside::addFromOutside();
var_dump(Lib\Peek::$held, $local, Probe\Shelf::$items);
echo "plain PHP reference\n";
$ref = &Probe\Shelf::$items;
$ref = ["one"];
Probe\Shelf::addTwice();
var_dump($ref);
unset($ref);
echo "plain PHP appends during the argument\n"; attempt(fn () => Probe\Shelf::appendDuringArgument());
echo "plain PHP replaces during the argument\n"; attempt(fn () => Probe\Shelf::replaceDuringArgument());
echo "protected(set) through a subclass\n"; attempt(fn () => Probe\SubLedger::write("sub"));
echo "object\n"; attempt(fn () => Probe\Shelf::countTwice());
echo "nullable object\n"; attempt(fn () => [Probe\Shelf::countMaybe(false), Probe\Shelf::countMaybe(true)]);
$output = ob_get_clean();
}
echo $output;2. Memory and refcounts
The suite has no ASan or valgrind runner of its own. So I used upstream's run-tests.php --asan precedent, which sets USE_ZEND_ALLOC=0, on a separate --enable-debug --enable-address-sanitizer build of head. Valgrind does not run on macOS, and Apple's ASan has no leak checker, so I checked leaks with macOS leaks on the system allocator.
ASan runs static_collections.phpt, review_probes.phpt, collection_methods.phpt and static_members.phpt. All 4 pass in each mode, with no ASan report:
- No opcache:
php run-tests.php --asan -d opcache.jit=disable …: 4 of 4 passed. - Opcache shared memory, each test twice:
--asan -d opcache.enable_cli=1 --repeat 2: 4 of 4 passed. - Tracing JIT, hot thresholds 1: 4 of 4 passed.
- Function JIT, hot thresholds 1: 4 of 4 passed.
leaks ran a script with every row of static_collections.phpt and every probe row, 3 rounds each. It included the shared-static, shared-local, plain PHP reference and private(set) error rows:
USE_ZEND_ALLOC=0 MallocStackLogging=1 leaks --atExit -- php -n leakprobe.php
Process 25633: 0 leaks for 0 total leaked bytes. (no opcache)
Process 25841: 0 leaks for 0 total leaked bytes. (tracing JIT)
Process 26422: 0 leaks for 0 total leaked bytes. (function JIT)
To confirm leaks catches a leak here, I ran php -n -r 'zend_leak_bytes(100);'. It printed 1 leak for 112 total leaked bytes.
The debug build's own leak report is also clean: the whole suite passes 173 of 173 in all 22 modes, and run-tests fails a test on any LEAK.
3. Plain PHP is unchanged
A .php file compiles to the same opcodes. It has self::, static:: and parent:: fetches, (object) self::$items casts, and Base::$next?->grow(). I dumped its opcodes before and after the optimizer (opcache.opt_debug_level=0x30000) on master and head, with its output: diff -s plain-master.txt plain-head.txt printed Files … are identical.
The tracing JIT compiles the same code for a hot loop of self::$x reads. I dumped the final IR (opcache.jit_debug=0x02000000) for $s += self::$x and $s += count(self::$list) loops. The diff of master and head shows only absolute addresses (uintptr_t c_4 = 0x1029cf0b8 and 0x1069470b8), with the same 320 lines.
| 20,000,000 iterations, best of 5, tracing JIT | master | head |
|---|---|---|
$s += self::$x |
18.9 ms | 18.7 ms |
$s += count(self::$list) |
26.1 ms | 25.5 ms |
The VM, with opcache and no JIT, adds one bit test per FETCH_STATIC_PROP_R. At 2,000,000 iterations it is within noise: self::$x took 42.0 ms on master and 42.7 ms on head, and count(self::$list) took 53.4 ms on master and 51.6 ms on head. Both are debug builds.
sharp/bin/test --upstream --opcache matches sharp/baseline/darwin, with 0 failures in all three runs.
4. The JIT rule is one rule
zend_jit_sharp_receiver_may_be_array is the only check. Four call sites use it: the function JIT and the tracing JIT, each for FETCH_OBJ_R and for FETCH_STATIC_PROP_R. The static case finds the property through zend_get_known_static_property_info. zend_jit_fetch_static_prop now calls the same function.
The moved lookup does the same thing as the old inline code. It is not byte-for-byte the same, because of two edits: the prop_name local is gone, and known_prop_info = prop_info became return prop_info.
- zend_string *prop_name;
-
ZEND_ASSERT(Z_TYPE_P(zv) == IS_STRING);
- prop_name = Z_STR_P(zv);
- zv = zend_hash_find(&ce->properties_info, prop_name);
+ zv = zend_hash_find(&ce->properties_info, Z_STR_P(zv));
…
- known_prop_info = prop_info;
+ return prop_info;Under the function JIT, Archive.ticker stays in the VM. With the mask removed, 200 calls of tickTwice() under opcache.jit=function printed int(400) and never reached the inline fetch. The tracing JIT inlines it, as the PR body says.
5. Tests
static_collections.phpt keeps the forms as rows of one file, and 9 of its 11 rows fail on master. The other two are contrast rows by design: the instance field keep and the object tickTwice.
For each fix line, I removed only that line, rebuilt, and ran the test:
| Fix line removed | Rows that fail |
|---|---|
zend_compile_sharp_receiver marks ZEND_AST_STATIC_PROP (that is master) |
Log add, retitle set, sell delete, tag remove, Branch::stack, show, Patron::count, the private(set) lambda, Archive::$shown: 9 rows |
zend_vm_def.h: the helper masks ZEND_SHARP_OPERATOR off the cache slot |
every row (the program crashes with empty output) |
sharp_collection_of_static_property: the private(set) access check |
the lambda row prints NULL, and Archive::$shown gains "verse" |
sharp_collection_write_back: the static private(set) throw |
the lambda row prints NULL |
zend_inference.c: a marked static fetch may become an object |
tracing JIT: Assertion failed: (info & (1 << type)), function zend_jit_trace_type_to_info_ex |
zend_jit.c and zend_jit_trace.c: the static receiver rule |
tracing JIT: Call to a member function add() on array. Function JIT: Termsig=11 |
zend_jit_ir.c: the inline fetch masks the mark off the cache slot |
none: this is Change 1 |
The suite on head passes 173 of 173 in all 22 modes, with --census and --differential clean. The 173 include my probe test.
The row for an object in a static field called `tickTwice()` once per round, so the tracing JIT never ran the fetch it compiled inline. With `|ZEND_SHARP_OPERATOR` removed from `zend_jit_fetch_static_prop`'s cache slot, the inline fetch reads the run-time cache 1 GiB past its slot and crashes, yet the row still passed in all 22 modes. Nothing checked that a change copies an array another static or a local shares, or that it reaches a plain PHP reference to the static. The row now loops, and three rows guard sharing: - `tickTwice()` runs 3 times in a loop and expects int(6). With the mask removed, the tracing JIT run dies with Termsig=11, and the other 21 modes pass - A change to a static List leaves the array another static shares as it was - A change to a static List leaves the array a local shares as it was - A PHP# add reaches `$ref = &Demo\Archive::$shelf` in plain PHP Zend/tests/sharp/ ├── StaticCollections.sharp* <- the two sharing methods and a public static for the reference └── static_collections.phpt* <- the loop and the three sharing rows
… to Mago c314bab Problem: PR #102 must be up to date with master. Master gained #103, which keeps a PHP# change to a static List, Map or Set. It also gained #104 and #105, which make the spec guard fail only when an example joins sharp/baseline/spec, and make the list name only the examples that fail. Mago #152 merged its own master and moved to c314bab. Solution: merge master. Git merged every file on its own, the generated Zend/zend_vm_execute.h included. zend_vm_gen.php regenerates the same VM files from the merged zend_vm_def.h. #103 marks ZEND_FETCH_STATIC_PROP_R with ZEND_SHARP_OPERATOR in extended_value, and this branch's ZEND_SHARP_VERIFY_TYPE_ARGS keeps its own flag on its own opcode. The pin moves to Mago c314bab. Only SHARP_MAGO_COMMIT changes in ext/sharp/sharp_unit.h, and SHARP_UNIT_ABI stays the same. method-declarations, generic-method-inference, self-on-type-parameters and index-rules now pass and leave sharp/baseline/spec. sharp/bin/test passes 199 of 199 tests without opcache, in both file cache modes, twice in one process, under each of the 16 optimizer passes alone, and under the tracing and function JITs. The census and sharp/bin/test --spec pass. . ├── Zend/ master's static receiver beside this branch's checks ├── ext/opcache/jit/ master's inline static object under the JIT ├── ext/sharp/ │ ├── php_sharp.h, sharp.c master's sharp_collection_of_static_property │ └── sharp_unit.h pinned to Mago c314bab ├── sharp/baseline/spec four examples that now pass leave the list └── sharp/bin/spec, docs/ master's guard and its documents
Problem
A changing method on a static collection field was silently lost on the engine. With
private static List<string> events = [];andLog.events.add(event);, the programLog::note("a"); Log::note("b"); var_dump(Log::seen());printedarray(0) {}.The receiver of a PHP# method call is marked so the VM makes a
Sharp\Collectionthat changes the array where it lives. Since 70bd2f3,zend_compile_sharp_receivermarked onlyZEND_AST_PROPandZEND_AST_NULLSAFE_PROP. AZEND_AST_STATIC_PROPreceiver fell through toCAST (object), whose handler keeps a slot only for a CV. Sosharp_collection_of_valuecopied the array, the method changed the copy, andsharp_collection_write_backreturned becausecollection->propertywas NULL.Opcodes for
Log.events.add(event)on master:Solution
The static property fetch now carries
ZEND_SHARP_OPERATOR, asFETCH_OBJ_Rdoes:zend_fetch_static_prop_helperturns a marked array into aSharp\Collectionthrough the newsharp_collection_of_static_property, which changes the static property through its slot.private(set)orprotected(set)static the caller may not set keeps a copy, and a change throws PHP's ownCannot modify private(set) propertyerror, as the instance receiver does throughwrite_property. PHP refuses hooks and readonly on static properties, so these are the only static properties the caller may not change in place.zend_jit_sharp_receiver_may_be_arrayleaves the fetch to the VM only when the declared type may hold an array. An object in a static field, as inFoo.bar.baz(), keeps its inline fetch.zend_get_known_static_property_infois the lookupzend_jit_fetch_static_propused inline, now shared, and the inline fetch masks the mark off the cache slot.Observed with a breakpoint on
zend_jit_fetch_static_propunder the tracing JIT, runningArchive::tickTwice()(Archive.ticker.tick()on aprivate static Ticker? ticker) andLog::note():Every form
Log.events.addon a static ListArchive.titles.set(0, …)on a static ListArchive.stock.delete(…)on a static MapArchive.tags.remove(…)on a static SetArchive.tags.add/.clear()on a static SetBranch.shared.addon a parent's static through a childArchive.shown.addon a{ get; private set; }static, in its classPatronreadsArchive.shown.count()showncallsaddError: Cannot modify private(set) propertythis.own.addon an instance field (contrast)Archive.tickTwice()3 times in a loop, on an object in a static field["one"](the add is lost)["one"], the List is["one","two"]["one"](the add is lost)["one"], the List is["one","two"]$ref = &Demo\Archive::$shelf, then PHP#Archive.shelf.add("two")$refstays["one"]$refis["one","two"]Not testable at the pinned Mago (625c278):
Self.events.add: the checker refusesSelf.events("This expression is not supported yet in PHP#"). It accepts onlySelf.method(...).setandremove: aMaphas no such methods yet ("Methodsetdoes not exist onMap<string, int>").deleteis the Map's changing method, and it is covered.sethook: PHP refuses it at compile time with "Cannot declare hooks for static property".Why no test caught it
collection_methods.phpt(withCollectionMethods.sharp) is the suite meant to cover "every method on every kind of place". It covered locals, parameters, instance properties, hooked properties and values, but no static field.static_members.phptcovers static fields, but only assignment,++,+=and??=, with no collection method.opcodes.phptcould not catch it either, because a twin spells a receiver as((object) $x), which matches the buggy cast.static_collections.phptis now the static-place counterpart, with one row per form. It fails on master in all 19--passesmodes and passes on this branch in all 19.Each fix line, removed
The reviewer removed one fix line at a time, rebuilt, and ran
static_collections.phpt. The first row is the master run, because master has none of the fix.Logadd,retitleset,selldelete,tagremove,Branch::stack,show,Patron::count, the private(set) lambda,Archive::$shown: 9 rowszend_vm_def.h: the helper masksZEND_SHARP_OPERATORoff the cache slotsharp_collection_of_static_property: the private(set) access checkNULL, andArchive::$showngains"verse"sharp_collection_write_back: the static private(set) throwNULLzend_inference.c: a marked static fetch may become an objectAssertion failed: (info & (1 << type)), function zend_jit_trace_type_to_info_exzend_jit.candzend_jit_trace.c: the static receiver ruleCall to a member function add() on array. Function JIT:Termsig=11zend_jit_ir.c: the inline fetch masks the mark off the cache slottickTwiceloop row, under the tracing JIT (below)The last line needed a stronger row. One call per round never ran the compiled inline fetch, so the row passed with the mask removed. The row now calls
tickTwice()3 times in a loop:Verification
sharp/bin/test --opcache --repeat --passes --census --differential: 172 of 172 in every mode, the census is clean, and every fixture compiles underphp -l.sharp/bin/test --upstream --opcache: 0 failures. The results matchsharp/baseline/darwin.Files