[1] Canvas 2D FontProxy use-after-free via thenable re-entrancy in measureText()
measureText() keeps running on a font object your promise getter just freed.
High. Ordinary page script frees the heap buffer underneath a font call that is still executing on it, through both <canvas> and OffscreenCanvas. Getting past a crash depends on reclaiming that buffer before the resumed font code reads pointer-typed members.
Canvas text rendering keeps a save/restore stack of drawing states, and each state carries the font used to measure and draw text. That font lives in a FontProxy, an internal wrapper around the resolved FontCascade (the font plus its fallback chain) that is notified when web fonts finish loading. Text APIs assume the font object they are calling into stays at a fixed address for the whole call.
The angle: any page that can call measureText() can, from inside a promise getter, grow the canvas state stack and free the heap buffer holding the font object that measurement is still running on.
Make CanvasRenderingContext2DBase::FontProxy ref-counted
CanvasRenderingContext2DBase::fontProxy()returns a raw pointer to theFontProxyof the current state. If the state stack is changed between the call and the use of that pointer, the pointer can refer to a freedFontProxy, because pushing a state can reallocate the stack's buffer. 320073@main tried to fix this by auditing everyfontProxy()call site and fetching a fresh pointer each time. There is still a way to invalidate the pointer while it is in use.FontProxy::metricsOfPrimaryFont()can trigger font loading, and a loaded font can resolve a JS promise. That promise can callsave()on the context. If enough states are saved, the stack reallocates and theFontProxyrunningmetricsOfPrimaryFont()is freed. When the promise returns,metricsOfPrimaryFont()continues on freed memory.The only fix is to make
FontProxyref-counted so it can be kept alive during operations. Callers offontProxy()now protect it before use. A savedStatewould otherwise share the sameFontProxythrough itsRef<>, soStategets a custom clone that value-clones the proxy. Each saved state keeps its own copy, as before. Copy-on-write is left as future work.
Source/WebCore/html/canvas/CanvasRenderingContext2DBase.h
Source/WebCore/html/canvas/CanvasRenderingContext2DBase.cpp
LayoutTests/fast/canvas/offscreen-canvas2d-measuretext-uaf.html
Patch Details
The change moves FontProxy out of each State into its own refcounted heap allocation, changes the save path to deep-clone that allocation so saved states stay independent, and pins the proxy with a strong reference at every caller that uses it across further font calls.
On the ownership side, FontProxy now derives from RefCounted<FontProxy> alongside FontSelectorClient and gains static Ref<FontProxy> create() and Ref<FontProxy> clone() const. Its default constructor, copy constructor and copy assignment become private. State::font changes from FontProxy to Ref<FontProxy>, and both CanvasRenderingContext2D::fontProxy() and OffscreenCanvasRenderingContext2D::fontProxy() now return state().font.ptr().
On the cloning side, State gets a custom clone() that copies the struct and then replaces the font with protect(this->font)->clone(). A FIXME notes copy-on-write as future work. State's copy constructor becomes private, move operations are explicitly defaulted, and realizeSavesLoop() appends state().clone() instead of a plain copy.
On the caller side, measureTextInternal, drawTextUnchecked, setLetterSpacing and setWordSpacing replace auto* fontProxy (or repeated fontProxy() calls) with RefPtr fontProxy. drawTextUnchecked also hoists one CheckedRef to the FontCascade. One-shot uses in canDrawText, the setFont*/setTextRendering/setLang setters, textOffset, setFontWithoutUpdatingStyle, OffscreenCanvasRenderingContext2D::setFont, and the State::canvasFont*()/fontString() getters are wrapped in protect(...). NODELETE is removed from all eight State const getters, including canvasLineCap, canvasLineJoin, canvasTextAlign and canvasTextBaseline, which do not touch the font; the commit gives no reason for those four. Four regression tests (canvas2d-measuretext-{uaf,null-deref} and their offscreen- twins) install a then getter on FontFace.prototype that calls save() and sets lineWidth during measureText().
Pointer into an element of a growable container held across a script re-entrancy point that can reallocate the container, including the implicit this of a method running on that element.
Background
Canvas state stack.
save() pushes a copy of the current drawing state (transform, styles, line width, font) and restore() pops it. WebKit defers the push: save() only increments m_unrealizedSaveCount, and the copies are materialized by realizeSaves()/realizeSavesLoop() the first time a state-mutating setter such as lineWidth runs.
Vector<State, 1> storage.
m_stateStack is a WTF Vector with one inline slot inside the owning context, spilling to a heap buffer once it grows past that. When a WTF Vector outgrows its capacity, it allocates a larger buffer, moves every element across, destroys the old elements, and frees the old heap buffer.
FontProxy and the Font Loading API.
FontProxy wraps the context's FontCascade and registers as a FontSelectorClient, so it hears when web fonts finish loading. measureText() asks it for widths and primary-font metrics. A FontFace added to document.fonts can be named in context.font, and its loaded promise resolves with the FontFace itself once loading completes.
Thenable assimilation.
When a promise is resolved with an object, the engine synchronously performs Get(value, "then") to see whether the value is itself a thenable. Any getter defined for then on the object or its prototype runs at that moment, inside whatever native frame performed the resolution.
Ref, RefPtr and protect().
WebKit's reference-counting smart pointers. A Ref/RefPtr local keeps its target alive until the local leaves scope; protect(x) yields a temporary strong reference.
Analysis
This is a use-after-free caused by a pointer into a reallocatable container surviving a script re-entrancy point.
measureTextInternal() FontFace.prototype.then getter
--------------------- ------------------------------
fontProxy = &state().font
(raw ptr into m_stateStack buffer)
font call -> pending web font loads
-> FontFace.loaded resolves
-> Get(FontFace, "then") ---> save() x N; lineWidth = ...
realizeSavesLoop()
m_stateStack grows:
move States, ~FontProxy,
free old buffer
font call resumes <-------------------- return
this / fontProxy ==> freed buffer
In the left column, measureTextInternal takes a raw fontProxy and makes several font calls through it: the width computation on its FontCascade, emHeightAscentAndDescent(protect(fontProxy->fontCascade())) (also reached through textOffset), and fontProxy->metricsOfPrimaryFont(). Per the test comment, measuring requests metrics, which forces the pending MyTestFam face to load, and completing the load resolves FontFace.loaded. The test comment is the basis for the resolution happening synchronously inside one of those font calls; which call hosts the re-entry is not pinned down by the source, but the test's wording about measureText fetching metrics "from a freed FontCascade" points to a FontCascade method's this, or the enclosing FontProxy, as the stale receiver.
Thenable assimilation fires the getter in the right column. save() only bumps the unrealized count; the lineWidth assignment then realizes the saves (the test comment "Set line width to ensure new states are created" implies this), so realizeSavesLoop() appends states until the vector exceeds capacity. The reallocation destroys every old State, running ~FontProxy, and frees the old buffer. When the getter returns, the font call in progress, and any later use of the raw local, resume on destroyed or freed memory.
The invariant that broke was never written down: the stack must not reallocate, and the current state must not be destroyed, while that pointer or the this of a method running on it is live. 320073@main enforced it at call sites by fetching fresh pointers. Call-site discipline cannot help when the invalidated pointer is the receiver of the very method that re-enters.
The two test variants differ in where the stale pointer lands:
-uaftests. Onesave()plus alineWidthset moves the stack off the inline slot onto the heap (the test says so in a comment). The 18 saves inside the getter then grow that heap buffer, so the old buffer is freed and the stale pointer targets freed heap memory.-null-dereftests. No prior save, so the first growth moves the stack out of the inline slot. The inline storage is not freed, but theStateandFontProxythere have been moved from and destroyed. The test naming and the inline capacity ofVector<State, 1>suggest the resumed call then reads moved-from or destructed members that are null; confirming this requires the~FontProxybody andFontProxy's move semantics.
Exploitability is a web-reachable UAF from plain JavaScript on the main thread, and the regression tests show a reliable crash. The freed allocation is the whole state-stack buffer, and the number of save() calls steers its capacity, so its size class is plausibly attacker-influenced. If the freed buffer were reclaimed with controlled contents between the free and the resumed call, the stale reads could consume attacker-shaped pointer fields from the embedded FontCascade, which would make this a fake-object or control-flow candidate rather than just a crash. The candidates to establish are pointer-typed or virtually dispatched members read after the getter returns: the FontCascade's fonts reference and the FontSelectorClient vtable of FontProxy. The inline-storage variant likely tops out at a null dereference. Whether the same trigger is reachable from OffscreenCanvas inside a worker is not established; the four tests run on the main thread.
Before the fix, this vulnerability weakened memory safety in the WebContent renderer. The text pipeline assumed the font object behind fontProxy() stays alive while a method runs on it, and ordinary web script could break that from a promise-thenable getter, through both HTMLCanvasElement and OffscreenCanvas contexts. If the freed memory were reclaimed with attacker-shaped data, this could serve as a renderer-plane memory-corruption foothold. Escaping the WebContent sandbox would still require a separate bug.
Insight: The pre-patch code already knew about re-entrancy here. measureTextInternal carried the comment "Bind the primary font's metrics only after width() has run, since it can rebuild the font cache" (that reordering is fix [3] below), and CanvasRenderingContext2D::fontProxy() wraps realization in a ScriptDisallowedScope. Both are local, ordering-based mitigations, and the scope only covers realization, not the later font calls where script actually runs. The durable fix changes the ownership model: once the proxy is a refcounted heap object, a Vector reallocation moves Ref handles and never destroys the proxy in use.
Audit directions
- Container element addresses held across script re-entrancy. The invariant is that no address into a reallocatable buffer may survive a script re-entrancy point, where the container's owner exposes a script-triggerable push. Narrow: grep
CanvasRenderingContext2DBasefor other accessors returning references intom_stateStack(state(),stateStack(), andLIFETIME_BOUNDgetters such asgetLineDash()), and check whether any reference is held across style resolution, image decode, or font loading. Wider: the same shape appears with WTFHashMaprehash andVectorgrowth anywhere in WebCore where the stored element is a non-refcounted value held by reference across event dispatch or promise resolution. Widest: this is general iterator/reference invalidation, the class Rust's borrow checker forbids statically; it applies tostd::vector/absl::flat_hash_mapusers in Chromium/Blink and to any C++ engine embedding a scripting runtime. Match tell: aT&orT*fromcontainer[i]orcontainer.last()still in use after a call whose callee can run script, while the container's owner exposes a script-reachableappendoradd. - Promise resolution with a platform object as a hidden script entry. Check every place where WebCore resolves a promise with a platform object (FontFace
loaded,FontFaceSet.ready, imagedecode(), WebCodecs, media) while the native caller still holds unprotected state; thenable assimilation runs userthengetters before resolution returns. Narrow: trace callers ofDeferredPromise::resolvereached synchronously from layout, font, or canvas paths, and confirm the frames above them useRef/RefPtrrather than raw pointers. Wider: any notification fan-out (FontSelectorClient::fontsNeedUpdate, observers, load callbacks) that can end in promise resolution inherits the hazard. Widest: every JS-engine embedder (Blink'sScriptPromiseResolver, Gecko'sPromise::MaybeResolve, Node native addons) has this hidden re-entrancy. Match tell: a native frame that resolves, or transitively triggers resolution of, a promise whose value is a script-visible object, then keeps using cached native state without re-validating it. - Methods on by-value container elements that call out to script. Audit methods on objects stored by value inside script-mutable containers whose bodies can reach script, where the dangling pointer is the method's own
this; fetching a fresh pointer at each call site cannot protectthis. Narrow: inspect the other value-embeddedFontSelectorClientimplementations and the otherCanvasRenderingContext2DBase::Statemembers (CanvasStyle,targetSwitcher) for methods that may trigger loads or style updates. Wider:Ref protectedThis { *this }only works for refcounted types, so search for non-refcounted classes held inVector/HashMapvalues that expose methods reachingDocument::updateStyleIfNeeded, resource loading, or event dispatch. Widest: Gecko'skungFuDeathGripand Chromium's self-scoped_refptrpinning express the same principle; a re-entering method must be able to keep its receiver alive, which is impossible if the receiver's storage belongs to a container the callee can resize. Match tell: a class without refcounting, used as a container element type, with at least one method whose call graph reaches script execution. - Re-entrancy guards that cover acquisition, not use. Review
ScriptDisallowedScopeplacements to see whether they cover the actual re-entrant window or only the acquisition step; here the scope inCanvasRenderingContext2D::fontProxy()guarded realization while the script-reachable font calls came later. Narrow: grepScriptDisallowedScopeinSource/WebCore/html/canvasandSource/WebCore/css, and check whether the guarded function returns a raw pointer used after the scope ends. Wider: the same mismatch applies toNoEventDispatchAssertionand other scoped assertions wrapping getters rather than consumers. This class is tied to WebKit's scoped script-disallow idiom; Blink'sScriptForbiddenScopeshould be checked the same way. Match tell: a scope guard declared inside a function that returns a pointer or reference, where the risky use happens in the caller after the guard is destroyed.