From 8e3c0c16206cead1edc10b06f57af8f70f512007 Mon Sep 17 00:00:00 2001 From: Niels Dossche <7771979+nielsdos@users.noreply.github.com> Date: Wed, 27 Nov 2024 20:31:37 +0100 Subject: [PATCH] Fix GH-16957: Assertion failure in array_shift with self-referencing array We have an RC1 violation because we're immediately dereferencing and copying the resulting array in the test case. Instead, transfer the lifetime using ZVAL_COPY_VALUE and unwrap only after the internal iterator is reset. --- ext/standard/array.c | 10 +++++-- ext/standard/tests/array/gh16957.phpt | 41 +++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 ext/standard/tests/array/gh16957.phpt diff --git a/ext/standard/array.c b/ext/standard/array.c index ba1424f677f82..3865ce0f25e19 100644 --- a/ext/standard/array.c +++ b/ext/standard/array.c @@ -3513,7 +3513,8 @@ PHP_FUNCTION(array_shift) } idx++; } - RETVAL_COPY_DEREF(val); + ZVAL_COPY_VALUE(return_value, val); + ZVAL_UNDEF(val); /* Delete the first value */ zend_hash_packed_del_val(Z_ARRVAL_P(stack), val); @@ -3567,7 +3568,8 @@ PHP_FUNCTION(array_shift) } idx++; } - RETVAL_COPY_DEREF(val); + ZVAL_COPY_VALUE(return_value, val); + ZVAL_UNDEF(val); /* Delete the first value */ zend_hash_del_bucket(Z_ARRVAL_P(stack), p); @@ -3591,6 +3593,10 @@ PHP_FUNCTION(array_shift) } zend_hash_internal_pointer_reset(Z_ARRVAL_P(stack)); + + if (Z_ISREF_P(return_value)) { + zend_unwrap_reference(return_value); + } } /* }}} */ diff --git a/ext/standard/tests/array/gh16957.phpt b/ext/standard/tests/array/gh16957.phpt new file mode 100644 index 0000000000000..a716228249e7d --- /dev/null +++ b/ext/standard/tests/array/gh16957.phpt @@ -0,0 +1,41 @@ +--TEST-- +GH-16957 (Assertion failure in array_shift with self-referencing array) +--FILE-- + 1, 300 => 'two'); +var_dump($shifted = array_shift($new_array2)); +var_dump($new_array2); +var_dump($new_array2 === $shifted); +?> +--EXPECT-- +array(2) { + [0]=> + int(1) + [1]=> + string(3) "two" +} +array(2) { + [0]=> + int(1) + [1]=> + string(3) "two" +} +bool(true) +array(2) { + [0]=> + int(1) + [1]=> + string(3) "two" +} +array(2) { + [0]=> + int(1) + [1]=> + string(3) "two" +} +bool(true)