Skip to content

Fix GH-16054: Segmentation fault when resizing hash table iterator list while adding #16060

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

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
7 changes: 6 additions & 1 deletion Zend/zend_hash.c
Original file line number Diff line number Diff line change
Expand Up @@ -2347,11 +2347,16 @@ static zend_always_inline bool zend_array_dup_element(HashTable *source, HashTab
// We need to duplicate iterators to be able to search through all copy-on-write copies to find the actually iterated HashTable and position back
static void zend_array_dup_ht_iterators(HashTable *source, HashTable *target) {
HashTableIterator *iter = EG(ht_iterators);
HashTableIterator *end = iter + EG(ht_iterators_used);
uint32_t nr_iterators_used = EG(ht_iterators_used);
HashTableIterator *end = iter + nr_iterators_used;

while (iter != end) {
if (iter->ht == source) {
size_t iter_index = iter - EG(ht_iterators);
Copy link
Member Author

Choose a reason for hiding this comment

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

Alternative idea is to use indices in the while loop, but then we have to fetch EG(ht_iterators) always in the loop body which seemed more expensive.

Copy link
Member

Choose a reason for hiding this comment

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

I think indices are going to be better.

Copy link
Member Author

Choose a reason for hiding this comment

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

Ok I have pushed a commit to do that.

uint32_t copy_idx = zend_hash_iterator_add(target, iter->pos);
/* Refetch iter and recompute end because the memory may be reallocated. */
end = EG(ht_iterators) + nr_iterators_used;
iter = &EG(ht_iterators)[iter_index];
HashTableIterator *copy_iter = EG(ht_iterators) + copy_idx;
copy_iter->next_copy = iter->next_copy;
iter->next_copy = copy_idx;
Expand Down
15 changes: 15 additions & 0 deletions ext/spl/tests/gh16054.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
--TEST--
GH-16054 (Segmentation fault when resizing hash table iterator list while adding)
--FILE--
<?php
$multi_array = ['zero'];
$multi_array[] =& $multi_array;
$it = new RecursiveTreeIterator(new RecursiveArrayIterator($multi_array), 0);
$counter = 0;
foreach ($it as $k => $v) {
if (++$counter > 200) break;
}
echo "ok\n";
?>
--EXPECT--
ok
Loading