Skip to content

Commit 3401d55

Browse files
authored
zend_weakrefs: Add zend_weakrefs_hash_(clean|destroy)() (#16439)
These are equivalent to `zend_hash_clean()` and `zend_hash_destroy()` respectively, but take care of correctly unregistering the weak references to the keys. This addition rounds off the weakmap functionality added in 471102e by taking one possible footgun away from the user.
1 parent 6292e5c commit 3401d55

File tree

3 files changed

+14
-5
lines changed

3 files changed

+14
-5
lines changed

Zend/zend_weakrefs.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,13 @@ ZEND_API zend_result zend_weakrefs_hash_del(HashTable *ht, zend_object *key) {
183183
return FAILURE;
184184
}
185185

186+
ZEND_API void zend_weakrefs_hash_clean(HashTable *ht) {
187+
zend_ulong obj_key;
188+
ZEND_HASH_FOREACH_NUM_KEY(ht, obj_key) {
189+
zend_weakrefs_hash_del(ht, zend_weakref_key_to_object(obj_key));
190+
} ZEND_HASH_FOREACH_END();
191+
}
192+
186193
void zend_weakrefs_init(void) {
187194
zend_hash_init(&EG(weakrefs), 8, NULL, NULL, 0);
188195
}

Zend/zend_weakrefs.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,12 @@ static zend_always_inline void *zend_weakrefs_hash_add_ptr(HashTable *ht, zend_o
4141
return NULL;
4242
}
4343
}
44+
ZEND_API void zend_weakrefs_hash_clean(HashTable *ht);
45+
static zend_always_inline void zend_weakrefs_hash_destroy(HashTable *ht) {
46+
zend_weakrefs_hash_clean(ht);
47+
ZEND_ASSERT(zend_hash_num_elements(ht) == 0);
48+
zend_hash_destroy(ht);
49+
}
4450

4551
/* Because php uses the raw numbers as a hash function, raw pointers will lead to hash collisions.
4652
* We have a guarantee that the lowest ZEND_MM_ALIGNED_OFFSET_LOG2 bits of a pointer are zero.

ext/zend_test/test.c

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1354,11 +1354,7 @@ PHP_RINIT_FUNCTION(zend_test)
13541354

13551355
PHP_RSHUTDOWN_FUNCTION(zend_test)
13561356
{
1357-
zend_ulong obj_key;
1358-
ZEND_HASH_FOREACH_NUM_KEY(&ZT_G(global_weakmap), obj_key) {
1359-
zend_weakrefs_hash_del(&ZT_G(global_weakmap), zend_weakref_key_to_object(obj_key));
1360-
} ZEND_HASH_FOREACH_END();
1361-
zend_hash_destroy(&ZT_G(global_weakmap));
1357+
zend_weakrefs_hash_destroy(&ZT_G(global_weakmap));
13621358

13631359
if (ZT_G(zend_test_heap)) {
13641360
free(ZT_G(zend_test_heap));

0 commit comments

Comments
 (0)