[php-src] PR #23566: Bound the free list walk in zend_mm_gc()
| From: | jvoisin | Date: | Fri, 04 Sep 2026 13:11:58 +0000 |
| Subject: | [php-src] PR #23566: Bound the free list walk in zend_mm_gc() | ||
| Groups: | php.git-pulls | ||
| Request: | Send a blank email to git-pulls+get-38302@lists.php.net to get a copy of this message | ||
Pull Request: https://github.com/php/php-src/pull/23566
Author: jvoisin
zend_mm_gc() counts free slots by walking each bin's free list to the end. The walk is
unbounded, and a cycle in the list makes it spin forever.
Such a cycle is easy to produce from a plain double free, as long as one other slot of the same size
class is freed in between:
efree(a); efree(b); efree(a); /* a -> b -> a */
Both links are written through zend_mm_set_next_free_slot(), so every shadow is valid and the
corruption detection added in 25360ef2495 does not apply. Neither would a check comparing the freed
pointer against the head of the list, since b is the head at the second efree(a).
gc_mem_caches() is exposed to userland, so this turns any double free into a reliable interpreter
hang. It also corrupts metadata while spinning: free_counter has no upper bound, but
ZEND_MM_SRUN_FREE_COUNTER is only 10 bits, so after 16384 iterations free_counter << 16
reaches ZEND_MM_IS_LRUN and the page map entry silently becomes an NRUN. A bailout interrupting the
loop, e.g. the execution timeout, leaves that behind.
A slot can be on a free list at most once, so the number of free slots counted for a page cannot
exceed the number of slots the page holds. Check that. This is a real invariant across repeated
collections, because the last loop of zend_mm_gc() resets the counter of every page it keeps with
ZEND_MM_SRUN(bin_num) and releases the pages that are entirely free, so counting always starts from
zero.
The check costs a compare and a branch per free slot, on a path that only runs on memory pressure or
on an explicit gc_mem_caches() call.
Verified with the sequence above: zend_mm_gc() previously never returned, and now aborts with
"zend_mm_heap corrupted". No false positives over 80 gc_mem_caches() calls spanning all 29
size classes and collecting 130MB, plus 200 object churn collections. 11327 tests pass.
The two other unbounded free list walks do not need the same treatment. zend_mm_refresh_key_child()
re-encodes with the new key as it goes, so the third visit to a cycled slot fails the old key check
and panics, which was confirmed the same way. The removal loop of zend_mm_gc() is only reached once
counting has completed, which now implies no duplicated slot.