php-src icon indicating copy to clipboard operation
php-src copied to clipboard

Stack overflow when destroying deeply nested arrays or objects

Open YuanchengJiang opened this issue 2 years ago • 5 comments

Description

The following code:

<?php
function test($vars) {
}
function foo() {
foreach ($array as $value) {
try {
try {
foreach ($array as $_) {
}
} finally {
throw new Exception;
}
} catch (Exception $e) { }
}
}
for ($i=0; $fusion < 550; $i++) {
$array = array($array);
}

Resulted in this output:

Segmentation fault (core dumped)

this seems to crash very old php like php 5.5

PHP Version

PHP 8.4.0-dev

Operating System

ubuntu 22.04

YuanchengJiang avatar Sep 13 '24 05:09 YuanchengJiang

I cannot reproduce this on PHP-8.2 or master. @YuanchengJiang Did you only test this on 5.5? If so, we no longer support that. See https://www.php.net/supported-versions.php.

iluuu1994 avatar Sep 13 '24 12:09 iluuu1994

Ah, nevermind. I can see it now. If the memory_limit is higher, this can trigger a stack-overflow when freeing the memory.

Fatal error: Allowed memory size of 134217728 bytes exhausted at file:0 (tried to allocate 224 bytes) in /home/ilutov/Developer/php-src/test.php on line 17
AddressSanitizer:DEADLYSIGNAL
=================================================================
==2207238==ERROR: AddressSanitizer: stack-overflow on address 0x7fff20c31ff8 (pc 0x0000012e7936 bp 0x7fff20c32030 sp 0x7fff20c31ff0 T0)
    #0 0x12e7936 in zend_array_destroy /home/ilutov/Developer/php-src/Zend/zend_hash.c:1747
    #1 0x1268336 in rc_dtor_func /home/ilutov/Developer/php-src/Zend/zend_variables.c:57
    #2 0x12cc9b1 in i_zval_ptr_dtor /home/ilutov/Developer/php-src/Zend/zend_variables.h:44
    #3 0x12e7ec2 in zend_array_destroy /home/ilutov/Developer/php-src/Zend/zend_hash.c:1769
    #4 0x1268336 in rc_dtor_func /home/ilutov/Developer/php-src/Zend/zend_variables.c:57
    #5 0x12cc9b1 in i_zval_ptr_dtor /home/ilutov/Developer/php-src/Zend/zend_variables.h:44
    #6 0x12e7ec2 in zend_array_destroy /home/ilutov/Developer/php-src/Zend/zend_hash.c:1769
    #7 0x1268336 in rc_dtor_func /home/ilutov/Developer/php-src/Zend/zend_variables.c:57
    #8 0x12cc9b1 in i_zval_ptr_dtor /home/ilutov/Developer/php-src/Zend/zend_variables.h:44
    #9 0x12e7ec2 in zend_array_destroy /home/ilutov/Developer/php-src/Zend/zend_hash.c:1769
    #10 0x1268336 in rc_dtor_func /home/ilutov/Developer/php-src/Zend/zend_variables.c:57
    #11 0x12cc9b1 in i_zval_ptr_dtor /home/ilutov/Developer/php-src/Zend/zend_variables.h:44
    #12 0x12e7ec2 in zend_array_destroy /home/ilutov/Developer/php-src/Zend/zend_hash.c:1769
    #13 0x1268336 in rc_dtor_func /home/ilutov/Developer/php-src/Zend/zend_variables.c:57
    #14 0x12cc9b1 in i_zval_ptr_dtor /home/ilutov/Developer/php-src/Zend/zend_variables.h:44
    #15 0x12e7ec2 in zend_array_destroy /home/ilutov/Developer/php-src/Zend/zend_hash.c:1769

I'm not sure this is worth fixing. It realistically only occurs in maliciously crafted data. /cc @arnaud-lb

iluuu1994 avatar Sep 13 '24 12:09 iluuu1994

It would be useful to fix this (it can happen with real code due to bugs - at least it happened to me during development), but I'm not sure we have a good way to do it. The same problem exists with nested objects.

arnaud-lb avatar Sep 13 '24 15:09 arnaud-lb

Some data points on current code, plus a prototype with measurements, in case they help decide whether this is worth fixing.

Still reproducible on master (930dacc5, 8.7.0-dev), 8.6.0 and 8.5.10, and it does not need crafted code. A plain linked list released from its head is enough:

<?php
class Node { public $next = null; }

$depth = (int) ($argv[1] ?? 100000);
$head = null;
for ($i = 0; $i < $depth; $i++) {
    $n = new Node();
    $n->next = $head;
    $head = $n;
}
unset($n);
echo "built\n";
$head = null;   // SIGSEGV here
echo "freed\n";

The array form is the same loop with $a = [$a]; followed by $a = null;. Both print built and then die.

First failing depth, 8 MiB stack, memory_limit=-1:

Build Arrays Objects
master 930dacc5, NTS, Linux aarch64 (--disable-all --enable-cli) 174,805 75,209
8.6.0 ZTS, Linux aarch64 (official php:8.6-cli image) ~174,800 ~75,200
8.5.10 NTS, macOS arm64 ~87,400 ~87,400

zend.max_allowed_stack_size does not cover this path. Same crash with the limit set to 4M on master and 8.6.0, and 1M on 8.5.10. The comparison path already has a check: $a == $b and $a === $b on the same structures throw Maximum call stack size reached during comparison. Destruction is the path that is left unguarded.

On "artificially crafted data structures" (from the discussion on #21494): 75k nodes is within reach of ordinary code. A queue, a parsed token stream or a degenerate tree built from input and held as a singly linked list hits it. Objects fail earlier than arrays, so a fix that only handles array tails leaves the more common shape broken.

A prototype that covers arrays and objects

The patch below (against 930dacc5, 8 files, +105 lines) does this:

  • zend_array_destroy() and zend_objects_store_del() test the stack position on entry, against EG(stack_limit) plus a 128 KiB margin.
  • With room to spare, nothing changes.
  • Near the limit, the value is pushed onto a pending list instead of being destroyed. The frame that hit the limit then destroys the pending values in a loop; values deferred while it runs join the same list, so the rest of the structure is released at a constant stack depth.
  • A pending object holds one reference, like an object whose destructor is running, so it can still be resurrected.

Destruction order is unchanged until the stack is nearly exhausted. For a chain released from its head it stays head-to-tail even then.

What I checked on master, patched against unpatched:

  • Both reproducers pass at 1,000,000 levels.
  • A script covering destructor order on a linked list, an exception thrown by a deferred destructor, mixed array/object nesting, two independent deep branches, a collected cycle and a live list surviving a collection prints the same output as the unpatched build at 20,000 levels, and the same again at 400,000.
  • A 300,000-level release inside a Fiber passes.
  • Zend/tests: 5569 passed, 0 failed, identical to the unpatched build (minimal --disable-all build, so extension tests did not run).

Cost

Instructions executed, measured with callgrind:

Script Unpatched Patched Diff
Zend/bench.php 3,841,001,532 3,841,006,156 +0.000%
Destruction-heavy loop (below) 1,364,865,608 1,377,465,733 +0.92%

That is about 4 instructions per array or object destruction. The second script is a worst case built for this path: 300,000 iterations that each create and destroy a nested array and two objects. I have no WordPress or Symfony numbers; your CI benchmark would say more than mine.

<?php
class P { public $a; public $b; function __construct($a, $b) { $this->a = $a; $this->b = $b; } }
$sum = 0;
for ($i = 0; $i < 300000; $i++) {
    $row = ['id' => $i, 'tags' => ['x', 'y', [$i, [$i + 1]]], 'meta' => ['k' => ['v' => $i]]];
    $o = new P($row, new P([$i], null));
    $sum += count($row['tags']) + count($o->b->a);
}
echo $sum, "\n";

Known gaps

  • No .phpt tests yet; not built on ZTS or Windows.
  • The "draining" flag is per executor, not per fiber: if a destructor suspends a fiber while the list is being drained, values deferred elsewhere wait until it resumes.
  • Destructors of deferred objects run with the margin as their stack budget.

Is a cost in this range acceptable for this bug? If so I can turn the prototype into a proper PR.

Prototype patch against 930dacc5
diff --git a/Zend/zend.c b/Zend/zend.c
index 3b68f636..47091cfd 100644
--- a/Zend/zend.c
+++ b/Zend/zend.c
@@ -847,6 +847,12 @@ static void executor_globals_ctor(zend_executor_globals *executor_globals) /* {{
 	executor_globals->lineno_override = -1;
 #ifdef ZEND_CHECK_STACK_LIMIT
 	executor_globals->stack_limit = (void*)0;
+#ifdef ZEND_CHECK_STACK_LIMIT
+	executor_globals->deferred_dtors = NULL;
+	executor_globals->deferred_dtors_count = 0;
+	executor_globals->deferred_dtors_size = 0;
+	executor_globals->deferred_dtors_draining = false;
+#endif
 	executor_globals->stack_base = (void*)0;
 #endif
 #ifdef ZEND_MAX_EXECUTION_TIMERS
diff --git a/Zend/zend_globals.h b/Zend/zend_globals.h
index bf93bf00..611bb539 100644
--- a/Zend/zend_globals.h
+++ b/Zend/zend_globals.h
@@ -322,6 +322,11 @@ struct _zend_executor_globals {
 	zend_call_stack call_stack;
 	zend_long max_allowed_stack_size;
 	zend_ulong reserved_stack_size;
+	/* Arrays and objects whose destruction was deferred near the stack limit */
+	zend_refcounted **deferred_dtors;
+	uint32_t deferred_dtors_count;
+	uint32_t deferred_dtors_size;
+	bool deferred_dtors_draining;
 #endif
 
 #ifdef ZEND_MAX_EXECUTION_TIMERS
diff --git a/Zend/zend_hash.c b/Zend/zend_hash.c
index 59be1972..bae238c9 100644
--- a/Zend/zend_hash.c
+++ b/Zend/zend_hash.c
@@ -20,6 +20,7 @@
 #include "zend.h"
 #include "zend_globals.h"
 #include "zend_variables.h"
+#include "zend_call_stack.h"
 
 #if defined(__aarch64__) || defined(_M_ARM64)
 # include <arm_neon.h>
@@ -2042,7 +2043,7 @@ ZEND_ATTRIBUTE_NONNULL ZEND_API void ZEND_FASTCALL zend_hash_destroy(HashTable *
 	pefree(HT_GET_DATA_ADDR(ht), GC_FLAGS(ht) & IS_ARRAY_PERSISTENT);
 }
 
-ZEND_ATTRIBUTE_NONNULL ZEND_API void ZEND_FASTCALL zend_array_destroy(HashTable *ht)
+static zend_always_inline void zend_array_destroy_impl(HashTable *ht)
 {
 	IS_CONSISTENT(ht);
 	HT_ASSERT(ht, GC_REFCOUNT(ht) <= 1);
@@ -2106,6 +2107,23 @@ ZEND_ATTRIBUTE_NONNULL ZEND_API void ZEND_FASTCALL zend_array_destroy(HashTable
 	FREE_HASHTABLE(ht);
 }
 
+ZEND_ATTRIBUTE_NONNULL ZEND_API void ZEND_FASTCALL zend_array_destroy(HashTable *ht)
+{
+#ifdef ZEND_CHECK_STACK_LIMIT
+	if (ZEND_RC_DTOR_NEAR_STACK_LIMIT()) {
+		zend_rc_dtor_defer((zend_refcounted*) ht);
+		return;
+	}
+#endif
+	zend_array_destroy_impl(ht);
+}
+
+/* Destroys the array in the calling frame, without the near-stack-limit deferral. */
+ZEND_ATTRIBUTE_NONNULL ZEND_API void ZEND_FASTCALL zend_array_destroy_now(HashTable *ht)
+{
+	zend_array_destroy_impl(ht);
+}
+
 ZEND_ATTRIBUTE_NONNULL ZEND_API void ZEND_FASTCALL zend_hash_clean(HashTable *ht)
 {
 	IS_CONSISTENT(ht);
diff --git a/Zend/zend_hash.h b/Zend/zend_hash.h
index 0b695e3c..1e3aaf67 100644
--- a/Zend/zend_hash.h
+++ b/Zend/zend_hash.h
@@ -382,6 +382,7 @@ ZEND_ATTRIBUTE_NONNULL ZEND_API HashTable* ZEND_FASTCALL zend_new_pair(const zva
 ZEND_ATTRIBUTE_NONNULL ZEND_API uint32_t zend_array_count(HashTable *ht);
 ZEND_ATTRIBUTE_NONNULL ZEND_API HashTable* ZEND_FASTCALL zend_array_dup(const HashTable *source);
 ZEND_ATTRIBUTE_NONNULL ZEND_API void ZEND_FASTCALL zend_array_destroy(HashTable *ht);
+ZEND_API void ZEND_FASTCALL zend_array_destroy_now(HashTable *ht);
 ZEND_ATTRIBUTE_NONNULL ZEND_API HashTable* zend_array_to_list(const HashTable *source);
 ZEND_ATTRIBUTE_NONNULL ZEND_API void ZEND_FASTCALL zend_symtable_clean(HashTable *ht);
 ZEND_ATTRIBUTE_NONNULL ZEND_API HashTable* ZEND_FASTCALL zend_symtable_to_proptable(HashTable *ht);
diff --git a/Zend/zend_objects_API.c b/Zend/zend_objects_API.c
index 12362ab9..b0994ab9 100644
--- a/Zend/zend_objects_API.c
+++ b/Zend/zend_objects_API.c
@@ -20,6 +20,7 @@
 #include "zend.h"
 #include "zend_globals.h"
 #include "zend_variables.h"
+#include "zend_call_stack.h"
 #include "zend_API.h"
 #include "zend_objects_API.h"
 #include "zend_fibers.h"
@@ -156,7 +157,7 @@ ZEND_API void ZEND_FASTCALL zend_objects_store_put(zend_object *object)
 	EG(objects_store).object_buckets[handle] = object;
 }
 
-ZEND_API void ZEND_FASTCALL zend_objects_store_del(zend_object *object) /* {{{ */
+static zend_always_inline void zend_objects_store_del_impl(zend_object *object) /* {{{ */
 {
 	ZEND_ASSERT(GC_REFCOUNT(object) == 0);
 
@@ -198,6 +199,23 @@ ZEND_API void ZEND_FASTCALL zend_objects_store_del(zend_object *object) /* {{{ *
 		ZEND_OBJECTS_STORE_ADD_TO_FREE_LIST(handle);
 	}
 }
+
+ZEND_API void ZEND_FASTCALL zend_objects_store_del(zend_object *object)
+{
+#ifdef ZEND_CHECK_STACK_LIMIT
+	if (ZEND_RC_DTOR_NEAR_STACK_LIMIT()) {
+		zend_rc_dtor_defer((zend_refcounted*) object);
+		return;
+	}
+#endif
+	zend_objects_store_del_impl(object);
+}
+
+/* Destroys the object in the calling frame, without the near-stack-limit deferral. */
+ZEND_API void ZEND_FASTCALL zend_objects_store_del_now(zend_object *object)
+{
+	zend_objects_store_del_impl(object);
+}
 /* }}} */
 
 ZEND_API ZEND_COLD zend_property_info *zend_get_property_info_for_slot_slow(zend_object *obj, zval *slot)
diff --git a/Zend/zend_objects_API.h b/Zend/zend_objects_API.h
index 0c1acb90..513fe015 100644
--- a/Zend/zend_objects_API.h
+++ b/Zend/zend_objects_API.h
@@ -61,6 +61,7 @@ ZEND_API void ZEND_FASTCALL zend_objects_store_destroy(zend_objects_store *objec
 /* Store API functions */
 ZEND_API void ZEND_FASTCALL zend_objects_store_put(zend_object *object);
 ZEND_API void ZEND_FASTCALL zend_objects_store_del(zend_object *object);
+ZEND_API void ZEND_FASTCALL zend_objects_store_del_now(zend_object *object);
 
 /* Called when the ctor was terminated by an exception */
 static zend_always_inline void zend_object_store_ctor_failed(zend_object *obj)
diff --git a/Zend/zend_variables.c b/Zend/zend_variables.c
index 1ee84ce5..0f8a8a54 100644
--- a/Zend/zend_variables.c
+++ b/Zend/zend_variables.c
@@ -56,6 +56,50 @@ ZEND_API void ZEND_FASTCALL rc_dtor_func(zend_refcounted *p)
 	zend_rc_dtor_func[GC_TYPE(p)](p);
 }
 
+#ifdef ZEND_CHECK_STACK_LIMIT
+/* Called instead of destroying an array or object when the native stack is nearly
+ * exhausted. The value is queued; the first caller to arrive here then destroys the
+ * queued values in a loop, and values queued while it runs join the same queue, so the
+ * rest of the structure is released at a constant stack depth. A queued object holds one
+ * reference, like an object whose destructor is running, so it can be resurrected. */
+ZEND_API ZEND_COLD void ZEND_FASTCALL zend_rc_dtor_defer(zend_refcounted *p)
+{
+	if (UNEXPECTED(GC_TYPE(p) == IS_NULL)) {
+		/* GC released this object already. */
+		return;
+	}
+	if (GC_TYPE(p) == IS_OBJECT) {
+		GC_SET_REFCOUNT(p, 1);
+	}
+	GC_REMOVE_FROM_BUFFER(p);
+
+	if (EG(deferred_dtors_count) == EG(deferred_dtors_size)) {
+		EG(deferred_dtors_size) = EG(deferred_dtors_size) ? EG(deferred_dtors_size) * 2 : 64;
+		EG(deferred_dtors) = safe_erealloc(EG(deferred_dtors), EG(deferred_dtors_size), sizeof(zend_refcounted*), 0);
+	}
+	EG(deferred_dtors)[EG(deferred_dtors_count)++] = p;
+
+	if (EG(deferred_dtors_draining)) {
+		return;
+	}
+	EG(deferred_dtors_draining) = true;
+	while (EG(deferred_dtors_count)) {
+		p = EG(deferred_dtors)[--EG(deferred_dtors_count)];
+		if (GC_TYPE(p) == IS_ARRAY) {
+			zend_array_destroy_now((zend_array*) p);
+		} else if (GC_DELREF(p) == 0) {
+			zend_objects_store_del_now((zend_object*) p);
+		} else {
+			gc_check_possible_root(p);
+		}
+	}
+	EG(deferred_dtors_draining) = false;
+	efree(EG(deferred_dtors));
+	EG(deferred_dtors) = NULL;
+	EG(deferred_dtors_size) = 0;
+}
+#endif
+
 #if ZEND_DEBUG
 static void ZEND_FASTCALL zend_string_destroy(zend_string *str)
 {
diff --git a/Zend/zend_variables.h b/Zend/zend_variables.h
index 9c6040a7..1861143a 100644
--- a/Zend/zend_variables.h
+++ b/Zend/zend_variables.h
@@ -27,6 +27,16 @@
 BEGIN_EXTERN_C()
 
 ZEND_API void ZEND_FASTCALL rc_dtor_func(zend_refcounted *p);
+
+#ifdef ZEND_CHECK_STACK_LIMIT
+/* Destroying a container destroys its children, one native frame per nesting level.
+ * Within this distance of the stack limit the destruction is deferred instead: see
+ * zend_rc_dtor_defer(). The margin is what a deferred destructor still has to run in. */
+# define ZEND_RC_DTOR_STACK_MARGIN (128 * 1024)
+# define ZEND_RC_DTOR_NEAR_STACK_LIMIT() \
+	UNEXPECTED((uintptr_t) zend_call_stack_position() <= (uintptr_t) EG(stack_limit) + ZEND_RC_DTOR_STACK_MARGIN)
+ZEND_API ZEND_COLD void ZEND_FASTCALL zend_rc_dtor_defer(zend_refcounted *p);
+#endif
 ZEND_API void ZEND_FASTCALL zval_copy_ctor_func(zval *zvalue);
 
 static zend_always_inline void zval_ptr_dtor_nogc(zval *zval_ptr)

Guikingone avatar Nov 29 '26 15:11 Guikingone

@Guikingone the patch makes sense to me. Feel free to create a PR against master.

The fiber gap would be fixed by #20001 later.

Nit: please rename "deferred dtors" to "deferred garbage" to avoid the confusion with destructors.

arnaud-lb avatar Nov 30 '26 15:11 arnaud-lb