Skip to content

Commit

Permalink
Fix freeing of incompletely initialized closures
Browse files Browse the repository at this point in the history
Make sure we null/initialize/addref the relevant fields before allocating any
memory.

Fixes phpGH-12073
  • Loading branch information
iluuu1994 committed Aug 29, 2023
1 parent f2c16b7 commit 7544212
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
27 changes: 27 additions & 0 deletions Zend/tests/gh12073.phpt
@@ -0,0 +1,27 @@
--TEST--
GH-12073: Fix freeing of non-ZMM pointer of incompletely allocated closure
--SKIPIF--
<?php
if (getenv("USE_ZEND_ALLOC") === "0" && getenv("USE_TRACKED_ALLOC") !== "1") {
die("skip Zend MM disabled");
}
?>
--FILE--
<?php

function test() {
$k = 1;
return function () use ($k) {
foo();
};
}

ini_set('memory_limit', '1M');

for ($i = 0; $i < 10_000; $i++) {
$$i = test();
}

?>
--EXPECTF--
Fatal error: Allowed memory size of %d bytes exhausted%s(tried to allocate %d bytes) in %s on line %d
9 changes: 5 additions & 4 deletions Zend/zend_closures.c
Expand Up @@ -689,6 +689,11 @@ static void zend_create_closure_ex(zval *res, zend_function *func, zend_class_en
closure->func.common.fn_flags |= ZEND_ACC_CLOSURE;
closure->func.common.fn_flags &= ~ZEND_ACC_IMMUTABLE;

zend_string_addref(closure->func.op_array.function_name);
if (closure->func.op_array.refcount) {
(*closure->func.op_array.refcount)++;
}

/* For fake closures, we want to reuse the static variables of the original function. */
if (!is_fake) {
if (closure->func.op_array.static_variables) {
Expand Down Expand Up @@ -736,10 +741,6 @@ static void zend_create_closure_ex(zval *res, zend_function *func, zend_class_en
}
memset(ptr, 0, func->op_array.cache_size);
}
zend_string_addref(closure->func.op_array.function_name);
if (closure->func.op_array.refcount) {
(*closure->func.op_array.refcount)++;
}
} else {
memcpy(&closure->func, func, sizeof(zend_internal_function));
closure->func.common.fn_flags |= ZEND_ACC_CLOSURE;
Expand Down

0 comments on commit 7544212

Please sign in to comment.