Skip to content

Fix circumvented type check with return by ref + finally #19172

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions Zend/tests/gh18736.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
--TEST--
GH-18736: Circumvented type check with return by ref + finally
--FILE--
<?php

function &test(): int {
$x = 0;
try {
return $x;
} finally {
$x = 'test';
}
}

try {
$x = &test();
var_dump($x);
} catch (Error $e) {
echo $e->getMessage(), "\n";
}

?>
--EXPECT--
test(): Return value must be of type int, string returned
9 changes: 9 additions & 0 deletions Zend/zend_compile.c
Original file line number Diff line number Diff line change
Expand Up @@ -5703,6 +5703,15 @@ static void zend_compile_return(zend_ast *ast) /* {{{ */

zend_handle_loops_and_finally((expr_node.op_type & (IS_TMP_VAR | IS_VAR)) ? &expr_node : NULL);

/* Content of reference might have changed in finally, repeat type check. */
if (by_ref
&& !zend_stack_is_empty(&CG(loop_var_stack))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this check needed? The by_ref makes sense because that is how the type of the returned variable changes, and the is_generator and ZEND_ACC_HAS_RETURN_TYPE make sense because those are the conditions used above, but this condition (empty loop variable stack) isn't checked above - maybe add a comment about why it is needed here but not previously?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's just a fast way to check whether we're in a try. We could use zend_has_finally(), but technically even loop/switch var FREEs could change the content of the reference. It's very unlikely to matter in practice, but given return-by-ref with finally/loops should be rare enough I didn't bother optimizing this more.

&& !is_generator
&& (CG(active_op_array)->fn_flags & ZEND_ACC_HAS_RETURN_TYPE)) {
zend_emit_return_type_check(
expr_ast ? &expr_node : NULL, CG(active_op_array)->arg_info - 1, 0);
}

opline = zend_emit_op(NULL, by_ref ? ZEND_RETURN_BY_REF : ZEND_RETURN,
&expr_node, NULL);

Expand Down