Skip to content
Draft
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
61 changes: 61 additions & 0 deletions Zend/tests/weakrefs/weakmap_temporary_key_by_ref.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
--TEST--
WeakMap dimension reference with a temporary key
--FILE--
<?php
$wm = new WeakMap;
try {
$r = &$wm[new stdClass];
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
var_dump(count($wm));

try {
$wm[new stdClass][] = 1;
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
var_dump(count($wm));

$key = new stdClass;
$wm[$key] = 2;
$keys = [$key];
$r = &$wm[array_pop($keys)];
$r = 3;
var_dump($wm[$key]);

$key = new stdClass;
$wm[$key] = 1;
$keys = [$key];
unset($key);
try {
$r = &$wm[array_pop($keys)];
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
var_dump(count($wm));

class K {
function __destruct() {
$GLOBALS['wm'] = null;
}
}

$wm = new WeakMap;
try {
$wm[new K][] = str_repeat("x", 10);
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
var_dump($wm);
?>
--EXPECT--
Cannot modify a WeakMap dimension using a temporary object key
int(0)
Cannot modify a WeakMap dimension using a temporary object key
int(0)
int(3)
Cannot modify a WeakMap dimension using a temporary object key
int(0)
Cannot modify a WeakMap dimension using a temporary object key
NULL
11 changes: 11 additions & 0 deletions Zend/zend_weakrefs.c
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,8 @@ static void zend_weakmap_free_obj(zend_object *object)

static zval *zend_weakmap_read_dimension(zend_object *object, zval *offset, int type, zval *rv)
{
zval *orig_offset = offset;

if (offset == NULL) {
zend_throw_error(NULL, "Cannot append to WeakMap");
return NULL;
Expand All @@ -369,6 +371,15 @@ static zval *zend_weakmap_read_dimension(zend_object *object, zval *offset, int
zend_object *obj_addr = Z_OBJ_P(offset);
zval *zv = zend_hash_index_find(&wm->ht, zend_object_to_weakref_key(obj_addr));
if (type == BP_VAR_W || type == BP_VAR_RW) {
const zend_execute_data *ex = EG(current_execute_data);
if (UNEXPECTED(GC_REFCOUNT(obj_addr) == 1)
&& ex && ex->func && ZEND_USER_CODE(ex->func->type)
&& ex->opline
&& (ex->opline->op2_type & (IS_TMP_VAR | IS_VAR))
&& orig_offset == ZEND_CALL_VAR(ex, ex->opline->op2.var)) {
zend_throw_error(NULL, "Cannot modify a WeakMap dimension using a temporary object key");
return NULL;
}
if (zv == NULL) {
zval value;
zend_weakref_register(obj_addr, ZEND_WEAKREF_ENCODE(&wm->ht, ZEND_WEAKREF_TAG_MAP));
Expand Down
Loading