[6] `CSSStyleSheet::replaceSync()` copy-on-write guard for shared cached contents
Medium. On main, the pre-image never parsed into existing contents, so this diff guards a newly added in-place path rather than closing a reachable hole. The branch fix it backports would, per the commit message, have handed script an inconsistent Vector::insert().
Deduplication caches are safe only if every object they hand out is treated as immutable by all of its holders. In WebKit's CSS object model, a JS-visible CSSStyleSheet wraps a StyleSheetContents (the parsed rule storage). Several sheets can share one StyleSheetContents, and a process-wide StyleSheetContentsCache, keyed by source text and parser context, can also publish it. Each CSSStyleSheet additionally keeps a lazily filled vector of per-rule JS wrappers, which is expected to stay the same length as the shared rule list it mirrors.
The angle: on main this is hardening: the guard ensures replaceSync()'s new in-place reparse can never append rules to a StyleSheetContents that another sheet or the cache can see. Per the commit message, the branch this backports had a fast path that let script desync a sibling's wrapper vector and drive an out-of-range Vector::insert().
The detached fast path in CSSStyleSheet::replaceSync() called StyleSheetContents::parseString() directly, bypassing willMutateRules() and both of its checks: whether the contents have more than one client, and whether they have been published to StyleSheetContentsCache. Contents reached through a cache hit are shared with every other sheet holding that entry, so parsing into them appended rules that those sheets and the cache entry itself observe. A sheet that had already materialized m_childRuleCSSOMWrappers was then left with a wrapper vector smaller than m_contents->ruleCount(). insertRule() inserts at the requested index without growing that vector, so Vector::insert() moved a negative number of elements. The fast path now parses into fresh contents whenever the current ones are shared or published, and replaces the rules in place only when this sheet is the sole client of unpublished contents. Going through RuleMutationScope instead does not work: setMutable() makes isCacheable() false permanently.
Source/WebCore/css/CSSStyleSheet.cpp
LayoutTests/sar3/fast/css/constructed-stylesheet-replace-sync-shared-contents.html
Patch Details
The detached fast path (isDetached() && m_childRuleCSSOMWrappers.isEmpty()) is restructured. On a cache hit, the result is bound as RefPtr cachedContents, swapped into m_contents with releaseNonNull(), the client is re-registered, and the function returns immediately. On a miss, a new contentsForReplacement lambda picks the parse target. It reuses m_contents after clearRules() only when hasOneClient() && !isInMemoryCache(), meaning this sheet is the sole client of contents never published to the cache. Otherwise it creates a fresh StyleSheetContents with the same parser context, moves this sheet's client registration to it, and calls checkLoaded(). The selected contents are then parsed and added to the cache if isCacheable(). The new test covers five scenarios: a second replaceSync replaces rather than appends, non-cacheable nested contents are replaced in place, an adopted sheet takes the general path, a fresh sheet sees exactly one rule (so the cache was not polluted), and two sheets sharing cached contents stay in sync so insertRule(..., 2) throws IndexSizeError.
Fast-path mutation of a shared, cache-published object that bypasses the copy-on-write gate, desynchronizing per-client derived state from the shared backing data.
Background
Constructable stylesheets.
Script can create a CSSStyleSheet with new CSSStyleSheet(), fill it with replaceSync(text) or replace(text), and attach it through adoptedStyleSheets. A sheet not attached anywhere is detached (CSSStyleSheet::isDetached()).
CSSStyleSheet vs. StyleSheetContents.
CSSStyleSheet is the per-sheet CSSOM object exposed to JS. StyleSheetContents is the refcounted parsed storage (m_childRules, m_importRules, and so on), and it tracks its sharing sheets in m_clients via registerClient()/unregisterClient().
Style::StyleSheetContentsCache.
A process-wide singleton mapping (source text, parser context) to a StyleSheetContents, so identical stylesheet text shares one parsed object. Entries are marked via addedToMemoryCache(), which drives isInMemoryCache(). Only contents passing isCacheable() are inserted; contents with imports, namespaces, nesting, or m_isMutable set are excluded. The cache exists to avoid reparsing identical text across many sheets.
Copy-on-write in CSSOM.
CSSOM mutations (insertRule, deleteRule, rule edits) go through CSSStyleSheet::willMutateRules(), usually via RuleMutationScope. If the contents are shared or cached, this clones them before mutating and marks the result mutable with setMutable(), which permanently opts it out of caching.
m_childRuleCSSOMWrappers and Vector::insert.
m_childRuleCSSOMWrappers is a per-sheet vector of lazily created CSSRule wrappers, indexed in parallel with the contents' rules and populated on access such as sheet.cssRules[i]. WTF Vector::insert(position, value) grows the buffer, shifts elements in [position, size) up by one, and writes at position.
Analysis
This is a copy-on-write violation on shared, cached StyleSheetContents.
first ──┐ ┌── second (wrappers: [W0], size 1)
▼ ▼
StyleSheetContents ◄── StyleSheetContentsCache
rules: [.p] (cache hit: 2 clients + cache)
branch fast path: first.replaceSync(text) parses INTO shared contents
rules: [.p, ...] ruleCount grows; second.wrappers still size 1
second.insertRule(r, k): k checked against ruleCount -> passes
wrappers.insert(k, ...) k > wrappers.size -> negative tail move
The top of the diagram is the sharing the cache creates: identical text gives first and second the same contents, and second.cssRules[0] materializes one wrapper. The commit message describes the branch shape in the middle row: the detached fast path called parseString() without willMutateRules(), so parsing appended rules visible to the sibling and to the cache entry. The bottom row is the consequence the commit message and the test comment both name. insertRule() validates the index against the rule count but inserts into the shorter wrapper vector without growing it, so Vector::insert() computes a negative tail length for the element move.
On main, the code before this patch never had that shape. On a cache hit it only swapped m_contents and re-registered the client; on a miss it always created a fresh StyleSheetContents, parsed into it, and published it. The clearRules()-and-reparse-into-m_contents path is new in this patch. The commit is a backport (Originally-landed-as: 316606.702@safari-7625-branch), and the claim that the direct-parse-into-shared-contents shape existed on that branch is relayed from its commit message. On main, the patch adds an in-place reuse optimization for sole-owner, uncached contents and attaches to it the sharing checks any in-place reparse must pass. The commit message explains why it does not simply use RuleMutationScope: setMutable() would make the contents permanently uncacheable.
The test's final scenario is the variant probe:
- Create
firstandsecond, andreplaceSyncboth with.p { color: red; }. The second call hits the cache, so both share oneStyleSheetContents. - Touch
second.cssRules[0]to materialize one wrapper. - Call
first.replaceSync(".q { color: blue; }"). With the guard,firstgets fresh contents, and the shared object is untouched. - Assert
second.cssRules.length == 1and thatsecond.insertRule(..., 2)throwsIndexSizeError, meaning the sibling's rule count never outran its wrappers.
The path is reachable from web content through the constructable-stylesheet API, as the test shows. Where the branch shape exists, the likely ceiling per the commit message and test comment is a renderer crash from an inconsistent Vector::insert(). Escalation hinges on whether insertRule() validates against ruleCount() and then calls Vector::insert() on the shorter vector, and whether WTF Vector::insert() enforces position <= size() in release builds. If it does not, the element move could run with a wrapped length. Because the vector stores RefPtr<CSSRule> slots, any surviving corruption would touch refcounted wrapper pointers, which makes it a lifetime-confusion candidate. Attacker control over the move length is not established, though. The code lives in the WebContent process and needs a separate escape for anything beyond renderer-plane impact.
The invariant at stake is renderer memory safety. CSSOM assumes that StyleSheetContents reachable from more than one client, or from the cache, is immutable unless it goes through the clone-on-write gate, and that assumption keeps each sheet's wrapper vector the same length as the rule list it mirrors. On main, this diff ensures the newly added in-place path cannot break it. On the source branch, according to the commit message, the fast path broke it. The commit message and the test comment both describe a later insertRule() that validates against ruleCount() but inserts into the shorter wrapper vector, giving a heap Vector element move with an inconsistent length.
Insight. This is a classic deduplication-cache hazard, and the commit message shows why the gate is awkward here. The canonical gate permanently disqualifies contents from caching, which pushes optimization-minded code into hand-written mutation paths that must re-derive the sharing checks (hasOneClient(), isInMemoryCache()) themselves. This patch's in-place reuse is exactly such a hand-written gate and is worth watching as the code evolves. The sharper risk is derived per-client state: m_childRuleCSSOMWrappers lives on each sheet but is implicitly sized from shared data, so any out-of-band mutation silently invalidates every sibling.
Audit directions
- Mutation of a shared or cache-published object through a path that bypasses the copy-on-write gate. The invariant is that anything reachable from more than one owner or from a dedup cache is immutable unless cloned first. Narrow: grep
Source/WebCore/cssfor callers ofparserAppendRule,parseString,clearRules,wrapperInsertRule, andwrapperDeleteRulethat are not dominated bywillMutateRules()/RuleMutationScope; start withCSSStyleSheet::replace()(async),@importchild-sheet handling, and theStyleSheetContentscopy constructor. Match tell: a mutation call onm_contentswith nohasOneClient()/isInMemoryCache()/isMutable()check on the same path. Wider: other WebCore dedup caches that hand out sharedRefs, such asMutableStylePropertiesvs. immutableStyleProperties,RenderStyledata viaDataRefcopy-on-write, andCachedResource-backed decoded data; match tell: a const-intended shared object reached through a non-const accessor on an optimization path. Widest: any interning or dedup cache returning mutable shared handles (Python string interning misuse, JavaString.internwith reflection, RustArccaches withget_mut/make_mutmisuse). The audit question is whether every write path checks unique ownership first. - Per-owner derived state sized from shared backing data with no resync on out-of-band change. A parallel index structure must be invalidated or resized whenever the collection it mirrors changes, no matter who changed it. Narrow: audit
CSSStyleSheet::insertRule,deleteRule, anditem(), plus nested-rule wrapper vectors inCSSGroupingRule,CSSKeyframesRule, andCSSStyleRule, and check whether each bounds-checks against the authoritative count or the wrapper vector's own size. Match tell: an index validated againstruleCount()/childRules().size()and then used on a separately sized wrapper vector. Wider: DOM live collections (HTMLCollectioncaches),CSSRuleListfor media and supports rules, andStyleSheetList. Widest: any binding layer that keeps view-side arrays parallel to a shared model (UI list adapters, ORM identity maps, GPU mirror buffers). Match tell: two collections indexed by the same integer with independent lengths. - Container index preconditions enforced only in debug builds. Check WTF
Vector::insert()andVector::remove()for release-mode enforcement ofposition <= size(); any caller that can pass a stale index would otherwise turn a logic desync into a wild-length memmove. Match tell: onlyASSERT/ASSERT_WITH_SECURITY_IMPLICATIONguards the position, with noRELEASE_ASSERTor span bounds check. Wider: grep WebCore forVector::insert(calls whose index comes from a different container's size. Widest:std::vector::insertwithout hardening and Chromiumbase::spanusages carry the same risk whenever bounds checks are debug-only.