diff --git a/Zend/zend_API.h b/Zend/zend_API.h
index d1064970dcd5..d69618169087 100644
--- a/Zend/zend_API.h
+++ b/Zend/zend_API.h
@@ -938,6 +938,14 @@ static zend_always_inline void zend_call_known_instance_method_with_1_params(
ZEND_API void zend_call_known_instance_method_with_2_params(
zend_function *fn, zend_object *this_ptr, zval *retval_ptr, zval *param1, zval *param2);
+/* Call a resolved user/internal function with two by-value arguments.
+ * Excludes deprecated/generator functions, trampolines, by-reference passing for either parameter. */
+ZEND_API zend_result zend_call_known_user_function_with_2_params(
+ const zend_fcall_info_cache *fcc, zval *retval, zval *arg1, zval *arg2);
+
+ZEND_API zend_result zend_call_known_internal_function_with_2_params(
+ const zend_fcall_info_cache *fcc, zval *retval, zval *arg1, zval *arg2);
+
/* Call method if it exists.
* Return FAILURE if method does not exist.
* If FAILURE is returned, retval will be UNDEF, and error will contain the validation failure message if provided.
diff --git a/Zend/zend_execute_API.c b/Zend/zend_execute_API.c
index 94273a4bc59f..3df57ca3ce11 100644
--- a/Zend/zend_execute_API.c
+++ b/Zend/zend_execute_API.c
@@ -1205,6 +1205,145 @@ ZEND_API void zend_call_known_instance_method_with_2_params(
zend_call_known_instance_method(fn, this_ptr, retval_ptr, 2, params);
}
+static zend_always_inline zend_result zend_call_known_function_with_2_params(
+ const zend_fcall_info_cache *fcc, zval *retval_ptr, zval *arg1, zval *arg2, bool internal)
+{
+ zval unused_retval;
+ zval *retval = retval_ptr ? retval_ptr : &unused_retval;
+
+ ZVAL_UNDEF(retval);
+ if (!EG(active)) {
+ return FAILURE;
+ }
+ if (ZEND_HAS_OOM()) {
+ zend_handle_delayed_oom();
+ ZEND_ASSERT(EG(exception));
+ }
+ if (EG(exception)) {
+ return SUCCESS;
+ }
+#ifdef ZEND_CHECK_STACK_LIMIT
+ if (UNEXPECTED(zend_call_stack_overflowed(EG(stack_limit)))) {
+ zend_call_stack_size_error();
+ return SUCCESS;
+ }
+#endif
+
+ zend_function *func = fcc->function_handler;
+ ZEND_ASSERT(func && func->type == (internal ? ZEND_INTERNAL_FUNCTION : ZEND_USER_FUNCTION));
+ ZEND_ASSERT(!(func->common.fn_flags & (ZEND_ACC_CALL_VIA_TRAMPOLINE | ZEND_ACC_DEPRECATED
+ | ZEND_ACC_GENERATOR)));
+ ZEND_ASSERT(!ARG_SHOULD_BE_SENT_BY_REF(func, 1) && !ARG_SHOULD_BE_SENT_BY_REF(func, 2));
+ zend_object *object = (func->common.fn_flags & ZEND_ACC_STATIC) ? NULL : fcc->object;
+ uint32_t call_info = ZEND_CALL_TOP_FUNCTION | ZEND_CALL_DYNAMIC;
+ if (object) {
+ GC_ADDREF(object);
+ call_info |= ZEND_CALL_HAS_THIS;
+ }
+ if (func->common.fn_flags & ZEND_ACC_CLOSURE) {
+ GC_ADDREF(ZEND_CLOSURE_OBJECT(func));
+ call_info |= ZEND_CALL_CLOSURE;
+ if (func->common.fn_flags & ZEND_ACC_FAKE_CLOSURE) {
+ call_info |= ZEND_CALL_FAKE_CLOSURE;
+ }
+ }
+ zend_execute_data *call = zend_vm_stack_push_call_frame(call_info, func, 2,
+ object ? (void *) object : (void *) fcc->called_scope);
+ ZVAL_COPY_DEREF(ZEND_CALL_ARG(call, 1), arg1);
+ ZVAL_COPY_DEREF(ZEND_CALL_ARG(call, 2), arg2);
+
+ const zend_class_entry *orig_fake_scope = EG(fake_scope);
+ EG(fake_scope) = NULL;
+ if (!internal) {
+ uint32_t orig_jit_trace_num = EG(jit_trace_num);
+ zend_init_func_execute_data(call, &func->op_array, retval);
+ ZEND_OBSERVER_FCALL_BEGIN(call);
+ zend_execute_ex(call);
+ EG(jit_trace_num) = orig_jit_trace_num;
+ } else {
+ ZVAL_NULL(retval);
+ call->prev_execute_data = EG(current_execute_data);
+ EG(current_execute_data) = call;
+#if ZEND_DEBUG
+ bool should_throw = zend_internal_call_should_throw(func, call);
+#endif
+ ZEND_OBSERVER_FCALL_BEGIN(call);
+ if (EXPECTED(zend_execute_internal == NULL)) {
+ func->internal_function.handler(call, retval);
+ } else {
+ zend_execute_internal(call, retval);
+ }
+#if ZEND_DEBUG
+ if (!EG(exception) && !ZEND_HAS_OOM() && call->func) {
+ if (should_throw) {
+ zend_internal_call_arginfo_violation(call->func);
+ }
+ if (call->func->common.fn_flags & ZEND_ACC_HAS_RETURN_TYPE) {
+ bool result = zend_verify_internal_return_type(call->func, retval);
+ ZEND_ASSERT(result);
+ }
+ ZEND_ASSERT(((call->func->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_return_should_unwrap_ref(call))
+ ? Z_ISREF_P(retval) : !Z_ISREF_P(retval));
+ ZEND_ASSERT(!(call->func->common.fn_flags2 & ZEND_ACC2_FORBID_DYN_CALLS));
+ }
+#endif
+ ZEND_OBSERVER_FCALL_END(call, retval);
+ EG(current_execute_data) = call->prev_execute_data;
+ zend_vm_stack_free_args(call);
+ if (UNEXPECTED(ZEND_CALL_INFO(call) & ZEND_CALL_HAS_EXTRA_NAMED_PARAMS)) {
+ zend_array_release(call->extra_named_params);
+ }
+ if (EG(exception)) {
+ zval_ptr_dtor(retval);
+ ZVAL_UNDEF(retval);
+ }
+ }
+
+ if (UNEXPECTED(atomic_exchange(&EG(vm_interrupt), false))) {
+ if (atomic_load(&EG(timed_out))) {
+ zend_timeout();
+ } else if (ZEND_HAS_OOM()) {
+ zend_handle_delayed_oom();
+ zval_ptr_dtor(retval);
+ ZVAL_UNDEF(retval);
+ } else if (zend_interrupt_function) {
+ zend_interrupt_function(EG(current_execute_data));
+ }
+ }
+ if (UNEXPECTED(ZEND_CALL_INFO(call) & ZEND_CALL_RELEASE_THIS)) {
+ OBJ_RELEASE(Z_OBJ(call->This));
+ }
+ EG(fake_scope) = orig_fake_scope;
+ if (object) {
+ OBJ_RELEASE(object);
+ }
+ zend_vm_stack_free_call_frame(call);
+ if (UNEXPECTED(EG(exception))) {
+ if (UNEXPECTED(!EG(current_execute_data))) {
+ zend_throw_exception_internal(NULL);
+ } else if (EG(current_execute_data)->func
+ && ZEND_USER_CODE(EG(current_execute_data)->func->common.type)) {
+ zend_rethrow_exception(EG(current_execute_data));
+ }
+ }
+ if (!retval_ptr) {
+ zval_ptr_dtor(&unused_retval);
+ }
+ return SUCCESS;
+}
+
+ZEND_API zend_result zend_call_known_user_function_with_2_params(
+ const zend_fcall_info_cache *fcc, zval *retval, zval *arg1, zval *arg2)
+{
+ return zend_call_known_function_with_2_params(fcc, retval, arg1, arg2, false);
+}
+
+ZEND_API zend_result zend_call_known_internal_function_with_2_params(
+ const zend_fcall_info_cache *fcc, zval *retval, zval *arg1, zval *arg2)
+{
+ return zend_call_known_function_with_2_params(fcc, retval, arg1, arg2, true);
+}
+
ZEND_API zend_result zend_call_method_if_exists_ex(
zend_object *this_ptr, zend_string *method_name, zval *retval_ptr,
uint32_t param_count, zval *params, HashTable *named_params, char **error
diff --git a/ext/standard/array.c b/ext/standard/array.c
index fe5d7cfd55e5..cce1e3583a80 100644
--- a/ext/standard/array.c
+++ b/ext/standard/array.c
@@ -755,6 +755,35 @@ PHP_FUNCTION(ksort)
}
/* }}} */
+static zend_always_inline zend_function *php_array_get_known_compare_func(const zend_fcall_info_cache *fcc)
+{
+ zend_function *func = fcc->function_handler;
+ if (func && (func->type == ZEND_USER_FUNCTION || func->type == ZEND_INTERNAL_FUNCTION)
+ && !(func->common.fn_flags & (ZEND_ACC_CALL_VIA_TRAMPOLINE | ZEND_ACC_DEPRECATED
+ | ZEND_ACC_GENERATOR))
+ && !ARG_SHOULD_BE_SENT_BY_REF(func, 1) && !ARG_SHOULD_BE_SENT_BY_REF(func, 2)) {
+ return func;
+ }
+ return NULL;
+}
+
+/* A comparator can replace or clear the shared callback state while comparisons are running, for
+ * example through a nested array_udiff_assoc() call, a failed callable check or a fiber switch.
+ * Use the specialized call only while the cache still holds the previously checked function. */
+static zend_always_inline void php_array_call_user_compare(zval *args, zval *retval)
+{
+ const zend_function *func = BG(user_compare_fci_cache).function_handler;
+ if (EXPECTED(func != NULL && func == BG(user_compare_known_func))) {
+ if (EXPECTED(func->type == ZEND_USER_FUNCTION)) {
+ zend_call_known_user_function_with_2_params(&BG(user_compare_fci_cache), retval, &args[0], &args[1]);
+ } else {
+ zend_call_known_internal_function_with_2_params(&BG(user_compare_fci_cache), retval, &args[0], &args[1]);
+ }
+ } else {
+ zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache));
+ }
+}
+
static inline int php_array_user_compare_unstable(Bucket *f, Bucket *s) /* {{{ */
{
zval args[2];
@@ -766,7 +795,7 @@ static inline int php_array_user_compare_unstable(Bucket *f, Bucket *s) /* {{{ *
BG(user_compare_fci).param_count = 2;
BG(user_compare_fci).params = args;
BG(user_compare_fci).retval = &retval;
- zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache));
+ php_array_call_user_compare(args, &retval);
if (UNEXPECTED(Z_TYPE(retval) == IS_FALSE || Z_TYPE(retval) == IS_TRUE)) {
if (!ARRAYG(compare_deprecation_thrown)) {
@@ -780,7 +809,7 @@ static inline int php_array_user_compare_unstable(Bucket *f, Bucket *s) /* {{{ *
/* Retry with swapped operands. */
ZVAL_COPY_VALUE(&args[0], &s->val);
ZVAL_COPY_VALUE(&args[1], &f->val);
- zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache));
+ php_array_call_user_compare(args, &retval);
zend_long ret = php_get_long(&retval);
return -ZEND_NORMALIZE_BOOL(ret);
@@ -800,17 +829,21 @@ static int php_array_user_compare(Bucket *a, Bucket *b) /* {{{ */
#define PHP_ARRAY_CMP_FUNC_VARS \
zend_fcall_info old_user_compare_fci; \
- zend_fcall_info_cache old_user_compare_fci_cache \
+ zend_fcall_info_cache old_user_compare_fci_cache; \
+ zend_function *old_user_compare_known_func \
#define PHP_ARRAY_CMP_FUNC_BACKUP() \
old_user_compare_fci = BG(user_compare_fci); \
old_user_compare_fci_cache = BG(user_compare_fci_cache); \
+ old_user_compare_known_func = BG(user_compare_known_func); \
ARRAYG(compare_deprecation_thrown) = 0; \
BG(user_compare_fci_cache) = empty_fcall_info_cache; \
+ BG(user_compare_known_func) = NULL; \
#define PHP_ARRAY_CMP_FUNC_RESTORE() \
BG(user_compare_fci) = old_user_compare_fci; \
BG(user_compare_fci_cache) = old_user_compare_fci_cache; \
+ BG(user_compare_known_func) = old_user_compare_known_func; \
static void php_usort(INTERNAL_FUNCTION_PARAMETERS, bucket_compare_func_t compare_func, bool renumber) /* {{{ */
{
@@ -831,6 +864,8 @@ static void php_usort(INTERNAL_FUNCTION_PARAMETERS, bucket_compare_func_t compar
RETURN_TRUE;
}
+ BG(user_compare_known_func) = php_array_get_known_compare_func(&BG(user_compare_fci_cache));
+
/* Copy array, so the in-place modifications will not be visible to the callback function */
arr = zend_array_dup(arr);
@@ -879,7 +914,7 @@ static inline int php_array_user_key_compare_unstable(Bucket *f, Bucket *s) /* {
BG(user_compare_fci).param_count = 2;
BG(user_compare_fci).params = args;
BG(user_compare_fci).retval = &retval;
- zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache));
+ php_array_call_user_compare(args, &retval);
if (UNEXPECTED(Z_TYPE(retval) == IS_FALSE || Z_TYPE(retval) == IS_TRUE)) {
if (!ARRAYG(compare_deprecation_thrown)) {
@@ -902,7 +937,7 @@ static inline int php_array_user_key_compare_unstable(Bucket *f, Bucket *s) /* {
ZVAL_STR(&args[1], f->key);
}
- zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache));
+ php_array_call_user_compare(args, &retval);
zend_long ret = php_get_long(&retval);
return -ZEND_NORMALIZE_BOOL(ret);
@@ -5332,6 +5367,10 @@ static void php_array_intersect(INTERNAL_FUNCTION_PARAMETERS, int behavior, int
}
PHP_ARRAY_CMP_FUNC_BACKUP();
+ zend_function *known_data_func = data_compare_type == INTERSECT_COMP_DATA_USER
+ ? php_array_get_known_compare_func(fci_data_cache) : NULL;
+ zend_function *known_key_func = key_compare_type == INTERSECT_COMP_KEY_USER
+ ? php_array_get_known_compare_func(fci_key_cache) : NULL;
/* for each argument, create and sort list with pointers to the hash buckets */
lists = (Bucket **)safe_emalloc(arr_argc, sizeof(Bucket *), 0);
@@ -5340,9 +5379,11 @@ static void php_array_intersect(INTERNAL_FUNCTION_PARAMETERS, int behavior, int
if (behavior == INTERSECT_NORMAL && data_compare_type == INTERSECT_COMP_DATA_USER) {
BG(user_compare_fci) = *fci_data;
BG(user_compare_fci_cache) = *fci_data_cache;
+ BG(user_compare_known_func) = known_data_func;
} else if ((behavior & INTERSECT_ASSOC) && key_compare_type == INTERSECT_COMP_KEY_USER) {
BG(user_compare_fci) = *fci_key;
BG(user_compare_fci_cache) = *fci_key_cache;
+ BG(user_compare_known_func) = known_key_func;
}
for (i = 0; i < arr_argc; i++) {
@@ -5399,6 +5440,7 @@ static void php_array_intersect(INTERNAL_FUNCTION_PARAMETERS, int behavior, int
&& key_compare_type == INTERSECT_COMP_KEY_USER) {
BG(user_compare_fci) = *fci_key;
BG(user_compare_fci_cache) = *fci_key_cache;
+ BG(user_compare_known_func) = known_key_func;
}
for (i = 1; i < arr_argc; i++) {
@@ -5418,12 +5460,14 @@ static void php_array_intersect(INTERNAL_FUNCTION_PARAMETERS, int behavior, int
if (data_compare_type == INTERSECT_COMP_DATA_USER) {
BG(user_compare_fci) = *fci_data;
BG(user_compare_fci_cache) = *fci_data_cache;
+ BG(user_compare_known_func) = known_data_func;
}
if (intersect_data_compare_func(ptrs[0], ptrs[i]) != 0) {
c = 1;
if (key_compare_type == INTERSECT_COMP_KEY_USER) {
BG(user_compare_fci) = *fci_key;
BG(user_compare_fci_cache) = *fci_key_cache;
+ BG(user_compare_known_func) = known_key_func;
/* When KEY_USER, the last parameter is always the callback */
}
/* we are going to the break */
@@ -5936,6 +5980,10 @@ static void php_array_diff(INTERNAL_FUNCTION_PARAMETERS, int behavior, int data_
}
PHP_ARRAY_CMP_FUNC_BACKUP();
+ zend_function *known_data_func = data_compare_type == DIFF_COMP_DATA_USER
+ ? php_array_get_known_compare_func(fci_data_cache) : NULL;
+ zend_function *known_key_func = key_compare_type == DIFF_COMP_KEY_USER
+ ? php_array_get_known_compare_func(fci_key_cache) : NULL;
/* for each argument, create and sort list with pointers to the hash buckets */
lists = (Bucket **)safe_emalloc(arr_argc, sizeof(Bucket *), 0);
@@ -5944,9 +5992,11 @@ static void php_array_diff(INTERNAL_FUNCTION_PARAMETERS, int behavior, int data_
if (behavior == DIFF_NORMAL && data_compare_type == DIFF_COMP_DATA_USER) {
BG(user_compare_fci) = *fci_data;
BG(user_compare_fci_cache) = *fci_data_cache;
+ BG(user_compare_known_func) = known_data_func;
} else if ((behavior & DIFF_ASSOC) && key_compare_type == DIFF_COMP_KEY_USER) {
BG(user_compare_fci) = *fci_key;
BG(user_compare_fci_cache) = *fci_key_cache;
+ BG(user_compare_known_func) = known_key_func;
}
for (i = 0; i < arr_argc; i++) {
@@ -6000,6 +6050,7 @@ static void php_array_diff(INTERNAL_FUNCTION_PARAMETERS, int behavior, int data_
) {
BG(user_compare_fci) = *fci_key;
BG(user_compare_fci_cache) = *fci_key_cache;
+ BG(user_compare_known_func) = known_key_func;
}
c = 1;
for (i = 1; i < arr_argc; i++) {
@@ -6026,6 +6077,7 @@ static void php_array_diff(INTERNAL_FUNCTION_PARAMETERS, int behavior, int data_
if (data_compare_type == DIFF_COMP_DATA_USER) {
BG(user_compare_fci) = *fci_data;
BG(user_compare_fci_cache) = *fci_data_cache;
+ BG(user_compare_known_func) = known_data_func;
}
if (diff_data_compare_func(ptrs[0], ptr) != 0) {
/* the data is not the same */
@@ -6033,6 +6085,7 @@ static void php_array_diff(INTERNAL_FUNCTION_PARAMETERS, int behavior, int data_
if (key_compare_type == DIFF_COMP_KEY_USER) {
BG(user_compare_fci) = *fci_key;
BG(user_compare_fci_cache) = *fci_key_cache;
+ BG(user_compare_known_func) = known_key_func;
}
} else {
break;
diff --git a/ext/standard/basic_functions.c b/ext/standard/basic_functions.c
index 9ae99b6f1eed..db914d58ca0b 100644
--- a/ext/standard/basic_functions.c
+++ b/ext/standard/basic_functions.c
@@ -400,6 +400,7 @@ PHP_RINIT_FUNCTION(basic) /* {{{ */
BG(locale_changed) = 0;
BG(user_compare_fci) = empty_fcall_info;
BG(user_compare_fci_cache) = empty_fcall_info_cache;
+ BG(user_compare_known_func) = NULL;
BG(page_uid) = -1;
BG(page_gid) = -1;
BG(page_inode) = -1;
diff --git a/ext/standard/basic_functions.h b/ext/standard/basic_functions.h
index 10dfd584d704..920e74ec2b05 100644
--- a/ext/standard/basic_functions.h
+++ b/ext/standard/basic_functions.h
@@ -60,6 +60,8 @@ typedef struct _php_basic_globals {
size_t strtok_len;
zend_fcall_info user_compare_fci;
zend_fcall_info_cache user_compare_fci_cache;
+ /* Eligible function identity for specialized PHP/native comparison calls, or NULL. */
+ zend_function *user_compare_known_func;
zend_llist *user_tick_functions;
zval active_ini_file_section;
diff --git a/ext/standard/tests/array/array_udiff_uintersect_callback_state.phpt b/ext/standard/tests/array/array_udiff_uintersect_callback_state.phpt
new file mode 100644
index 000000000000..be20dd5a42f8
--- /dev/null
+++ b/ext/standard/tests/array/array_udiff_uintersect_callback_state.phpt
@@ -0,0 +1,74 @@
+--TEST--
+array_udiff() and array_uintersect() preserve results across nested and replaced callbacks
+--FILE--
+ 3, 'b' => 1, 'c' => 2, 'd' => 3];
+ $expected = $operation === 'array_udiff' ? ['a' => 3, 'b' => 1, 'd' => 3] : ['c' => 2];
+
+ // Nested comparisons must restore the outer callback.
+ $called = false;
+ $result = $operation($left, [2, 4], [2, 5], function ($a, $b) use (&$called) {
+ if (!$called) {
+ $called = true;
+ $inner = [3, 1, 2];
+ usort($inner, 'strcmp');
+ array_udiff($inner, [2], 'strcmp');
+ array_uintersect($inner, [2], 'strcmp');
+ }
+ return $a <=> $b;
+ });
+ var_dump($result === $expected);
+
+ // Failed callable validation clears the cached function.
+ $called = false;
+ $result = $operation($left, [2, 4], [2, 5], function ($a, $b) use (&$called) {
+ if (!$called) {
+ $called = true;
+ try {
+ array_udiff_assoc([1], [1], 'no_such_function');
+ } catch (TypeError $e) {
+ echo $e::class, "\n";
+ }
+ }
+ return $a <=> $b;
+ });
+ var_dump($result === $expected);
+
+ // A nested associative comparison can leave a different callback cached.
+ $called = false;
+ $result = $operation($left, [2, 4], [2, 5], function ($a, $b) use (&$called) {
+ if (!$called) {
+ $called = true;
+ array_uintersect_assoc(['1'], ['1'], 'strcmp');
+ }
+ return $a <=> $b;
+ });
+ var_dump($result === $expected);
+
+ try {
+ $operation($left, [2], static function ($a, $b): int {
+ throw new Exception('expected');
+ });
+ } catch (Exception $e) {
+ echo $e->getMessage(), "\n";
+ }
+ var_dump($operation($left, [2, 4], [2, 5], strcmp(...)) === $expected);
+}
+?>
+--EXPECT--
+array_udiff
+bool(true)
+TypeError
+bool(true)
+bool(true)
+expected
+bool(true)
+array_uintersect
+bool(true)
+TypeError
+bool(true)
+bool(true)
+expected
+bool(true)
diff --git a/ext/standard/tests/array/sort/usort_callback_state_replaced.phpt b/ext/standard/tests/array/sort/usort_callback_state_replaced.phpt
new file mode 100644
index 000000000000..86e8f5a0dd8f
--- /dev/null
+++ b/ext/standard/tests/array/sort/usort_callback_state_replaced.phpt
@@ -0,0 +1,65 @@
+--TEST--
+usort() keeps working when a comparator replaces or clears the shared callback state
+--FILE--
+ $args[1];
+ }
+}
+
+// A failed callable check clears the cached function.
+$items = [3, 1, 2];
+$called = false;
+usort($items, function ($a, $b) use (&$called): int {
+ if (!$called) {
+ $called = true;
+ try {
+ array_udiff_assoc([1], [1], 'no_such_function');
+ } catch (TypeError $error) {
+ echo $error::class, "\n";
+ }
+ }
+ return $a <=> $b;
+});
+echo implode(',', $items), "\n";
+
+// array_uintersect_assoc() leaves an internal function in the cache.
+$items = [3, 1, 2];
+$called = false;
+usort($items, function ($a, $b) use (&$called): int {
+ if (!$called) {
+ $called = true;
+ array_uintersect_assoc(['1'], ['1'], 'strcmp');
+ }
+ return $a <=> $b;
+});
+echo implode(',', $items), "\n";
+
+// A fiber suspended inside another sort's magic comparator leaves that sort's state behind.
+$items = [3, 1, 2];
+$fiber = null;
+try {
+ usort($items, function ($a, $b) use (&$fiber): int {
+ if ($fiber === null) {
+ $fiber = new Fiber(static function (): void {
+ $inner = [2, 1];
+ usort($inner, [new SuspendingComparator(), 'compare']);
+ });
+ $fiber->start();
+ var_dump($fiber->isSuspended());
+ }
+ return $a <=> $b;
+ });
+} catch (FiberError) {
+ // The outer sort may call the suspended sort's comparator outside its fiber.
+}
+echo "done\n";
+?>
+--EXPECT--
+TypeError
+1,2,3
+1,2,3
+bool(true)
+done
diff --git a/ext/standard/tests/array/sort/usort_internal_callback_state.phpt b/ext/standard/tests/array/sort/usort_internal_callback_state.phpt
new file mode 100644
index 000000000000..012cf25f655d
--- /dev/null
+++ b/ext/standard/tests/array/sort/usort_internal_callback_state.phpt
@@ -0,0 +1,32 @@
+--TEST--
+Native sorting callbacks tolerate callback-state changes during string conversion
+--FILE--
+value;
+ }
+}
+foreach (['strcmp', strcmp(...)] as $callback) {
+ SortString::$clear = true;
+ $items = [new SortString('3'), new SortString('1'), new SortString('2')];
+ usort($items, $callback);
+ foreach ($items as $item) { echo $item->value; }
+ echo "\n";
+}
+?>
+--EXPECT--
+cleared
+123
+cleared
+123
diff --git a/ext/standard/tests/array/sort/usort_internal_callbacks.phpt b/ext/standard/tests/array/sort/usort_internal_callbacks.phpt
new file mode 100644
index 000000000000..52a9f83826c8
--- /dev/null
+++ b/ext/standard/tests/array/sort/usort_internal_callbacks.phpt
@@ -0,0 +1,45 @@
+--TEST--
+Native sorting callbacks retain conversions, exceptions and bound method context
+--FILE--
+ 'a', 'item2' => 'b', 2 => 'c'];
+uksort($items, 'strnatcmp');
+echo implode(',', array_keys($items)), ': ', implode(',', $items), "\n";
+
+class SortValue {
+ public function __construct(public int $value) {}
+ public function compare(self $other): int {
+ return $this->value <=> $other->value;
+ }
+}
+$method = new ReflectionMethod(SortValue::class, 'compare');
+foreach ([[$method, 'invoke'], $method->invoke(...)] as $callback) {
+ $items = [new SortValue(3), new SortValue(1), new SortValue(2)];
+ usort($items, $callback);
+ foreach ($items as $item) { echo $item->value; }
+ echo "\n";
+}
+
+foreach (['strcmp', strcmp(...), 'strlen'] as $callback) {
+ try {
+ $items = [[], []];
+ usort($items, $callback);
+ } catch (TypeError $error) {
+ echo $error::class, ': ', $error->getMessage(), "\n";
+ }
+}
+echo "done\n";
+?>
+--EXPECT--
+2,10,30
+2,30,item2: c,a,b
+123
+123
+TypeError: strcmp(): Argument #1 ($string1) must be of type string, array given
+TypeError: strcmp(): Argument #1 ($string1) must be of type string, array given
+ArgumentCountError: strlen() expects exactly 1 argument, 2 given
+done
diff --git a/ext/standard/tests/array/sort/usort_reference_return.phpt b/ext/standard/tests/array/sort/usort_reference_return.phpt
new file mode 100644
index 000000000000..37ea146af405
--- /dev/null
+++ b/ext/standard/tests/array/sort/usort_reference_return.phpt
@@ -0,0 +1,53 @@
+--TEST--
+Sorting callbacks may return references to local or shared values
+--FILE--
+ $b;
+ return $result;
+}
+$items = [3, 1, 2];
+usort($items, 'compareLocal');
+var_dump($items === [1, 2, 3]);
+
+// Converting the comparison result must not modify the referenced string.
+$result = '';
+$closure = function &($a, $b) use (&$result) {
+ $result = (string) ($a <=> $b);
+ return $result;
+};
+$alias =& $closure(3, 1);
+$items = ['three' => 3, 'one' => 1, 'two' => 2];
+uasort($items, $closure);
+var_dump($items === ['one' => 1, 'two' => 2, 'three' => 3]);
+var_dump(is_string($alias));
+$alias = 'still alive';
+echo $result, "\n";
+
+class ReferenceComparator {
+ public int $result = 0;
+ public function &compare(int $a, int $b): int {
+ $this->result = $a <=> $b;
+ return $this->result;
+ }
+}
+$items = [3 => 'a', 1 => 'c', 2 => 'b'];
+uksort($items, (new ReferenceComparator())->compare(...));
+var_dump($items === [1 => 'c', 2 => 'b', 3 => 'a']);
+
+try {
+ $items = [2, 1];
+ usort($items, function &($a, $b) {
+ throw new Exception('expected');
+ });
+} catch (Exception $e) {
+ echo $e->getMessage(), "\n";
+}
+?>
+--EXPECT--
+bool(true)
+bool(true)
+bool(true)
+still alive
+bool(true)
+expected
diff --git a/ext/standard/tests/array/sort/usort_user_callback_context.phpt b/ext/standard/tests/array/sort/usort_user_callback_context.phpt
new file mode 100644
index 000000000000..75f5a99972db
--- /dev/null
+++ b/ext/standard/tests/array/sort/usort_user_callback_context.phpt
@@ -0,0 +1,28 @@
+--TEST--
+usort() keeps deprecations and called scope for user comparators
+--FILE--
+ $b; }
+
+class SortBase {
+ public static function compare($a, $b): int {
+ echo static::class, "\n";
+ return $a <=> $b;
+ }
+}
+class SortChild extends SortBase {}
+
+foreach (['deprecatedCompare', [SortChild::class, 'compare'], SortChild::compare(...)] as $callback) {
+ $items = [2, 1];
+ usort($items, $callback);
+ echo implode(',', $items), "\n";
+}
+?>
+--EXPECTF--
+Deprecated: Function deprecatedCompare() is deprecated in %s on line %d
+1,2
+SortChild
+1,2
+SortChild
+1,2
diff --git a/ext/zend_test/tests/execute_internal.phpt b/ext/zend_test/tests/execute_internal.phpt
index 6c7fc7577591..811d5abebaf4 100644
--- a/ext/zend_test/tests/execute_internal.phpt
+++ b/ext/zend_test/tests/execute_internal.phpt
@@ -16,6 +16,12 @@ f(time() > 0 ? [1, 2, 3] : []);
array_map("count", [[], [1, 2]]);
+foreach (['strcmp', strcmp(...)] as $callback) {
+ $items = ['b', 'a'];
+ usort($items, $callback);
+ echo $items[0], $items[1], "\n";
+}
+
?>
--EXPECTF--
@@ -35,3 +41,13 @@ int(6)
0 => 0,
1 => 2,
) -->
+
+
+
+
+ab
+
+
+
+
+ab
diff --git a/ext/zend_test/tests/observer_usort.phpt b/ext/zend_test/tests/observer_usort.phpt
new file mode 100644
index 000000000000..416dfbde5479
--- /dev/null
+++ b/ext/zend_test/tests/observer_usort.phpt
@@ -0,0 +1,52 @@
+--TEST--
+Observer: sorting callbacks, including reference returns, retain balanced begin and end events
+--EXTENSIONS--
+zend_test
+--INI--
+zend_test.observer.enabled=1
+zend_test.observer.show_output=1
+zend_test.observer.observe_all=1
+--FILE--
+ $b;
+}
+function &compareReference($a, $b): int {
+ $result = $a <=> $b;
+ return $result;
+}
+// Repeat compare() to check events after its observer handlers have been initialized.
+foreach ([
+ ['usort', 'compare'],
+ ['usort', 'compare'],
+ ['uksort', 'compareReference'],
+] as [$sort, $callback]) {
+ $items = [2 => 2, 1 => 1];
+ $sort($items, $callback);
+ foreach ($items as $item) { echo $item; }
+ echo "\n";
+}
+?>
+--EXPECTF--
+
+
+
+
+
+
+
+
+12
+
+
+
+
+12
+
+
+
+
+
+
+12
+
diff --git a/ext/zend_test/tests/observer_usort_internal.phpt b/ext/zend_test/tests/observer_usort_internal.phpt
new file mode 100644
index 000000000000..cf0ffb85ecaf
--- /dev/null
+++ b/ext/zend_test/tests/observer_usort_internal.phpt
@@ -0,0 +1,32 @@
+--TEST--
+Observer: native sorting callbacks retain balanced begin and end events
+--EXTENSIONS--
+zend_test
+--INI--
+zend_test.observer.enabled=1
+zend_test.observer.show_output=1
+zend_test.observer.observe_all=1
+--FILE--
+
+--EXPECTF--
+
+
+
+
+
+
+
+
+ab
+
+
+
+
+ab
+