[4] ShadowRoot's duplicate `m_shadowIncludingRoot` leaves shadow trees pointing at a freed host
Shadow DOM's composed-root cache outlived the element it pointed at.
A renderer UAF reachable with attachShadow, a retained childNodes list and one GC. It sits at High rather than higher because whether the stale read hands script a dangling node depends on the cache's pointer type and on slot reuse, neither of which this change settles.
DOM trees in WebKit cache tree-derived answers on every node so composed-tree queries don't have to walk upward each time, and those caches are only safe while they point at live nodes. Each node stores its shadow-including root in Node::m_shadowIncludingRoot — the topmost ancestor reached by walking parents and crossing from each shadow root to its host — and a ShadowRoot, the hidden subtree an element attaches via attachShadow(), links back to that host element. The invariant is that this cached root always matches what a fresh upward walk would find, including after the host is torn down.
The angle: a page can keep a shadow tree alive past its host's destruction and then ask a shadow child for its composed root, reading through a cached pointer to the freed host element.
Per the commit message (rdar://178311709), ShadowRoot declared its own m_shadowIncludingRoot, hiding the inherited one, so ShadowRoot::setHost() wrote only the derived copy. Element::removeShadowRootSlow()'s oldRoot.setHost(nullptr) therefore left Node::m_shadowIncludingRoot in the shadow root and its descendants pointing at the host, and once the detached host was destroyed while something outside ElementRareData still held the shadow tree, getRootNode({composed: true}) read freed memory. The earlier fix for webkit.org/b/312426 (314671@main) added the equivalent reset in removeDetachedChildrenInContainer(), but shadow roots aren't in the host's child list, so that path never ran for them.
Source/WebCore/dom/ShadowRoot.h
Source/WebCore/dom/Element.cpp
Source/WebCore/dom/Node.cpp
LayoutTests/sar3/fast/shadow-dom/shadow-root-composed-root-after-host-destruction.html
Patch Details
ShadowRoot.h loses its duplicate WeakPtr<Node, WeakPtrImplWithEventTargetData> m_shadowIncludingRoot, the shadowIncludingRoot() and setShadowIncludingRoot(Node*) accessors, and the declaration of the inline setHost(Element*); the constructor's m_shadowIncludingRoot(this) initializer and the SameSizeAsShadowRoot slot go with it. Element.cpp deletes the inline ShadowRoot::setHost(Element*) body, which set m_host and the derived cache together, and Element::addShadowRoot now calls the surviving setHost(WeakPtr&&) overload, which assigns only m_host. Node::updateShadowIncludingRoot() drops its dual write and assigns only Node::m_shadowIncludingRoot = host ? host->m_shadowIncludingRoot : shadowRoot; its ASSERT(traverseToShadowIncludingRoot(this) == m_shadowIncludingRoot) is unchanged. The diff adds no new recompute or invalidation call; the production change is purely the consolidation of two storage slots into one. Which teardown path recomputes the surviving subtree's cache once the duplicate is gone is an open question. Most likely an existing Node-level update in the shadow-root removal path previously targeted the derived copy and now operates on the base slot. The new test keeps a shadow tree alive only through a ChildNodeList, forces GC of the detached host, and expects getRootNode({composed: true}) on the shadow child to return the shadow root.
A derived class re-declaring a base-class cache field under the same name, so some writes hit the shadowing copy while the base copy most readers consult keeps a dangling owner pointer.
Background
Shadow DOM.
An element (the host) can own a ShadowRoot via attachShadow(). The shadow root is a DocumentFragment subclass and is not a child of the host: Element::addShadowRoot stores it in the host's m_shadowRoot, and the shadow root points back through ShadowRoot::m_host, a WeakPtr<Element, WeakPtrImplWithEventTargetData>.
The shadow-including root cache.
The shadow-including root is reached by walking parent links, crossing from each shadow root to its host, until a node with neither. Node.getRootNode({composed: true}) returns it to script. WebKit caches it per node in Node::m_shadowIncludingRoot and maintains it with updateShadowIncludingRoot(), updateShadowIncludingRootForSubtree() and resetShadowIncludingRoot(); a debug ASSERT checks the cache against a live traversal.
C++ name hiding. When a derived class declares a member with the same name as a base-class member, unqualified uses inside the derived class, and calls through a derived-typed expression, refer to the derived one. The two data members occupy separate storage and can hold different values.
DOM wrapper lifetime.
The GC keeps JS wrappers for DOM nodes alive through "opaque roots". A C++ object such as a ChildNodeList can hold a strong Ref to a node without making the GC treat that node's tree as reachable, so the C++ ownership graph and the JS-reachable graph can disagree about what is alive.
Detachment paths.
removeDetachedChildrenInContainer() detaches a container's regular children by walking firstChild() / nextSibling(). Shadow roots are detached from their host through a separate Element path.
Analysis
This is a use-after-free read through a stale cached node pointer.
attachShadow + innerHTML span.Node cache = host
shadowRoot.childNodes ChildNodeList Refs the shadow tree
host unreachable from JS GC collects host wrapper
host detach (per commit msg: removeShadowRootSlow → setHost(nullptr))
└─► writes ShadowRoot::m_shadowIncludingRoot
└─► Node::m_shadowIncludingRoot still = host
host Element destroyed ─┐
│ failure window: shadow root + span cache → freed host
child.getRootNode( │
{composed: true}) ─┘ reads cached pointer → freed Element
The timeline's middle row is the split. Node::updateShadowIncludingRoot() wrote both copies, but the inline ShadowRoot::setHost(Element*) wrote only the derived WeakPtr copy, resetting it to this for a null host. Shadow-tree descendants inherit Node::m_shadowIncludingRoot from their parent via m_shadowIncludingRoot = parent->m_shadowIncludingRoot, so they follow the base copy, which nobody reset. Any reader going through a ShadowRoot-typed expression would have seen the derived copy instead: either this or a WeakPtr nulled with the host. That would let the two slots disagree without any ShadowRoot-side check noticing. Which call sites, if any, consumed that derived accessor is not established.
The earlier reset in removeDetachedChildrenInContainer() couldn't help, because its sibling walk never reaches a shadow root. The ChildNodeList in the second row is what holds the shadow tree alive across the host's destruction while the GC sees no reason to keep the host.
The trigger is four ordinary steps: attachShadow and innerHTML to build a shadow tree, a retained childNodes list to keep it alive, natural GC of the detached host, and getRootNode({composed: true}) on a shadow child. Per the commit message, that last call reads freed memory.
What happens next depends on two unsettled facts. First, the declared type of Node::m_shadowIncludingRoot: the pre-fix .get() and SameSizeAsNode's void* shadowIncludingRoot show only a pointer-sized smart wrapper. A CheckedPtr with zombie-on-delete semantics (WTF_OVERRIDE_DELETE_FOR_CHECKED_PTR is present on Node) would likely downgrade this to a contained crash; a zeroing WeakPtr would not produce the freed-host reference at all. Second, whether WTF_MAKE_PREFERABLY_COMPACT_TZONE_ALLOCATED would let an attacker-influenced object reuse the freed Element's slot. If the pointer is raw-like and a same-size-class allocation reclaims the slot before the read, getRootNode would hand the stale Node* to the bindings layer for wrapper lookup or creation, exposing a type-confused or freed object to script; virtual dispatch on it (nodeType, wrapper creation) would make it a control-flow candidate. Without reclamation, the ceiling is a crash or a wrong-object read. The bug stays in WebContent and doesn't cross the sandbox on its own.
This vulnerability weakens memory safety in the WebContent renderer. WebCore assumes a node's cached shadow-including root always refers to a live node that traverseToShadowIncludingRoot would also reach. Before the fix, web content could break that with attachShadow and GC timing so that a web-exposed DOM API read a pointer to a destroyed Element; if the slot were reclaimed and the pointer handed to script as a Node, an attacker would gain a renderer-plane UAF over a DOM node, the class of primitive historically used for renderer compromise, with a separate sandbox escape still required.
The commit message's pointer to 314671@main suggests discovery by variant analysis: reviewing which other detachment edges need the same reset exposes the shadow-root path and the shadowed member. This week's appendix also carries 3317c4c, a GC-correctness hardening for the same bug.
Insight: The compiler accepts the shadowing, and the SameSizeAsShadowRoot static_assert verified only that the class size stayed consistent with the extra member, not that the member was redundant. The fix adds no new invalidation cleverness — it deletes the second slot so every reader and writer, through Node- or ShadowRoot-typed expressions, resolves to one storage location. A denormalized cache of a tree-derived value must have exactly one storage owner; a second "convenience" copy creates write paths that look correct in review but update state nobody reads.
Audit directions
- Cached tree-derived values stored or written in more than one place. Shadow-including root, tree scope, owner document, composed parent — a denormalized cache must have exactly one storage slot, and every lifecycle transition (attach, host change, owner destruction) must write it. Narrow: enumerate every writer of
m_shadowIncludingRoot,m_treeScopeandsetParentTreeScopeinSource/WebCore/dom, and check that each host-change or teardown path (Element::addShadowRoot,Element::removeShadowRootSlow,ShadowRoot::setHost) updates the canonicalNode-level field rather than a side copy. Wider: look for the same split in caches that cross a non-child edge — slot-assignment caches, style-scope pointers,AXObjectCacheparent pointers — where a subclass or helper keeps its own copy. Widest: any tree or graph that denormalizes ancestor-derived state for fast lookup (Gecko'snsINode::SubtreeRoot, Blink'sTreeScope, ORM identity caches). Tell: two fields or two setters meant to hold the same derived value, where at least one write path updates only one of them. - Field and accessor shadowing across WebCore class hierarchies. Grep for data members and accessors in WebCore subclasses that share a name with a base-class member; Clang
-Wshadow-fieldfinds these, as does diffing member names ofNode/ContainerNode/ElementagainstShadowRoot,DocumentFragment,DocumentandHTMLTemplateElement. Derived-side setters silently update a copy base-class readers never consult, so invalidation looks correct in review. Wider: getter/setter pairs that cache a value in two layers (a base field plus a derived "fast copy"). Widest: any C++ or Java codebase with field shadowing, which is why Chromium and LLVM style guides discourage it. In code review, a derived setter assigning a member whose name also exists in a base class, where base-class methods read the unqualified name, is the visual flag. - C++ ownership and GC reachability disagreeing. A C++
Refkeeps a subtree alive after the GC has collected the JS-visible owner and run its native destructor. Investigate DOM collection and list types that holdRefs into shadow trees or detached subtrees without opaque-root tracing —ChildNodeList,LiveNodeListsubclasses,HTMLCollection,StaticNodeList,NodeIterator/TreeWalker,Rangeboundary points — and for each, check which back-pointers in the retained subtree point toward the collected owner. Wider:MutationObserverregistrations,IntersectionObservertargets andAbortSignalfollow lists. Widest: any embedder mixing refcounting with a tracing GC (Blink Oilpan, the Gecko cycle collector, Node.js native addons). Tell: a native object keeping a child alive while the parent's native destructor runs, combined with an upward pointer in the child that the destructor does not clear.