[1] DFG elides store barriers on `NewTypedArray` / `NewTypedArrayBuffer` results
DFG skipped GC barriers on objects too fresh to scan, except they weren't.
High. Ordinary script in an optimized function could get a still-reachable object swept by the collector. Reachability isn't what limits it. Reliability is: the attacker has to win a probabilistic concurrent-marking race and then reclaim the freed slot.
Concurrent garbage collectors depend on write barriers to learn about pointer edges created while marking is already underway. A write barrier is a small check the compiler emits around each pointer store. JSC's DFG optimizing JIT runs a barrier-insertion pass that skips the barrier on stores into an object it can prove was allocated so recently that the collector cannot have scanned it yet. That proof rests on one invariant: no collection can start or advance between creating the object and the next operation the compiler knows can trigger GC.
The angle: any page script that gets a function into the DFG/FTL tiers could win a concurrent-marking race and be left holding a live JS reference to an object the collector already swept. That is a GC use-after-free and a typical starting point for type confusion.
The DFG barrier insertion phase tracks an "epoch" serial number. The epoch is bumped every time the phase encounters a node that can GC. Allocating nodes set their epoch to the current one, and a store into a node whose epoch is still current skips the FencedStoreBarrier. This is sound only if no GC safepoint can run between the allocation of the node's result and the next doesGC() node. Two nodes on that list violate the requirement:
NewTypedArrayBuffer(new ArrayBuffer(n)) allocates theJSArrayBuffercell and then runsfinishCreation, which registers the buffer with the heap through a GC safepoint.NewTypedArray(new Uint8Array(x)) allocates the view before copying elements out of an array-likex. Reading those elements can invoke getters, which can allocate and GC.
The fix drops both nodes from the epoch list. They are listed explicitly alongside default, so re-adding them would be a duplicate-case compile error.
Source/JavaScriptCore/dfg/DFGStoreBarrierInsertionPhase.cpp
JSTests/stress/dfg-store-barrier-elision-new-array-buffer-mid-node-gc.js
Patch Details
The change edits the node-classification switch in StoreBarrierInsertionPhase::handleNode. NewTypedArray and NewTypedArrayBuffer are removed from the case group of allocating nodes whose result is stamped with the current epoch. That group still contains NewArrayBuffer, NewInternalFieldObject, NewPromise, NewRegExp, NewStringObject and others. The two nodes are re-listed directly above default, which places their results in the primordial epoch. Every later possibly-cell store into those results now gets a FencedStoreBarrier. A comment names the two mid-node safepoints, setFromArrayLike and Heap::addReference.
The commit also adds a stress test that runs under --verifyGC=1. It races a barrier-elided computed-key store into a fresh ArrayBuffer against concurrent marking.
Write-barrier elision that treats an allocation operation as atomic with respect to GC, when the operation can reach a safepoint after the new object is already visible to the collector.
Background
Tri-color marking. The collector colors cells white (not yet seen), grey (seen, children not yet scanned) and black (fully scanned). Cells still white at the end of marking are swept.
Concurrent marking and store barriers.
JSC's collector, Riptide, marks concurrently with the mutator (the thread running JS). Mutator stores of a cell pointer therefore go through a store barrier. The barrier checks the destination's cell state. If the destination may already have been scanned, the barrier re-greys it or records it so the marker re-visits it. FencedStoreBarrier is the DFG node that emits this barrier together with the memory fencing that concurrent marking needs.
GC safepoints and conservative scanning. A GC safepoint is any point where the mutator lets a collection start or advance. Examples are an allocation slow path, extra-memory reporting, and any call that can run JS. JSC also scans the machine stack conservatively: any word that looks like a cell pointer is a root. A freshly allocated cell sitting in a register or stack slot is therefore visible to the marker.
doesGC() and the epoch model.
doesGC() (in DFGDoesGC.cpp) is the DFG's per-node predicate for whether executing a node may trigger GC. The barrier insertion phase gives every node an Epoch. The current epoch advances at each doesGC() node, and allocating nodes stamp their result with the current epoch. The primordial Epoch() means "arbitrarily old". In Global (SSA) mode the same reasoning extends across basic blocks through m_stateAtHead/m_stateAtTail.
The two nodes.
NewTypedArrayBuffer is emitted for new ArrayBuffer(n). NewTypedArray is emitted for typed-array constructors such as new Uint8Array(x), including the case where x is an array-like whose elements are copied into the new view.
Analysis
This is an unsound barrier elision: the compiler's freshness proof was broken by work happening inside the allocating node.
Before (on fresh-epoch list) After (falls into default)
buf = NewTypedArrayBuffer epoch := E buf = NewTypedArrayBuffer epoch := Epoch()
└─ finishCreation └─ finishCreation
└─ Heap::addReference <- safepoint └─ Heap::addReference
stack scan finds buf, marker blackens
buf[key] = victim buf[key] = victim
└─ epoch still E -> barrier ELIDED └─ FencedStoreBarrier emitted
black buf -> white victim, unrecorded marker re-visits buf
(victim swept while reachable via buf)
In the left column, the epoch model sees one node and assumes it is atomic. doesGC() describes the boundary between nodes, though, and the safepoint sits inside this one. During Heap::addReference (or, for NewTypedArray, during a user getter run by setFromArrayLike), a conservative stack scan can find the already-allocated result, and the concurrent marker can blacken it. When control returns, the phase still treats buf as current-epoch, so the next cell store into it is emitted without a barrier. That store creates a black→white edge the collector never hears about. If victim has no other path from the roots, it is swept while still reachable through buf's property storage.
The commit message narrows the affected store shapes. Element writes such as ta[0] = 1 store numbers through specialized array modes that need no barrier. Named-property writes such as ta.foo = o must first allocate out-of-line property storage, because neither typed arrays nor ArrayBuffers have inline capacity. That allocation bumps the epoch, so those stores were already barriered. What remains is the computed-key store, ta[k] = o.
The discovery shape points to pattern auditing: someone checked the fresh-epoch list against the runtime operation behind each node, looking for safepoints that fire after the result cell exists. The in-file FIXME about undocumented barrier invariants and the precise mechanism in the commit message support that over fuzzing. The probabilistic stress test reads as confirmation built afterwards.
The regression test reduces the trigger to a straight-line, single-block function:
let buf = new ArrayBuffer(SZ). There is nodoesGC()node between this allocation and the store, so the elision really applies.let victim = cur.p. The victim is given auxiliary (butterfly) storage on purpose.buf[key] = victimis the barrier-elided by-val IC transition store.cur.p = nulldrops the only other path tovictim.--verifyGC=1re-marks from the roots andRELEASE_ASSERTs on any reachable cell the realSlotVisitormissed. A JS-visible oracle (check) separately detects recycled property values.
The test's delay and external-memory pacing constants tune the race window.
Exploitability follows the same shape. The pattern is reachable from ordinary web JS once the enclosing function tiers up to DFG/FTL: new ArrayBuffer(n), or new Uint8Array(arrayLike) with a getter that runs GC, followed by a computed-key cell store before the next doesGC() node. The confirmed effect is a reachable cell being swept. The next escalation step depends on what reoccupies the swept cell's slot before the stale edge in buf's property storage is read back. If the slot could be reliably reclaimed by a cell with a different structure in the same size class, the stale reference would behave as a type-confused JSCell. The victim's out-of-line butterfly could be reclaimed the same way, which is why the test gives it one. The commit does not quantify the concurrent-marker race that this depends on. Reliability, not reachability, is the remaining obstacle.
This vulnerability weakens memory safety in the WebContent process at the boundary between JIT-compiled code and the concurrent collector. The broken invariant is the tri-color rule: a black cell must never gain a reference to a white cell unless a write barrier tells the collector. An attacker who wins the race would hold a live JS reference to a swept cell, a state that typically becomes type confusion between JS objects inside the renderer. Going beyond the renderer would need a separate sandbox escape.
Insight: The epoch analysis encodes a stronger contract than the "allocating node" label suggests. The node must allocate its result, run no safepoint until it completes, and return. Heap registration, extra-memory reporting, and spec-mandated user callbacks all break that contract from the inside. The file's own FIXME (rdar://177100632) admits the barrier placement invariants are undocumented, so the remaining fresh-list entries have not all been checked against this criterion. The fix's defensive idiom is worth copying: listing excluded opcodes as explicit case labels next to default turns accidental re-inclusion into a compile error instead of a silent regression.
Audit directions
- Allocations that hit a safepoint after the result is published. The invariant is that a barrier-elided object must not be scannable by the marker until the elision window closes.
- Narrow: audit every remaining case in the fresh-epoch list of
DFGStoreBarrierInsertionPhase.cpp(NewArrayBuffer,NewInternalFieldObject,NewPromise,NewRegExp,NewRegExpUntyped,NewStringObject, and the rest), along with the slow-path operation each one calls. A match is anyfinishCreationor post-allocation step that reports extra memory, registers with the heap, or calls user JS. - Wider: the same assumption appears wherever a freshly materialized object is assumed white, such as DFG object allocation sinking materializations and the barrier clustering/fencing phases. Check whether any of them allocate several cells in sequence and store between them without a barrier.
- Widest: Turbofan's write-barrier elimination for young allocations and HotSpot C2's ReduceInitialCardMarks rest on the same "no safepoint between allocation and initializing stores" contract.
- Code-review tell: an allocation whose initialization path can call back into heap accounting or user code after the object pointer escapes to a register.
- Per-node GC-effect summaries that describe a node's boundary but not its interior. A node can be "allocating" and still GC midway through its own execution.
- Narrow: read
DFGDoesGC.cppand the epoch switch together, looking for nodes whose backing operation is a multi-step runtime call (construct-then-fill, construct-then-register). Grep the corresponding JIT operations for extra-memory reporting or accessor invocation after the result is created. - Wider: the same pattern shows up in clobberize/AI effect models whenever an operation's documented effect summarizes several internal steps.
- Widest: LLVM's gc-leaf-function/statepoint attributes and V8's operator
kNoAllocate/kNoWriteproperties are effect annotations of the same kind. A match is any operation annotated as non-GCing or fresh-allocating whose implementation contains a reachable safepoint or callout. - Spec-mandated user-code callouts inside constructor-like operations. These run after the result object already exists.
- Narrow: investigate DFG/FTL nodes that allocate first and then fill from an iterable or array-like, such as typed-array construction from objects. Verify whether user-observable getters,
Symbol.iteratororvalueOfhooks run while the new object is already live. A match is an allocate-then-populate operation where any compiler pass (barrier elision, allocation sinking, escape analysis) still treats the result as untouched. - Widest: this is the general "object published before construction completes" hazard. It also applies to SpiderMonkey's Ion barrier elision on fresh objects and to any GC'd runtime with two-phase construction plus compiler-side freshness assumptions.