From 2ff496e871aabe7f16179294078fbc9de4ce0d5b Mon Sep 17 00:00:00 2001 From: Nikita Popov Date: Fri, 20 Aug 2021 15:37:46 +0200 Subject: [PATCH] Handle resource table reallocation during shutdown New resources may be created while closing resources during shutdown. This may result in a reallocation of arData and use after free. This problem was exposed by 7f7a90b2bc301ba275ec2c606d78f9223e84d48f, which creates one resources less, and thus moved the reallocation to shutdown for a number of existing tests. However, the general problem already existed previously. We don't try to also close the newly added resources -- we will later perform a graceful reverse destroy of the table, which will catch any remaining cases. --- Zend/zend_list.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/Zend/zend_list.c b/Zend/zend_list.c index bacdd739e6f..055ba1a2893 100644 --- a/Zend/zend_list.c +++ b/Zend/zend_list.c @@ -213,13 +213,17 @@ void zend_init_rsrc_plist(void) void zend_close_rsrc_list(HashTable *ht) { - zend_resource *res; - - ZEND_HASH_REVERSE_FOREACH_PTR(ht, res) { - if (res->type >= 0) { - zend_resource_dtor(res); + /* Reload ht->arData on each iteration, as it may be reallocated. */ + uint32_t i = ht->nNumUsed; + while (i-- > 0) { + Bucket *p = &ht->arData[i]; + if (Z_TYPE(p->val) != IS_UNDEF) { + zend_resource *res = Z_PTR(p->val); + if (res->type >= 0) { + zend_resource_dtor(res); + } } - } ZEND_HASH_FOREACH_END(); + } }