From 97ee5bd0ca1d26e282fd40d3f8dc4e645fa2f36f Mon Sep 17 00:00:00 2001 From: Ilia Alshanetsky Date: Fri, 25 Sep 2026 02:15:47 -0400 Subject: [PATCH] Zend: Reset extended_value of FREE synthesized by DCE DCE rewrites a dead instruction whose operand still needs freeing into a FREE, but kept the instruction's extended_value. After (float) and (array) casts and empty() it has bit 0 set, which ZEND_HANDLE_EXCEPTION reads as ZEND_FREE_ON_RETURN: when a destructor run by that FREE throws, the throw point moves by the FREE's op2, which is (uint32_t)-1, and cleanup_live_vars() frees the operand a second time. --- NEWS | 2 ++ Zend/Optimizer/dce.c | 1 + ext/opcache/tests/opt/dce_029.phpt | 51 ++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+) create mode 100644 ext/opcache/tests/opt/dce_029.phpt diff --git a/NEWS b/NEWS index 8fe84a4176dc..62eb4bf99656 100644 --- a/NEWS +++ b/NEWS @@ -163,6 +163,8 @@ PHP NEWS . Fixed function JIT ASSIGN_DIM reporting an undefined value or key out of order, or when the VM does not, on non-array containers. (Jorg Sowa) . Fix JIT register allocation for ASSIGN to traced reference. (ndossche) + . Fixed a double free when a destructor throws while freeing a temporary + whose result the optimizer discarded. (Ilia Alshanetsky) - PDO_Firebird: . Fixed stack buffer overflow with long connection user names, passwords, diff --git a/Zend/Optimizer/dce.c b/Zend/Optimizer/dce.c index 414abe01f96a..88164671af86 100644 --- a/Zend/Optimizer/dce.c +++ b/Zend/Optimizer/dce.c @@ -454,6 +454,7 @@ static bool dce_instr(context *ctx, zend_op *opline, zend_ssa_op *ssa_op) { opline->opcode = ZEND_FREE; opline->op1.var = EX_NUM_TO_VAR(ssa->vars[free_var].var); opline->op1_type = free_var_type; + opline->extended_value = 0; ssa_op->op1_use = free_var; ssa_op->op1_use_chain = ssa->vars[free_var].use_chain; diff --git a/ext/opcache/tests/opt/dce_029.phpt b/ext/opcache/tests/opt/dce_029.phpt new file mode 100644 index 000000000000..17ab173e1a93 --- /dev/null +++ b/ext/opcache/tests/opt/dce_029.phpt @@ -0,0 +1,51 @@ +--TEST-- +DCE must not keep the replaced instruction's extended_value on a synthesized FREE +--INI-- +opcache.enable=1 +opcache.enable_cli=1 +opcache.optimization_level=-1 +opcache.file_update_protection=0 +opcache.jit=disable +--EXTENSIONS-- +opcache +--FILE-- +a = [new D]; + } + + public function clobber(): int { + $this->a = []; + return 0; + } + + public function test() { + empty(($this->a ?? [])[$this->clobber()]); + } +} + +$c = new C; +try { + $c->test(); +} catch (Exception $e) { + echo $e::class, ": ", $e->getMessage(), "\n"; +} + +$a = []; +for ($i = 0; $i < 10; $i++) { + $a[] = [$i]; +} +echo count($a), "\n"; +?> +--EXPECT-- +Exception: dtor +10