zend-memory
Skill855 starsChanged 10 days agoApache-2.0View on GitHub
Use when changing or reviewing code that owns, borrows or frees PHP memory in ext-php-rs (Zval, ZBox/ZBoxable, ZendStr, ZendHashTable, ZendObject, ZendClassObject, refcounts, shallow_clone, persistent vs request memory, IntoZval/FromZval), the Rust value of a #[php_class] (borrow cells, ClassRef/ClassRefMut, payloads), the cycle collector (GcTrace, get_gc), MINIT tables, or when debugging a segfault, use-after-free, double free or leak, including ASan, LSan, valgrind and debug-PHP runs, a crash only CI shows, PHP output handlers, or memory-checking a downstream extension against a branch.
In this repository6 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- php-bindingsSkill
- pr-descriptionSkill
- proc-macrosSkill
- semver-breaking-changesSkill
The file
We split this skill into the rules it gives an agent
1 rule. About 0 are common, 0 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 39
When the engine takes a value, the Rust side must not drop it: mem::forget, ManuallyDrop, or ZBox::into_raw.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Zend memory, ownership and the cycle collector
Where things live
src/types/zval.rs:Zval. Dropping aZvalreleases what it holds (change_type→ null first, then the release, aszend_assign_to_variabledoes: the release can run a destructor or a GC run that walks this very slot).shallow_clonecopies the value and bumps the refcount.src/boxed.rs:ZBox<T>, an owning pointer released throughZBoxable::free(ext_php_rs_zend_string_releaseforZendStr,zend_array_destroyforZendHashTableexcept immutable arrays,ext_php_rs_zend_object_releasefor objects; theext_php_rs_*helpers wrap Zend macros insrc/wrapper.c).ZBox::into_rawhands ownership to C;ZBox::from_rawtakes it back.src/types/string/,src/types/array/,src/types/object.rs,src/types/class_object.rs:ZendStr,ZendHashTable,ZendObject,ZendClassObject<T>(azend_objectwith the Rust value in front of it).src/types/payload.rs: the borrow cell around a class's Rust value,ClassRef/ClassRefMut,BorrowError(thrown to PHP asError).src/gc.rs:GcRoots,GcTrace;#[php_class]reports each field whose type implementsGcTracefrom the class'sget_gchandler.src/types/separated.rs,src/types/php_ref.rs: by-value mutation (COW separation) and by-reference parameters.src/alloc.rs:emalloc/efreewrappers.- Guide:
guide/src/types/zval_ownership.md,guide/src/advanced/minit_memory.md,guide/src/macros/classes.md("Access to the Rust Value", "PHP Values in Rust Fields"),guide/src/migration-guides/v0.17.md.
Ownership rules to check in every change
- Know who owns each pointer. For every
*mut zend_*that crosses the FFI boundary, write down whether the engine borrows it, takes it (no refcount bump:ZVAL_COPY_VALUE,zend_declare_class_constant,zend_enum_add_case,zend_hash_updatewith a value), or copies it (ZVAL_COPY,zend_string_copy). When the engine takes a value, the Rust side must not drop it:mem::forget,ManuallyDrop, orZBox::into_raw. - Refcounted vs not. Interned strings, immutable arrays and scalars have no
refcount to bump (
Z_REFCOUNTED,GC_FLAGS & GC_IMMUTABLE). Code that incrementsgc.refcountmust check theRefCountedtype flag first, asshallow_clonedoes. - Persistent vs request memory. Anything that outlives the request (MINIT tables,
module globals, class constants of internal classes, persistent strings) must be
allocated persistently (
pemalloc(…, 1),zend_string_init(…, 1)) and freed with the persistent deallocator. Request memory is freed at request end by ZendMM even if Rust still points at it.ZendStrrelease honoursIS_STR_PERSISTENT. - Release can run PHP. Dropping a
Zval, aZBox<ZendObject>or a hash table can call a destructor, which can call back into the extension and reach the same object. Never release while holding a&mutinto memory the destructor can reach, or while aClassRefMutof that object is alive. Move the value out first. - Hashtable iteration. A callback during iteration can modify the table. Don't
keep a
&Zvalinto a bucket across a call to PHP; buckets move on resize. - Separation. Writing to an array or string that the caller also holds needs
separation first (
SEPARATE_ARRAY,Zval::array_mut, also reached throughSeparated), otherwise the caller's value changes. - Bailouts. A PHP fatal error longjmps over Rust frames, and their destructors
never run (
.lsan-suppressions.txtlists the tests that do this on purpose). Code that calls PHP and owns Rust values goes throughtry_catch/BailoutGuard(src/zend/try_catch.rs,src/zend/bailout_guard.rs, guideadvanced/bailout_guard.md). - MINIT tables are owned for the life of the process by a per-extension static;
method tables are freed right after registration (guide
advanced/minit_memory.md). A&'static ClassEntryis valid only until module shutdown: a SAPI that restarts the module (FrankenPHP) frees and recreates every class entry, so never cache one across MINIT (same guide, "Module restarts").
The Rust value of a class
- The Rust value of a
#[php_class]object lives in a borrow cell. Generated wrappers borrow it for the whole call:&selftakes a shared borrow,&mut selfan exclusive one. A PHP call from a method that reaches the same object again gets aBorrowError(PHPError), not a second&mut. - An object of a PHP subclass that never calls
parent::__construct()has no Rust value:BorrowError::Uninitialized. Every path that reads the value (methods, property handlers,get_gc,clone,var_dump, comparison) must handle it. - Property handlers,
get_gc,clone_objandfree_objrun from the engine at any time, including while a method holds the value mutably. They must not panic or double-borrow; the collector does not read a value that is mutably borrowed.
Output handlers (src/zend/output.rs)
- A running handler's input (
context->in) is its own buffer. Output written from the callback appends to it and canereallocit, so detach the buffer for the call. - A non-write
ob_*call inside a handler reachesphp_output_lock_error, which runsphp_output_deactivate()(frees every handler) beforeE_ERROR. If the callback catches that bailout, the trampoline must not touch the handler and must re-raise. context->outmust be engine-owned (free = 1) when the handler returns:php_output_header()runs theheader_register_callback()function beforeub_write, and its output re-enters the same handler. In Embed, clearheaders_sentandrequest_info.no_headersthroughSapiGlobals::get_mut()to reach that path.
The cycle collector
- A cycle is collected only if every object in it reports the values it holds.
A field that keeps a PHP value must be of a
GcTracetype (see the list in the guide), or the cycle leaks. - A new container or wrapper type that can hold PHP values needs a
GcTraceimpl, and a test that builds a cycle through it,unsets it, callsgc_collect_cycles()and checks the count it returns or a destructor that ran. get_gcmust report each value once, and must not allocate per call beyond the engine's GC buffer.
Tests for memory bugs
- A test for a use-after-free or double free must fail on the base under a detector (ASan, debug PHP, valgrind), not only "by luck". Say which one in the test's comment if it doesn't crash without it.
- Refcounts:
debug_zval_dump()in the PHP script shows them; assert on the output throughrun_php_capturing_stderror by comparingob_get_clean()in PHP. - Leaks: a debug PHP reports request leaks on stderr at shutdown
(
[Fri …] Script: '…'/=== Total N memory leaks detected ===);run_phpdoes not fail on them, so assert stderr is clean.
Detectors
- Debug PHP (
--enable-debug): Zend assertions and the leak report. CI'ssetup-phpusesdebug: true. Linux:nix develop .#debug/.#zts-debug/.#php86-debug. USE_ZEND_ALLOC=0: ZendMM hands out chunks from its own arenas, so ASan and valgrind can't see request-memory errors without it. Set it for every detector run.ASan, as CI runs it (job "Test with ASan", Linux, nightly):
RUSTFLAGS="-Zsanitizer=address -Clink-arg=-Wl,-undefined,dynamic_lookup" \ USE_ZEND_ALLOC=0 USE_TRACKED_ALLOC=1 \ LSAN_OPTIONS=suppressions=$PWD/.lsan-suppressions.txt \ cargo +nightly test -Zbuild-std --target x86_64-unknown-linux-gnu \ -p ext-php-rs --lib --test module_tests --features embed,closure,anyhow,observernix develop .#asansets these variables and provides an ASan-instrumented debug PHP with embed. This job covers the library's unit tests andmodule_tests, not class, enum or INI registration (MINIT can't run inside Embed's request): for those, load the extension into that ASan PHP as a cdylib:RUSTFLAGS="-Zsanitizer=address -Zexternal-clangrt -Clink-arg=-Wl,--allow-shlib-undefined" \ cargo build -Zbuild-std --target x86_64-unknown-linux-gnu -p tests ZEND_DONT_UNLOAD_MODULES=1 php -d extension=target/x86_64-unknown-linux-gnu/debug/libtests.so script.php-Zexternal-clangrtleaves__asan_*undefined in the.so, and the instrumentedphpprovides them. WithoutZEND_DONT_UNLOAD_MODULES=1, PHP unloads the.sobefore the leak check and every frame shows<unknown module>.ASAN_OPTIONS=fast_unwind_on_malloc=0:malloc_context_size=30gives full stacks. To tell a per-call leak from a one-time one, run the script with two iteration counts and compare.- LSan suppressions are only for leaks that are by design (PHP's own persistent allocations at embed shutdown, tests that bail out on purpose). A real leak is fixed, never suppressed.
- A crash only in CI's embed job: the runner's PHP loads its preinstalled PECL
extensions (xdebug with observers, apcu, redis, …) into the embed SAPI, and the nix
shells load none. Reproduce in
docker run ubuntu:26.04with the sury repository,php8.5-cli php8.5-dev libphp8.5-embed php8.5-xdebugand CI's test command, then gdb. Locally, anFcallObserverthat observes every call, in the.#asanlane, shows the same class of bug. - A downstream extension against a branch: the
.#asanPHP has core only (no dom or tokenizer), so Pest can't run there. Run PHPT or plain scripts under ASan, and Pest under.#debug. From another repository, setLSAN_OPTIONSwith the absolute path of.lsan-suppressions.txt. Valgrind on the nix PHP needs--trace-children=yes(thephpbinary is a wrapper) and-d pcre.jit=0(PCRE JIT code floods the report). Run the base branch the same way before you blame the change: timing-sensitive tests fail under valgrind there too. - macOS: ASan works for Rust code (
-Zsanitizer=addresson nightly), but there is no instrumented PHP and no nix shell; run the detector jobs on Linux or rely on CI.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

