Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions Zend/tests/gh15869.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
--TEST--
GH-15869 (Stack overflow in zend_array_destroy when freeing deeply nested arrays)
--FILE--
<?php
ini_set('memory_limit', '512M');

$a = [];
for ($i = 0; $i < 200000; $i++) {
$a = [$a];
}
echo "Built\n";
unset($a);
echo "Freed\n";
?>
--EXPECT--
Built
Freed
23 changes: 23 additions & 0 deletions Zend/tests/gh15869_multi_branch.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
--TEST--
GH-15869 (Stack overflow in zend_array_destroy with multiple deeply nested branches)
--FILE--
<?php
ini_set('memory_limit', '1G');

/* Two independent deeply nested chains in one array.
* Without the destroy stack, one branch would recurse via rc_dtor_func. */
$a = [];
$b = [];
for ($i = 0; $i < 200000; $i++) {
$a = [$a];
$b = [$b];
}
$c = [$a, $b];
unset($a, $b);
echo "Built\n";
unset($c);
echo "Freed\n";
?>
--EXPECT--
Built
Freed
31 changes: 29 additions & 2 deletions Zend/zend_hash.c
Original file line number Diff line number Diff line change
Expand Up @@ -1820,6 +1820,11 @@ ZEND_API void ZEND_FASTCALL zend_hash_destroy(HashTable *ht)

ZEND_API void ZEND_FASTCALL zend_array_destroy(HashTable *ht)
{
zend_array *child;

tail_call:
child = NULL;

IS_CONSISTENT(ht);
HT_ASSERT(ht, GC_REFCOUNT(ht) <= 1);

Expand All @@ -1839,10 +1844,27 @@ ZEND_API void ZEND_FASTCALL zend_array_destroy(HashTable *ht)
if (HT_IS_PACKED(ht)) {
zval *zv = ht->arPacked;
zval *end = zv + ht->nNumUsed;
zval *last = end - 1;

do {
while (zv != last) {
i_zval_ptr_dtor(zv);
} while (++zv != end);
zv++;
}
/* Tail-call optimization for the last element: if it is an
* array whose refcount reaches zero, defer its destruction
* to avoid deep recursion through rc_dtor_func. */
if (Z_REFCOUNTED_P(last)) {
zend_refcounted *ref = Z_COUNTED_P(last);
if (!GC_DELREF(ref)) {
if (GC_TYPE(ref) == IS_ARRAY) {
child = (zend_array *)ref;
} else {
rc_dtor_func(ref);
}
} else {
gc_check_possible_root(ref);
}
}
} else {
Bucket *p = ht->arData;
Bucket *end = p + ht->nNumUsed;
Expand Down Expand Up @@ -1877,6 +1899,11 @@ ZEND_API void ZEND_FASTCALL zend_array_destroy(HashTable *ht)
free_ht:
zend_hash_iterators_remove(ht);
FREE_HASHTABLE(ht);

if (UNEXPECTED(child)) {
ht = (HashTable *)child;
goto tail_call;
}
}

ZEND_API void ZEND_FASTCALL zend_hash_clean(HashTable *ht)
Expand Down
Loading