Skip to content

Fix GH-15869: Stack overflow when destroying deeply nested arrays or objects - #25969

Open
Guikingone wants to merge 1 commit into
php:masterfrom
Guikingone:fix/gh-15869-deep-destruction
Open

Guikingone wants to merge 1 commit into
php:masterfrom
Guikingone:fix/gh-15869-deep-destruction

Conversation

@Guikingone

Copy link
Copy Markdown

Fixes GH-15869.

The bug

Destroying an array or an object destroys its children from inside the same call, one native stack frame group per nesting level. A structure that is nested deeply enough overflows the native stack and the process crashes with SIGSEGV when the last reference is dropped. A singly linked list is enough, no crafted data is needed:

class Node { public $next = null; }
$head = null;
for ($i = 0; $i < 100000; $i++) {
    $n = new Node();
    $n->next = $head;
    $head = $n;
}
unset($n);
$head = null; // SIGSEGV

The same happens with $a = [$a] in a loop and then $a = null. zend.max_allowed_stack_size does not help: comparison, compilation and function calls check it, destruction does not.

The change

zend_array_destroy() and zend_objects_store_del() compare the native stack position with EG(stack_limit) plus a margin (ZEND_GARBAGE_STACK_MARGIN, 128 KiB). With room to spare nothing changes. Within the margin the value is not destroyed but pushed on a list of deferred garbage (EG(deferred_garbage)), and zend_defer_garbage() destroys the values on that list in a loop. Values that become deferred while the loop runs are added to the same list, so the rest of the structure is released at a constant stack depth.

  • A deferred object holds one reference, like an object whose destructor is running. It can be resurrected by its destructor, and the destructor and the free handler run once.
  • For a list released from its head the destructors still run from head to tail. Siblings that are all deferred are destroyed in reverse order; destruction order of siblings is not guaranteed by PHP, and it only differs once the stack is nearly exhausted.
  • Destroying a value can call destructors, which run user code in frames of their own. A value released from such a frame starts a loop of its own (the list remembers EG(current_execute_data) of the frame that is draining it). Without this, unbounded recursion through destructors (for example a destructor that does new Foo) would no longer reach the stack limit but would loop forever at a constant depth: the existing stack_limit_001, 002, 003, 006 and gh16041_001 tests catch that. It also lets a destructor release another deep structure.
    This is new compared with the prototype posted on the issue, which had that defect. The Zend/tests run I reported there was made without --enable-zend-test, so these tests were skipped and I did not see it.
  • Per-request state is reset in init_executor() and shutdown_executor(), and the draining flag in _zend_bailout(), because a fatal error in a destructor leaves the loop through longjmp. Without the reset a process that serves several requests (php-fpm, CLI server) keeps a dangling list pointer: with the reset removed, the second request after such a fatal error corrupted the heap on the CLI server (zend_mm_heap corrupted).
  • zend_array_destroy_now() and zend_objects_store_del_now() are the destruction bodies without the check. They are only needed by zend_defer_garbage() in another translation unit, so they are declared in zend_variables.h next to it, without ZEND_API, and only exist where ZEND_CHECK_STACK_LIMIT is defined. The public functions keep their signatures and symbols (JIT calls them as before).
  • Where the stack limit is not supported nothing is compiled in. With zend.max_allowed_stack_size=-1 EG(stack_limit) is 0, the check is never true, and the behaviour is the one before this change (the crash stays possible, as it was).

UPGRADING.INTERNALS has a note: zend_array_destroy() and zend_objects_store_del() can return before the array or object is destroyed, when the stack is nearly exhausted.

What changes for users

Nothing until the stack is within 128 KiB of the limit. Past that point, structures that used to crash are released.

Cost

Measured on the prototype of this change (against 930dacc), release build, instructions executed under callgrind:

Script Unpatched Patched Diff
Zend/bench.php 3,841,001,532 3,841,006,156 +0.000%
300,000 iterations that each create and destroy a nested array and two objects 1,364,865,608 1,377,465,733 +0.92%

Measured again on the final version against current master (2536fb681df, aarch64 Linux, GCC 13, -O2, --disable-all --enable-cli --enable-zend-test):

Script Unpatched Patched Diff
Zend/bench.php 3,841,843,891 3,841,857,381 +0.0004%
same destruction loop 1,365,704,850 1,378,313,851 +0.92%

That is about 4 instructions per array or object destruction (one stack comparison, no memory access beyond EG()). The second script is a worst case built for this path. Both measurements are NTS; the cost on ZTS, where EG() goes through the thread-local lookup, was not measured. I have no application benchmarks (WordPress, Symfony).

Tests

Zend/tests/stack_limit/gh15869_001.phpt to 013.phpt. All use a reduced zend.max_allowed_stack_size (1M) and are skipped where the stack limit is not supported. All of them crash with SIGSEGV on unpatched master.

Test What it checks
001 deeply nested array released (also with references and string keys); memory is back to the baseline
002 deep linked list of objects released; memory is back to the baseline
003 destructors of a list released from its head run in head to tail order
004 exceptions thrown by destructors of deferred objects propagate (and chain), all destructors still run
005 an object resurrected by its destructor while deferred (tail, and a node in the middle with the rest of the list)
006 arrays and objects mixed in one deep structure
007 two independent deep branches, one behind an array, one under an object
008 garbage cycles collected next to a deep live list, with the list as possible roots, and gc_collect_cycles() called from a destructor during the release
009 releases inside a Fiber (fiber.stack_size)
010 fatal error in a deferred destructor: the shutdown function can still release deep structures
011 exit() in a deferred destructor: same
012 a destructor that runs during the release itself releases a deep structure
013 a Fiber suspended by a destructor during the release; another release runs meanwhile

The existing Zend/tests/stack_limit/ tests that rely on unbounded destructor recursion hitting the limit pass.

Known limits

  • zend.max_allowed_stack_size=-1 disables the mechanism, as it disables every other stack check.
  • The destructors of deferred objects, and the free handlers of internal classes, run with the margin as their stack budget. A destructor that needs more than that gets the usual "Maximum call stack size reached" Error.
  • If zend.max_allowed_stack_size is so small that the margin plus zend.reserved_stack_size is more than the whole stack (seen with 128K and below on this build; 192K was not affected), every destruction is deferred and runs in the frame that requested it. This is correct, but siblings are destroyed in reverse order: [new A(1), new A(2)] destroys 2 then 1. Destructors that call functions still work.
  • Not guarded: zend_hash_destroy() and zend_hash_clean() called by engine or extension code on a table of their own are not entry points of the check, but every value they hold is released through zval_ptr_dtor(), so the next nesting level is checked. Internal objects whose free_obj handler walks its own structure recursively without going through zval_ptr_dtor() are not covered. The GC frees garbage without recursion and was not changed.
  • The queue and the draining state are shared by the whole executor, not kept per Fiber. A Fiber that is suspended by a destructor while it drains the queue leaves the entries it did not reach in the queue until it is resumed; releases that happen meanwhile in other Fibers drain their own entries only. If the Fiber is never resumed, those entries are released with the request. Test 013 covers the suspended case. A per-Fiber state can follow Delaying destructors and GC #20001, as discussed on the issue.

What was tested

  • Debug builds (--enable-debug --enable-zend-test --disable-all --enable-cli), NTS and ZTS, and a debug NTS build with --enable-address-sanitizer --enable-undefined-sanitizer (GCC 13), all on aarch64 Linux in Docker. Zend/tests: 5774 tests, 67 skipped, 0 failed with the patch on NTS and ZTS; the unpatched build passes the same tests and fails the 13 new ones. In the ASAN run, 13 tests failed (oom_unserialize_*, new_oom, gh23088, gc/gh9993, runtime_compile_time_binary_operands); run again with the default memory_limit, 13 of them fail on an unpatched ASAN build and 12 on the patched one. The new tests pass under ASAN.
  • The CLI server with several requests in a row, one of them ending with a fatal error inside a deferred destructor.
  • Not tested: Windows and macOS (read for MSVC problems only: both new declarations match their definitions, including ZEND_FASTCALL; no new public symbol), 32-bit platforms, extensions other than zend_test, opcache with the JIT enabled (the JIT reaches both functions through the same exported symbols), other allocators than the Zend MM.

…or objects

Destroying an array or an object destroys its children from inside the same
call, so a deeply nested structure, such as a long linked list, overflows the
native stack when its last reference is dropped.

zend_array_destroy() and zend_objects_store_del() now compare the stack
position with EG(stack_limit) plus ZEND_GARBAGE_STACK_MARGIN. Near the limit
the value is queued in EG(deferred_garbage) instead of being destroyed, and
zend_defer_garbage() destroys the queue in a loop. Values deferred while the
loop runs join the queue, so the rest of the structure is released at a
constant stack depth. A deferred object holds one reference, like an object
whose destructor is running, so it can still be resurrected.

A value released from a destructor, which runs in a frame of its own, starts
a loop of its own, so that unbounded recursion through destructors still
reaches the stack limit and throws.

The queue is reset when a request starts and ends, and the draining flag when
a bailout happens, as a fatal error in a destructor leaves the loop with a
longjmp.

Nothing changes until the stack is within the margin of the limit, and the
mechanism is inactive where the stack limit is unsupported or disabled with
zend.max_allowed_stack_size=-1.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Stack overflow when destroying deeply nested arrays or objects

1 participant