CSSStyleSheet::forEachStyleScope: iterate through a copy of m_adoptingTreeScopes
CVE: CVE-2026-112697 · Safari 27.2 · Released October 26, 2026 Impact: Processing maliciously crafted web content may lead to arbitrary code execution Apple's description: A use-after-free issue was addressed with improved memory management. Credit: OpenAI Codex Security - Amy Burnett, 은태 장
High. A style fan-out loop walked a live hash set while running a callback that can edit that same set, which is the textbook stale-iterator shape. Any page that shares one constructable sheet across shadow roots can reach it. Getting past a crash depends on reclaiming the freed bucket array.
Constructable stylesheets let script build a sheet once and attach it to the document and to any number of shadow roots through adoptedStyleSheets, so one sheet can feed style into many trees at once. Inside WebCore, CSSStyleSheet records those adopters in a set named m_adoptingTreeScopes. Its forEachStyleScope() helper fans each sheet mutation out to every adopter's Style::Scope so the affected trees get invalidated. The fan-out passes control to a caller-supplied callback in the middle of iteration, and its safety depends on one invariant: nothing the callback does may insert into or remove from the set being walked.
The angle: A page that shares one stylesheet across several shadow roots could push the style fan-out into continuing over freed hash-table memory, which gives a use-after-free inside the renderer.
Source/WebCore/css/CSSStyleSheet.cpp
Patch Details
The change touches one function, CSSStyleSheet::forEachStyleScope in Source/WebCore/css/CSSStyleSheet.cpp. The function has two paths:
- Single-owner path (unchanged). If the sheet has a single owning
m_styleScope, the function callsapply(*scope)and returns. Sheets that come from<style>or<link>elements take this path. - Adopted path (rewritten). If no single owner exists, which is the normal case for a constructable sheet adopted by several trees, the function iterates
m_adoptingTreeScopes. It resolves each entry to itsStyle::ScopethroughstyleScopeFor()and callsapplyon it.
Before the patch, the adopted path iterated the hash set directly with for (Ref treeScope : m_adoptingTreeScopes). After the patch, it first takes a snapshot with copyToVectorOf<Ref<ContainerNode>>(m_adoptingTreeScopes) and iterates the resulting Vector.
The single line has two separate effects:
- No live hash-set iterator while
applyruns. The loop now walks aVectorthat exists only for the duration of this call. Callback code that adds or removes adopting tree scopes changesm_adoptingTreeScopes, but the loop never reads from it again after the copy. - Every adopter is strongly held for the whole loop. The old loop built one
Refper iteration, so only the tree scope currently being visited was protected. The snapshot's element type isRef<ContainerNode>, so every adoptingDocumentandShadowRootis kept alive from before the firstapplyuntil after the last one.
The styleScopeFor helper and the protect(...) wrapper around its result are unchanged. The fix changes only what the loop iterates over and how long the elements live.
Background
Constructable stylesheets and adoption.
new CSSStyleSheet() creates a stylesheet that has no owner node: no <style> element and no <link>. Script attaches it to a tree by assigning document.adoptedStyleSheets or shadowRoot.adoptedStyleSheets. One sheet object can appear in the adopted list of many tree scopes at once, and editing its rules affects all of them.
Tree scopes and Style::Scope.
A tree scope is the root of an independently styled DOM tree: the Document itself, or a ShadowRoot attached to an element. Both derive from ContainerNode, WebCore's base class for nodes that can have children. Each tree scope has a Style::Scope. This is the per-tree object that tracks which stylesheets are active in that tree and drives style invalidation and style-resolver rebuilds when they change. styleScopeFor() maps a tree scope to its Style::Scope through ShadowRoot::styleScope() or Document::styleScope().
Adopter bookkeeping in CSSStyleSheet.
Because an adopted sheet has no single owner, CSSStyleSheet keeps m_adoptingTreeScopes, the set of every tree scope that has adopted it. Entries are added and removed as adoptedStyleSheets assignments change. forEachStyleScope() is the fan-out primitive that sheet-mutation paths use to reach every adopter's Style::Scope with a caller-supplied lambda, the apply parameter.
WTF hash containers.
WTF is WebKit's internal template library. Its HashSet and WeakHashSet use open addressing: entries are stored directly in a contiguous bucket array, with no per-entry nodes. An iterator over these containers is essentially a pointer into that bucket array. Inserting can grow the table and rehash it into a new allocation, and removing can shrink it the same way. Both release the old bucket array. WeakHashSet holds weak references that do not keep their targets alive, and it periodically prunes entries whose targets have died. Pruning also restructures the table.
Ref, protect, and copyToVectorOf.
Ref<T> is WebKit's non-null, strongly owning smart pointer; it keeps the object alive until the Ref goes away. protect(...) wraps a reference in a temporary strong ref for the duration of the expression. copyToVectorOf<T>(collection) is a WTF helper that copies a collection into a fresh Vector<T>. With T = Ref<ContainerNode>, each element is strongly retained by the vector.
Analysis
This is a re-entrancy iterator-invalidation bug: a callback invoked inside a range-for over a WTF hash set can mutate that set, and the loop then advances an iterator into freed or stale bucket storage.
forEachStyleScope (pre-fix) apply() callback
─────────────────────────── ───────────────────────────────
it = m_adoptingTreeScopes.begin()
Ref treeScope = *it ── scope A ──► Style::Scope work for A
└─► adopter bookkeeping (candidate)
add/remove on m_adoptingTreeScopes
└─► rehash/shrink: old buckets freed
++it ◄── returns ──
*it ──► reads freed bucket array ◄══ FAILURE WINDOW
styleScopeFor(stale ContainerNode&) ──► apply(...) on garbage scope
In the left column, the loop holds a single iterator: a pointer into m_adoptingTreeScopes' bucket array. While it holds that pointer, the loop calls apply, the right column. That lambda is arbitrary sheet-mutation work, such as invalidation or resolver updates on the adopter's Style::Scope. The commit message states that apply can modify the hash set itself. The message does not say which path does this. The natural candidate is the adopter bookkeeping, the addAdoptingTreeScope/removeAdoptingTreeScope-style calls made when adoptedStyleSheets changes or when a ShadowRoot that adopted the sheet is torn down. Once the right column reallocates the table, control returns to ++it in the left column, which now points into memory the set no longer owns.
The C++ desugaring of the old range-for shows the shape of the hazard:
// for (Ref treeScope : m_adoptingTreeScopes) is equivalent to:
auto it = m_adoptingTreeScopes.begin();
auto end = m_adoptingTreeScopes.end(); // captured once, before any apply()
for (; it != end; ++it) {
Ref treeScope = *it; // only the *current* element is retained
apply(protect(styleScopeFor(treeScope)));
}
Both it and end are computed from the bucket array that exists before the first callback. Nothing in the loop re-reads the container after a mutation, so a rehash inside apply leaves both iterators pointing at freed storage. The next dereference yields whatever now occupies that memory, and that value is reinterpreted as a ContainerNode&.
The Ref treeScope = *it line also shows a second, lifetime hazard. The element type of m_adoptingTreeScopes is declared in CSSStyleSheet.h. The fix's copyToVectorOf<Ref<ContainerNode>> shows the elements convert to ContainerNode&, which makes it likely a weak set of ContainerNode. If it is a WeakHashSet, the old loop strongly held only the element currently being visited, while every later adopter stayed weakly held. Work in apply on scope A that destroys scope B would then leave a null or pruned entry where B used to be. Because WeakHashSet prunes dead entries during mutation, that pruning is itself another rehash trigger, which feeds back into the iterator path above. In that variant, the effect could be a dangling Style::Scope& for a scope other than the current one.
As for the primitive: if the set is mutated mid-loop, the stale iterator reads freed bucket-array memory. It could then pass a forged or stale ContainerNode& into styleScopeFor. The downstream use is a dynamicDowncast<ShadowRoot> followed by a Style::Scope method call on whatever object comes out. That makes the bug a type-confusion or control-flow candidate if the attacker can control heap reclamation. Without reclamation control, the expected observable result is a crash. Apple's "arbitrary code execution" impact line is consistent with the controlled-reclamation case.
Reachability is ordinary web content. The prerequisites are only standard web platform features: build a sheet with new CSSStyleSheet(), adopt it into the document and/or several shadow roots through adoptedStyleSheets, and reach a sheet mutation that fans out through the adopted path rather than the single-owner early return. The bug runs in the WebContent process. A successful exploit yields renderer compromise, and escaping the WebContent sandbox would require a separate bug.
The fix restores the invariant structurally rather than by auditing every apply caller. copyToVectorOf removes the shared mutable state: once the snapshot exists, m_adoptingTreeScopes can be rehashed, shrunk, or pruned as often as the callback likes, and the loop never reads from it again. Because the snapshot holds Ref<ContainerNode> rather than raw or weak references, every adopter that was present at loop entry stays alive until the loop finishes. This closes the iterator-invalidation path and the destroy-the-next-element path with the same line.
forEachStyleScope walked a live hash set while handing control to a callback that can add or remove entries in that same set, leaving the loop iterating freed bucket storage.
Insight
Takeaway: before any loop whose body can run style, layout, or script, snapshot the collection into Vector<Ref<T>> with copyToVectorOf, because a Ref in the loop header protects only the current element and never the container.
Audit directions
-
Mutate-while-iterate on registrant collections. The invariant: no code path reachable from the loop body may insert into or remove from the container being iterated. Narrow: grep
Source/WebCore/cssandSource/WebCore/stylefor range-for loops overWeakHashSet/HashSetmembers (m_*Clients,m_*Scopes,m_adopting*) whose body calls aFunction/lambda or aStyle::Scopemethod. Start withStyleSheetContentsclient fan-out (users ofregisterClient/unregisterClient) and theStyle::Scopesheet-collection update paths. Wider: the same shape appears in observer delivery (theMutationObserver,ResizeObserver, andIntersectionObserverregistries), inEventTargetlistener vectors, and inMediaQueryListlistener fan-out, wherever the callback can reach script or teardown. Widest: this is the general mutate-while-iterate class behind Java'sConcurrentModificationException, Python's "dictionary changed size during iteration", and the C++ STL iterator-invalidation rules forunordered_set. Match tell: a loop whose body reaches anadd/removeon the iterated container, even transitively, with no snapshot taken before the loop. -
One strong ref per step over a weak registry. The invariant: callback side effects on element N must not be able to destroy element N+1 before the loop reaches it. Narrow: audit
for (Ref x : weakSet)andfor (auto& x : weakSet)loops in WebCore that call into style, layout, or DOM teardown, and check whether acopyToVectorOf<Ref<...>>snapshot exists. Wider: the same shape appears in any weak-reference registry iterated with one protecting strong ref per step, includingWeakListHashSet,SingleThreadWeakHashSet, and caches keyed byWeakPtr. Widest: any garbage-collected or weak-reference system where iteration upgrades one weak ref at a time has to account for side effects that kill later entries. Examples are PythonWeakSetiteration, RustWeak::upgradeloops, and JSWeakRef.deref()inside loops. Match tell: a strong ref taken inside the loop header instead of over the whole collection before the loop starts.