← All reports

Ensure validity of FontRanges/GlyphPage references

HighWebCore platform/graphics —UAF

CVE: CVE-2026-112640 · Safari 27.2 · Released October 26, 2026 Impact: Processing maliciously crafted web content may lead to memory corruption Apple's description: A use-after-free issue was addressed with improved memory management. Credit: an anonymous researcher

Severity: High | Component: WebCore platform/graphics — FontCascadeFonts | 5b951ba | Bugzilla 324262

High. A font load on a worker spins a nested run loop, a purge timer shrinks the glyph cache inside it, and the suspended frame then writes into the freed bucket array. Ordinary worker APIs reach it. Turning that write into a primitive depends on reclaiming the allocation inside the window.

Text rendering resolves each character to a glyph by walking the CSS font-family list and memoizing what it finds, so that later characters on the same Unicode page skip the walk. In WebCore, the object that holds that memo for one cascade is FontCascadeFonts. It owns two caches: a vector of realized fallback families, and a hash table of glyph pages keyed by Unicode page number. A reference into either cache stays valid only while nothing that runs during the lookup can grow, shrink, or rehash the container the reference points into.

The angle: A page can start a worker that measures text against a still-downloading web font, and the renderer then writes glyph-cache state into heap memory that has already been freed. No attacker script has to run inside that window.

Source/WebCore/platform/graphics/FontCascadeFonts.cpp

+const FontRanges& FontCascadeFonts::appendRealizedFallbackRanges(FontRanges&& fontRanges)
+{
+ m_realizedFallbackRanges.append(makeUniqueRef<FontRanges>(WTF::move(fontRanges)));
+ return m_realizedFallbackRanges.last();
+}
+
const FontRanges& FontCascadeFonts::realizeFallbackRangesAt(const FontCascadeDescription& description, FontSelector* fontSelector, unsigned index)
{
if (index < m_realizedFallbackRanges.size())
@@
- m_realizedFallbackRanges.append(FontRanges());
- auto& fontRanges = m_realizedFallbackRanges.last();
+ // Build the result in a local to avoid half-initialized entries in m_realizedFallbackRanges.
+ FontRanges fontRanges;
 
if (!index) {
fontRanges = realizeNextFallback(description, m_lastRealizedFallbackIndex, fontSelector);
@@
- return fontRanges;
+ return appendRealizedFallbackRanges(WTF::move(fontRanges));
}
@@
if (fontSelectorFallbackIndex == fontSelector->fallbackFontCount())
- return fontRanges;
+ return appendRealizedFallbackRanges({ });
++m_lastRealizedFallbackIndex;
fontRanges = FontRanges(fontSelector->fallbackFontAt(description, fontSelectorFallbackIndex));
}
 
- return fontRanges;
+ return appendRealizedFallbackRanges(WTF::move(fontRanges));
}
@@ GlyphData FontCascadeFonts::glyphDataForCharacter(...)
const unsigned pageNumber = GlyphPage::pageNumberForCodePoint(c);
+ auto& cachedPages = m_cachedPages[resolvedEmojiPolicy];
+
+ auto glyphData = [&]() {
+ auto cacheEntry = cachedPages.find(pageNumber);
+ if (cacheEntry == cachedPages.end()) {
+ // We need to build the cache page. This can trigger font loading /
+ // cache changes, so build the entry on the stack, then insert.
+ GlyphPageCacheEntry newEntry { glyphPageFromFontRanges(pageNumber, realizeFallbackRangesAt(description, fontSelector, 0)) };
+ cacheEntry = cachedPages.add(pageNumber, WTF::move(newEntry)).iterator;
+ }
+ return cacheEntry->value.glyphDataForCharacter(c);
+ }();
 
- auto& cacheEntry = m_cachedPages[resolvedEmojiPolicy].ensure(pageNumber, [&] {
- // Initialize cache with a full page of glyph mappings from a single font.
- return GlyphPageCacheEntry { glyphPageFromFontRanges(pageNumber, realizeFallbackRangesAt(description, fontSelector, 0)) };
- }).iterator->value;
-
- GlyphData glyphData = cacheEntry.glyphDataForCharacter(c);
if (!glyphData.isValid()) {
// No glyph, resolve per-character.
ASSERT(variant == FontVariant::Normal);
glyphData = glyphDataForVariant(c, description, fontSelector, variant, resolvedEmojiPolicy);
- // Cache the results.
- cacheEntry.setGlyphDataForCharacter(c, glyphData);
+
+ // Since glyphDataForVariant() can itself trigger cache changes,
+ // do a fresh lookup for the cache page before storing.
+ auto cacheEntry = cachedPages.find(pageNumber);
+ if (cacheEntry != cachedPages.end() && !cacheEntry->value.glyphDataForCharacter(c).isValid())
+ cacheEntry->value.setGlyphDataForCharacter(c, glyphData);
}
 
return glyphData;

Source/WebCore/platform/graphics/FontCascadeFonts.h

- Vector<FontRanges, 1> m_realizedFallbackRanges;
- unsigned m_lastRealizedFallbackIndex { 0 };
+ // Realized ranges are held by reference across calls that can realize
+ // further fallbacks, so they are stored indirectly, and must never move.
+ // A null range indicates we reached the end of our sources.
+ Vector<UniqueRef<FontRanges>, 1> m_realizedFallbackRanges;
+ unsigned m_lastRealizedFallbackIndex { 0 }; // Index into fallback sources (specified and system).

Source/WebCore/platform/graphics/TextMeasurementCache.h

void clear()
{
- ASSERT(isMainThread());
+ if (!isMainThread())
+ return;
+
m_singleCharMap.clear();
m_map.clear();

The commit closes two dangling-reference windows in FontCascadeFonts. In both, font realization can start a font load, and that load can mutate the same object's caches.

Fallback-range storage. m_realizedFallbackRanges changes from Vector<FontRanges, 1> to Vector<UniqueRef<FontRanges>, 1>. Each realized family is now its own heap allocation. When the vector reallocates its backing store, only the owning pointers move, and the FontRanges objects stay where they are:

  Before: Vector<FontRanges, 1>           After: Vector<UniqueRef<FontRanges>, 1>
  [ FontRanges#0 ]  <- caller's ref        [ ptr0 ]──► FontRanges#0  <- caller's ref
        │ grow past inline capacity              │ grow
        ▼                                        ▼
  [ #0' | #1 ]  (old storage freed,        [ ptr0 | ptr1 ]  (ptrs move,
   caller's ref now dangles)                pointee address unchanged)

A new helper, appendRealizedFallbackRanges(FontRanges&&), wraps each entry with makeUniqueRef and returns a reference to the heap object. realizeFallbackRangesAt() no longer appends an empty placeholder and fills it through last(). It builds the result in a stack local across realizeNextFallback(), fontSelector->fontRangesForFamily(), lastResortFallbackFont() and fontSelector->fallbackFontAt(), and appends only when it returns. All three return sites go through the helper, so the vector never holds a half-built entry. That includes the end-of-sources case, which appends an empty FontRanges, and the header comment now documents that a null range marks the end. The constructor, isLoadingCustomFonts() and forEachRealizedFont() switch from . to ->. FontRanges gains WTF_MAKE_TZONE_ALLOCATED, which heap allocation through makeUniqueRef requires.

Glyph-page cache. glyphDataForCharacter() stops using HashMap::ensure() with a lambda that ran fallback realization while the table was in the middle of inserting. It also stops keeping auto& cacheEntry bound to a bucket value across a later call. The new code does three things:

  1. It builds the GlyphPageCacheEntry on the stack and only then calls cachedPages.add().
  2. It reads the initial GlyphData inside an immediately-invoked lambda, so no reference into the table outlives that lambda.
  3. After glyphDataForVariant() returns, it looks the page up again with cachedPages.find(pageNumber). It writes only if the page still exists and the character's slot is still invalid. This also respects the ASSERT(!glyphDataForCharacter(character).isValid()) precondition inside GlyphPageCacheEntry::setGlyphDataForCharacter.

Collateral. TextMeasurementCache::clear() used to ASSERT(isMainThread()). It now returns early off the main thread, which matches its add() methods. Without this, the debug-build test would trip the assertion when FontCascadeFonts::pruneSystemFallbacks() or FontCascadeCache::clearShapedTextCaches() runs on a worker. A new layout test, font-cascade-fonts-glyph-page-purge-crash.html, drives the glyph-page window from a Worker and needs ASan to report a meaningful pass/fail.

Font cascades and fallback. A font cascade is the resolved form of a CSS font-family list at a particular size and style. When the first family has no glyph for a character, the engine tries the next family, then font-selector fallbacks, then system fallback, and finally a last-resort font. FontCascadeFonts is the per-cascade object that does this walk and memoizes the results. It runs in the WebContent process on the main thread and also on worker threads, for example when a Worker measures text on an OffscreenCanvas.

FontRanges and lazy realization. FontRanges is the realized form of one family in the list: a vector of (from, to, FontAccessor) ranges. A FontAccessor is a handle that produces the actual font on demand and can start a web-font download when asked. realizeFallbackRangesAt(description, fontSelector, index) materializes the index-th fallback family on first use and memoizes it in m_realizedFallbackRanges. Callers such as glyphDataForVariant() walk this list index by index and hold the returned const FontRanges& while they realize later entries.

The glyph-page cache. Glyphs are cached per Unicode "page", a fixed-size block of code points. m_cachedPages holds one HashMap per ResolvedEmojiPolicy (the emoji-presentation mode in effect), mapping a page number to a GlyphPageCacheEntry. An entry takes one of two forms:

pruneSystemFallbacks() discards system-fallback state, and that includes the mixed-font pages.

WTF container semantics. WTF Vector<T, N> stores up to N elements inline. When it grows past capacity it moves every element into new storage, so references to elements do not survive growth. WTF HashMap is open-addressing, meaning values live directly in the bucket array. That array is reallocated both when the table grows and when it shrinks (a rehash), so references and iterators into it do not survive insertion or removal. UniqueRef<T> is a non-null owning pointer: where the UniqueRef is stored has no effect on the address of the object it owns.

Workers, synchronous loads, and nested run loops. Workers expose self.fonts (a FontFaceSet) and OffscreenCanvas, so worker script can trigger font fallback and text measurement. Some worker resource loads are synchronous. The worker thread blocks inside a nested run loop until the main thread delivers the response, and timers scheduled on that run loop can fire during the wait. FontCache maintains a purge timer of this kind, which evicts inactive font data.

This is a use-after-free caused by a reference into a rehashable container held across a re-entrant callout. Here the callout is a synchronous font load, and the code that re-enters is a timer.

  Worker frame: glyphDataForCharacter()     Nested run loop (same worker thread)
  ─────────────────────────────────────     ───────────────────────────────────
  cacheEntry = &bucket[page(U+13A0)]
  miss → glyphDataForVariant()
    └─► walk cascade → PendingFam
          └─► loadResourceSynchronously() ─► FontCache purge timer fires
                                              └─► pruneSystemFallbacks()
                                                    ├─► drop mixed-font pages
                                                    └─► shrink → rehash()
                                                        frees old bucket array
  ◄─ load returns, frame resumes
  cacheEntry.setGlyphDataForCharacter()  ✗  write into freed bucket array

In the left column, the old glyphDataForCharacter() binds auto& cacheEntry to the GlyphPageCacheEntry that sits inside a bucket of m_cachedPages[resolvedEmojiPolicy]. On a glyph miss it calls glyphDataForVariant(), intending to write the result back through that same reference. The code assumes that resolving one character cannot change the table that the character's page lives in.

The arrow across the columns is where that assumption fails. glyphDataForVariant() walks the fallback cascade and can reach a downloadable @font-face that is still pending. On a worker, that load goes through WorkerThreadableLoader::loadResourceSynchronously and spins a nested run loop. The FontCache purge timer can fire inside that loop and call pruneSystemFallbacks() on the same FontCascadeFonts. Once enough mixed-font pages are removed, the HashMap drops below its shrink threshold and rehash() frees the bucket array. When the load returns, the suspended frame calls setGlyphDataForCharacter() through cacheEntry, which now points into freed memory. The test describes it directly: "The fault is a write into the freed bucket array."

None of this requires author script inside the window, which is why the test says the bug is "independent of the reentrancy mitigations in CSSFontFace/DeferredPromise". The regression test builds the window deterministically from ordinary web APIs:

  1. A Worker adds a FontFace('PendingFam', ...) to self.fonts. Its source is a data: URL over a megabyte long, so opportunisticallyStartFontDataURLLoading() won't pre-warm it, and unicodeRange: 'U+13A0' keeps it out of earlier walks.
  2. The worker churns OffscreenCanvas measureText calls across many (family, size) pairs. Each fontForFamily() arms the purge timer, and overflowing the FontCascadeCache makes enough fonts inactive that purgeInactiveFontDataIfNeeded() will actually purge.
  3. A victim context with font = '10px Times, PendingFam' measures twelve ideographs, each on its own glyph page. None are covered by Times, so each resolves through system fallback. The result is twelve mixed-font entries that pruneSystemFallbacks() will drop, which is enough to push the table under its shrink threshold.
  4. The worker drops a large object graph to arm JSC heap timers. This gives the nested run loop a deadline, so its wait times out and fires the shared timer.
  5. The worker posts 'hold', and the main thread busy-waits for 1.8 s so it cannot service the load request.
  6. measureText('\u13A0') binds the cache entry for that page, misses in Times, and walks down to PendingFam. Its synchronous load opens the window shown in the diagram.

The original ensure() call had a related hazard. Its factory lambda ran realizeFallbackRangesAt(), which can also start loads, while HashMap::ensure was partway through inserting into the same table. The bucket for pageNumber was already visible before its value existed.

The second instance has the same shape in the fallback-range vector. The old realizeFallbackRangesAt() appended an empty FontRanges to Vector<FontRanges, 1>, took auto& fontRanges = m_realizedFallbackRanges.last(), and then assigned into it from realizeNextFallback() or fontSelector->fontRangesForFamily(). Both of those can load fonts. If the load path realized more fallback ranges on the same object, the vector, whose inline capacity is one, could grow and move its storage. The pending assignment would then write into the old storage, and the const FontRanges& returned to the caller would dangle. Any caller holding an earlier realizeFallbackRangesAt() result across a later realization was exposed the same way. The new header comment confirms callers rely on that pattern: ranges "are held by reference across calls that can realize further fallbacks, so they are stored indirectly, and must never move." The empty placeholder also exposed a half-initialized entry to re-entrant readers such as isLoadingCustomFonts() and forEachRealizedFont().

On the glyph-page side, the write is a heap UAF against a freed WTF HashMap bucket array, limited to one GlyphPageCacheEntry-sized slot. On the stale entry, setGlyphDataForCharacter does the following:

Those operations are where the ceiling could rise above a fixed-slot write. If the freed bucket were reclaimed with attacker-influenced contents, releasing a stale RefPtr<GlyphPage> could act as a decrement on a controlled pointer, and following a stale m_mixedFont could act as a write through a controlled pointer. Both depend on reclaiming the freed allocation inside the nested-run-loop window, and the diff does not establish that control. The Vector<FontRanges> instance would be a similar stale-write / stale-read class against the old vector backing store. Its elements are FontRanges objects holding Ref<FontAccessor> members, so if that path were reached it could expose refcount operations on stale pointers.

On non-ASan builds the confirmed effect is silent, and the test prints its pass text either way. All of this stays in the WebContent process, including its worker threads. Impact beyond the renderer would need a separate sandbox escape.

The fix restores the invariant in three ways:

A reference into m_cachedPages was held across a font load whose nested run loop let a purge timer shrink and rehash that same table, so the write-back landed in freed buckets.

The re-entrancy here has no JavaScript in it. The window is opened by a synchronous resource load on a worker thread, which spins a nested run loop, together with a cache-maintenance timer that fires inside that loop. An audit that only looks for points where author callbacks can run, and the CSSFontFace/DeferredPromise mitigations built around such callbacks, will miss this shape entirely. Function names such as realizeFallbackRangesAt and glyphPageFromFontRanges read like pure lookups, yet any of them can reach a load. Before this fix, the "must never move" header comment captured an invariant that existed only in how callers behaved.