Ensure validity of FontRanges/GlyphPage references
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
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
Source/WebCore/platform/graphics/FontCascadeFonts.h
Source/WebCore/platform/graphics/TextMeasurementCache.h
Patch Details
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:
- It builds the
GlyphPageCacheEntryon the stack and only then callscachedPages.add(). - It reads the initial
GlyphDatainside an immediately-invoked lambda, so no reference into the table outlives that lambda. - After
glyphDataForVariant()returns, it looks the page up again withcachedPages.find(pageNumber). It writes only if the page still exists and the character's slot is still invalid. This also respects theASSERT(!glyphDataForCharacter(character).isValid())precondition insideGlyphPageCacheEntry::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.
Background
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:
- a single-font
GlyphPage, held asRefPtr<GlyphPage> m_singleFont; - a heap-allocated
MixedFontGlyphPage, held as astd::unique_ptr, used once individual characters on the page have been resolved through fallback.
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.
Analysis
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:
- A Worker adds a
FontFace('PendingFam', ...)toself.fonts. Its source is adata:URL over a megabyte long, soopportunisticallyStartFontDataURLLoading()won't pre-warm it, andunicodeRange: 'U+13A0'keeps it out of earlier walks. - The worker churns
OffscreenCanvasmeasureTextcalls across many (family, size) pairs. EachfontForFamily()arms the purge timer, and overflowing theFontCascadeCachemakes enough fonts inactive thatpurgeInactiveFontDataIfNeeded()will actually purge. - 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 thatpruneSystemFallbacks()will drop, which is enough to push the table under its shrink threshold. - 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.
- The worker posts
'hold', and the main thread busy-waits for 1.8 s so it cannot service the load request. measureText('\u13A0')binds the cache entry for that page, misses in Times, and walks down toPendingFam. 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:
- It reads
m_mixedFont. If that is null, it allocates aMixedFontGlyphPage, stores the pointer, and nullsm_singleFont. - It then calls
m_mixedFont->setGlyphDataForCharacter, which writes a glyph index and aSingleThreadWeakPtr<const Font>into the page that pointer refers to.
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:
- No reference into the table survives the callout. The initial read happens inside a lambda that returns by value. The write-back starts from a fresh
find()and is skipped if the page was pruned or the slot was filled re-entrantly. - Nothing is visible in the table before it is fully built. Both the glyph page and the
FontRangesare constructed off-container and then inserted. - References to fallback ranges are stable by construction.
UniqueRefmakes eachFontRangesaddress independent of the vector's storage.
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.
Insight
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.
Audit directions
-
References into WTF
HashMap/Vectorstorage held across a call that can reach resource loading. The invariant: no element reference survives a callout unless that callout provably cannot touch the container. Narrow: inSource/WebCore/platform/graphics(FontCache.cpp, FontCascadeFonts.cpp,GlyphPageusers, ComplexTextController), grep for.ensure(whose functor callsrealize*,fontForFamily,fontRangesForFamilyorglyphData*. Also look forauto& x = ...last()or->valuebindings followed by such calls. Wider: anyensure/addfactory functor with side effects on its own table, or aHashMap::finditerator kept across a function that can prune the map. Check the CSSFontFace/CSSFontSelector caches andTextMeasurementCacheusers. Widest: this is the iterator-invalidation-across-reentrancy class. It recurs in LLVMDenseMap(references invalidated by insertion inside a lookup-or-create helper), instd::unordered_map::try_emplacewith side-effecting value construction, and in Chromium'sbase::flat_map. Rust's borrow checker rejects it statically. Match tell: a container element reference bound before, and dereferenced after, any call whose transitive callees can insert into or erase from the same container. -
Synchronous worker loads as hidden re-entrancy points. Trace
WorkerThreadableLoader::loadResourceSynchronouslyand its callers in the font and CSS loading paths. For each, ask which timers can fire during the nested run loop and which caches those timers mutate. Narrow: enumerateFontCachepurge and memory-pressure callbacks such aspurgeInactiveFontDataIfNeededandpruneSystemFallbacks. Check every frame that can be suspended under a worker font load for live references into the structures those callbacks prune. Wider: the same applies toimportScripts, sync XHR in workers, and any other nested-run-loop wait, where JSC heap timers, GC finalizers and cache-trim timers all run inside the window. Widest: nested event loops are re-entrancy points in any GUI or runtime that pumps messages inside a blocking call: Win32 modal loops, GLib nested main loops, CocoarunModal, Node's deprecateddeasync. Match tell: a native frame that caches state and then calls something that waits on I/O by pumping the loop instead of truly blocking. -
Lookup-or-create code that publishes a placeholder before the value is built. The old
realizeFallbackRangesAtappended an emptyFontRangesfirst, and the oldensureinserted a bucket before its factory ran, so re-entrant readers could see half-initialized entries. Narrow: search WebCore font and style caches forappend(T())oradd(key, { })followed by population through a reference. Wider: memoization tables in CSS style resolution, image decoder caches andSVGResourcesCacheshare the same shape. Widest: this is the general publish-before-initialize class. It also shows up in lazy-init singletons and in compiler memo tables (for example, re-entrant type interning), where a recursive query observes a sentinel entry. Match tell: the key becomes visible in the container strictly before the code that computes its value returns.