Skip to content

Commit fec7950

Browse files
committed
Fix GH-23089: stack overflow in array_merge_recursive()
Check the Zend stack limit before descending into nested arrays Add a regression test with iterative input cleanup to isolate the merge failure from the separate array destruction overflow under AddressSanitizer Continues the stack guard proposed in GH-23091
1 parent 6144bac commit fec7950

3 files changed

Lines changed: 39 additions & 0 deletions

File tree

‎NEWS‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,8 @@ PHP NEWS
8686
(ndossche)
8787

8888
- Standard:
89+
. Fixed bug GH-23089 (Stack overflow in array_merge_recursive() with deeply
90+
nested arrays). (Lazizbek Ergashev, akasakariko)
8991
. Fixed dns_get_record() returning partially built records for malformed
9092
DNS responses. (Marti2203)
9193

‎ext/standard/array.c‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4100,6 +4100,13 @@ PHPAPI int php_array_merge_recursive(HashTable *dest, HashTable *src) /* {{{ */
41004100
zval *src_entry, *dest_entry;
41014101
zend_string *string_key;
41024102

4103+
#ifdef ZEND_CHECK_STACK_LIMIT
4104+
if (UNEXPECTED(zend_call_stack_overflowed(EG(stack_limit)))) {
4105+
zend_call_stack_size_error();
4106+
return 0;
4107+
}
4108+
#endif
4109+
41034110
ZEND_HASH_FOREACH_STR_KEY_VAL(src, string_key, src_entry) {
41044111
if (string_key) {
41054112
if ((dest_entry = zend_hash_find_known_hash(dest, string_key)) != NULL) {
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
--TEST--
2+
GH-23089 (Stack overflow in array_merge_recursive with deeply nested arrays)
3+
--SKIPIF--
4+
<?php
5+
if (ini_get('zend.max_allowed_stack_size') === false) {
6+
die('skip No stack limit support');
7+
}
8+
?>
9+
--INI--
10+
zend.max_allowed_stack_size=1M
11+
--FILE--
12+
<?php
13+
$a = [];
14+
for ($i = 0; $i < 30000; $i++) {
15+
$a = ['k' => $a];
16+
}
17+
try {
18+
array_merge_recursive($a, $a);
19+
} catch (Throwable $e) {
20+
echo $e::class, ': ', $e->getMessage(), "\n";
21+
}
22+
23+
/* Avoid the separate stack overflow during array destruction (GH-15869). */
24+
unset($e);
25+
while ($a) {
26+
$a = $a['k'];
27+
}
28+
?>
29+
--EXPECTF--
30+
Error: Maximum call stack size of %d bytes (zend.max_allowed_stack_size - zend.reserved_stack_size) reached. Infinite recursion?

0 commit comments

Comments
 (0)