From f40c8fdf672923fd585023574e954b79b85b8777 Mon Sep 17 00:00:00 2001
From: Nikita Popov <nikita.ppv@gmail.com>
Date: Thu, 15 Apr 2021 12:32:05 +0200
Subject: [PATCH] Fix return-by-ref from array_reduce callback

Fixes oss-fuzz #32990.
---
 ext/standard/array.c                                     |  3 +++
 ext/standard/tests/array/array_reduce_return_by_ref.phpt | 11 +++++++++++
 2 files changed, 14 insertions(+)
 create mode 100644 ext/standard/tests/array/array_reduce_return_by_ref.phpt

diff --git a/ext/standard/array.c b/ext/standard/array.c
index 3967d83..4556cfe 100644
--- a/ext/standard/array.c
+++ b/ext/standard/array.c
@@ -5877,6 +5877,9 @@ PHP_FUNCTION(array_reduce)
 			zval_ptr_dtor(&args[1]);
 			zval_ptr_dtor(&args[0]);
 			ZVAL_COPY_VALUE(return_value, &retval);
+			if (UNEXPECTED(Z_ISREF_P(return_value))) {
+				zend_unwrap_reference(return_value);
+			}
 		} else {
 			zval_ptr_dtor(&args[1]);
 			zval_ptr_dtor(&args[0]);
diff --git a/ext/standard/tests/array/array_reduce_return_by_ref.phpt b/ext/standard/tests/array/array_reduce_return_by_ref.phpt
new file mode 100644
index 0000000..8da7018
--- /dev/null
+++ b/ext/standard/tests/array/array_reduce_return_by_ref.phpt
@@ -0,0 +1,11 @@
+--TEST--
+Return by reference from array_reduce() callback
+--FILE--
+<?php
+$array = [1, 2];
+var_dump(array_reduce($array, function &($a, $b) {
+    return $b;
+}, 0));
+?>
+--EXPECT--
+int(2)
-- 
1.8.3.1

