Repository navigation
[JSC] JSArray::setLength / shiftCountWithAnyIndexingType clear live butterfly slots through libc memset, racing the concurrent marker - #564
Conversation
…rough libc memset JSArray::shiftCountWithAnyIndexingType, shiftCountWithArrayStorage, unshiftCountWithArrayStorage, unshiftCountSlowCase and setLength move elements with gcSafeMemmove() and then clear the vacated slots with a loop of WriteBarrier<Unknown>::clear(). Clang's loop-idiom recognition compiles that loop to a call to memset(). The butterfly is live and a marker thread may be scanning it at the same time, and libc makes no promise about store width: musl's x86_64 memset writes the head and tail of the range with 1-, 2-, 4-byte and unaligned 8-byte stores. A marker that loads the slot mid-sequence sees, for example, only the low byte or the low five bytes of the pointer being cleared, treats it as a JSCell* and crashes in SlotVisitor::appendHiddenSlow / JSObject::visitChildren, or marks a bogus address and crashes later in SlotVisitor::drain, or parks forever in MarkedBlock::aboutToMarkSlow on a lock word derived from the torn value. On a musl build this reproduces within seconds with Array.prototype.splice on arrays of objects while the collector is marking; glibc's memset happens to use 8-byte-or-wider stores for these shapes, which is why glibc builds do not show it. Make updateEncodedJSValueConcurrent() a relaxed atomic store and route WriteBarrier's unbarriered stores (setWithoutWriteBarrier, clear, setUndefined, setStartingValue, copyFrom, setEarlyValue) through it. On 64-bit targets that is the same single store instruction as before, but the compiler can neither split it nor fuse a loop of them into memset() or memcpy(), so a slot the marker can observe is always written with one word-sized store regardless of the libc underneath. The bulk clears in JSArray.cpp use gcSafeZeroMemory(), matching the gcSafeMemmove() calls next to them, so large clears stay vectorized.
There was a problem hiding this comment.
Beyond the inline finding, I checked that each gcSafeZeroMemory() call covers exactly the same slots as the loop it replaces — end/count in shiftCountWithAnyIndexingType (end = oldLength - count), lengthToClear in setLength, startOfEmptyVectorTail/count in shiftCountWithArrayStorage, and startIndex/count in unshiftCountWithArrayStorage all match the old bounds. I also confirmed gcSafeZeroMemory() itself is hand-written asm using only 8- and 16-byte stores at 8-byte-aligned offsets, so it does not reintroduce sub-word torn writes, and that WriteBarrierBase<T>::set() reaches storeConcurrently() via setEarlyValue().
Extended reasoning...
This change rewires every unbarriered WriteBarrier store and several bulk butterfly clears to guarantee word-atomic visibility to the concurrent marker — core GC/mutator-race territory. The inline finding covers the test-duration convention issue; separately I verified that the loop→gcSafeZeroMemory conversions preserve the exact slot ranges (the arithmetic differs in form but is equivalent in each of the five sites), that gcSafeZeroMemory in GCMemoryOperations.h uses only 8/16-byte asm stores so it cannot itself tear a JSValue, and that the barriered set() path flows through the new storeConcurrently() via setEarlyValue(). Given the sensitivity of concurrent-GC store ordering and that at least one further verified finding is being withheld from this review, human sign-off is still appropriate.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Essentials Run ID: 📒 Files selected for processing (2)
Included review availability: 1 review is currently available. Your included PR review attempts over the past 7 days set your current allowance at 2 reviews per hour. WalkthroughJavaScriptCore replaces per-slot clearing with GC-safe bulk zeroing for contiguous array truncation, shifted tails, and newly exposed vector slots. Double-array truncation still clears slots individually with ChangesConcurrent array clearing
Merge Risk: ⚪ Minimal · up to This change uses GC-safe clearing for affected array and vector storage, preventing concurrent marking from observing torn slot updates. The reviewed changes are ready to merge with no active risk identified. 🚥 Pre-merge checks | ✅ 3 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description provides a detailed problem statement, fix, and verification results. It does not follow the repository template because it omits the Bugzilla URL, reviewer line, and changed-file/function summary.
Warning Git: CodeRabbit could not clone the repository, so clone-backed analysis was skipped and this review may be incomplete. Verify repository clone access, such as SSH credentials, before requesting another full review. If clone access is intentionally unavailable, use Comment |
Preview Builds
|
|
Claude wrote this comment (posted from Jarred's account at his request). I reviewed this and then went looking for other instances of the same pattern. Summary: the fix is right, I'd keep the Review
Why not a clang attribute insteadI tried It does suppress loop-idiom, but LLVM treats the no-builtin set as an inline-compatibility constraint, so it can't go on Sweep for other instancesI took the Compiler-fused
Every other fused Explicit mem-ops on live storage: every move on live Contiguous/ArrayStorage already goes through One place outside the invariant this PR establishes: musl detail worth putting in the descriptionFrom musl's
musl aarch64 Nits
|
Only JSArray::setLength and JSArray::shiftCountWithAnyIndexingType clear slots of a live Contiguous butterfly that the marker scans without a lock. The ArrayStorage variants run under cellLock(), which the marker also takes for that shape, and every other WriteBarrier clear loop in the tree fills storage that is not published yet. Keep the fix to those two sites, using the existing gcSafeZeroMemory(), and drop the WriteBarrier/EncodedJSValue store changes and the stress test.
Unlike shift/unshiftCountWithArrayStorage, this path is reached from putByIndexBeyondVectorLengthWithArrayStorage without cellLock(), so the marker's ArrayStorage lock does not exclude it. It cleared the new tail with a WriteBarrier::clear() loop (fused into memset) and then raised vectorLength with no storeStoreFence, so a marker that reads the new vectorLength is not guaranteed to see the cleared slots. Use gcSafeZeroMemory and fence before publishing the length, matching ensureLengthSlow.
There was a problem hiding this comment.
Thanks — the stress test I flagged is gone, and I reviewed the two new commits without finding bugs. Given this sits in the concurrent-marker path, a human sign-off is still worthwhile.
What was reviewed:
- Range arithmetic at all three sites matches the removed loops exactly (
lengthToClear = publicLength - newLength;oldLength - end = count;availableVectorLength - vectorLength). contiguous().data()andm_vectorareWriteBarrier<Unknown>*, satisfyinggcSafeZeroMemory'ssizeof(T) == sizeof(JSValue)static_assert; byte counts are alwaysn * 8so thebytes % 8 == 0RELEASE_ASSERT holds.- The new
storeStoreFence()beforesetVectorLengthinincreaseVectorLengthis strictly more conservative — though the PR description says ArrayStorage scanning iscellLock()-serialized, so a reviewer familiar withvisitButterflyshould confirm this hunk is wanted.
Extended reasoning...
Overview
Three WriteBarrier<Unknown>::clear() loops over live butterfly slots are replaced with gcSafeZeroMemory(), the primitive JSC already uses alongside gcSafeMemmove() so the concurrent marker never observes a torn JSValue. Two sites are the Int32/Contiguous branches of JSArray::setLength and JSArray::shiftCountWithAnyIndexingType; the third (added after my previous review) is the in-place branch of JSObject::increaseVectorLength, which also gains a WTF::storeStoreFence() before setVectorLength. The stress test I previously commented on was dropped, so the diff is now three hunks across two files.
Security risks
The bug being fixed is a concurrent-GC torn read that produces a garbage JSCell*, which is memory-corruption-adjacent. The fix itself introduces no new attack surface: it swaps a compiler-lowered memset for an 8-byte-atomic zeroing primitive over the identical range, and the added fence only strengthens ordering. No auth, crypto, or input-parsing surface is touched.
Level of scrutiny
High. This is core JavaScriptCore GC-visible mutation — an off-by-one in the pointer or byte count, or a mismatch with gcSafeZeroMemory's alignment/size assertions, would either crash immediately or corrupt adjacent slots under GC. I checked each range against the removed loop bounds and against the template's static_assert(sizeof(T) == sizeof(JSValue)) and RELEASE_ASSERT(bytes % 8 == 0); all hold. Because correctness here depends on the concurrent-marker protocol (which butterflies are scanned under cellLock(), which are not), a reviewer with visitButterfly context should still confirm — particularly the increaseVectorLength hunk, since the PR description states ArrayStorage marking is lock-serialized, which would make that clear loop already safe and the fence unnecessary (though harmless).
Other factors
My earlier inline comment concerned only the stress test's runtime; that file was removed in 86265bc, so nothing from my prior review remains open. Jarred-Sumner (a maintainer) authored the third hunk, and Jarred also commented on the thread, so there is active human engagement. No regression test ships with the fix now, but the change is a straight substitution of an existing primitive that unshiftCountSlowCase already uses in the same file.
…erfly slots through libc memset (oven-sh/WebKit#564) (#41407) ### What Bumps WebKit from `fbd894680a6c` to [`2e2aa2290fac`](oven-sh/WebKit@2e2aa22), the oven-sh/WebKit#564 merge commit on `main`. The range contains two changes: **oven-sh/WebKit#564 — concurrent marker could read a torn JSValue on musl builds.** `JSArray::setLength` and `JSArray::shiftCountWithAnyIndexingType` — the Int32/Contiguous paths behind `array.length = n`, `Array.prototype.splice` and `shift` — move elements with `gcSafeMemmove()` and then cleared the vacated butterfly slots with a `WriteBarrier::clear()` loop, which clang compiles to a call to libc `memset()`. The GC's parallel marker scans that same butterfly on a helper thread without a lock, and libc makes no promise about store width: musl's `memset` writes the head and tail of the range with 1-, 2- and 4-byte and unaligned 8-byte stores (glibc happens to use 8-byte-or-wider stores for these sizes). So on `*-musl` builds (Alpine images, musl `--compile` targets) a marker thread could load a half-cleared slot — the low byte, or the low five bytes, of the pointer that was there — treat it as a `JSCell*`, and: - SIGSEGV on a `HeapHelper` thread in `JSObject::visitChildren` / `SlotVisitor::appendHiddenSlow` at `<garbage & ~0x3fff> + 0x20` (e.g. `0x20`, `0x8f6c954020`), or - SIGSEGV at `0xd0` in `SlotVisitor::drain` after the torn pointer was marked and pushed, or - a mark bit / cell-state byte written at a non-cell offset in an unrelated block (later crashes anywhere), or - a hung process with a marker parked in `MarkedBlock::aboutToMarkSlow` → `CountingLock::lockSlow` while the mutator waits in `Heap::runFixpointPhase`. A 25-line script (64 arrays of 3000 objects, `a.splice(N - 6, 3)` + refill in a loop) crashes `oven/bun:1.4.1-alpine` within seconds with default options, 6/6 runs; the glibc image and the same musl image with an `LD_PRELOAD` memset that only does 8-byte stores both run clean. The clears now use `gcSafeZeroMemory()`, and the unlocked in-place ArrayStorage grow path in `JSObject::increaseVectorLength` fences before publishing the larger vector length. **oven-sh/WebKit#560 — CodeBlock aging** drops the per-allocation byte counter added in oven-sh/WebKit#557 and ages idle optimized code against the last collection that saw allocation instead. ### Related reports - Fixes #19895 — musl x64, `HeapHelper` thread in `JSObject::visitChildren` → `visitButterfly` under `SlotVisitor::drain`; the fault address `0x7623000020` is a butterfly pointer with bytes 0–2 and 5–6 zeroed, which is exactly musl `memset`'s intermediate state when clearing a single 8-byte slot. - Fixes #17792 — musl x64-baseline, long-running `next start`, parallel marker `SlotVisitor::drain` → `visitChildren` faulting at `0xd0`, i.e. a torn pointer that was marked and then visited. - Not this bug, deliberately not marked: the glibc reports with marker-thread stacks (#32109, #30205, #30191, #34476, #26678, #28990) — glibc's `memset` does not tear these slots, and their fault addresses (`0x703b1a408020`, `0x800000020`, `0xe00000020`, …) point at a stale block or an `IndexingHeader` read rather than a torn pointer.
Problem
JSArray::setLengthandJSArray::shiftCountWithAnyIndexingType— the Int32/Contiguous paths behindarray.length = n,Array.prototype.spliceandshift— move elements withgcSafeMemmove()and then clear the vacated slots with a loop ofWriteBarrier<Unknown>::clear(). Clang's loop-idiom pass compiles that loop to a call to libcmemset()(releaselibJavaScriptCore:memset@pltwithWriteBarrier.hclear()inlined atJSArray.cpp:1309and:1734; an unmodified upstream JSCOnly build has the same calls at the same loops).Nothing serializes these two clears with the collector: the butterfly is live, and
JSObject::visitButterflyscans Contiguous butterflies on a marker thread without takingcellLock()(it only does that for ArrayStorage shapes, whose shift/unshift paths hold the lock). libc makes no promise about store width. musl's x86_64memsetwrites the head and tail of the range with 1-, 2- and 4-byte and unaligned 8-byte stores for n ≤ 126, and its generic Cmemset(used on aarch64) starts with byte stores too. So the marker can load a torn JSValue out of a slot that is being cleared — for the last slot of the range musl zeroes byte 7, then bytes 5–6, then bytes 1–4, so the marker sees the low five bytes (0x0000008f6c954020) or the low byte (0x20) of the pointer that was there; for the first slot it sees that pointer with its low one or three bytes zeroed — and treats it as aJSCell*.On an x86_64-musl build this reproduces in seconds with ordinary code and default options:
Depending on the torn value the outcome is a SIGSEGV in
SlotVisitor::appendHiddenSlow/JSObject::visitChildrenreading theMarkedBlockheader of a garbage block address,MarkedBlock::aboutToMarkSlow→analyzeInvalidHandleAndCrash, a SIGSEGV at0xd0inSlotVisitor::drainafter the torn pointer was marked and pushed, a mark bit and cell-state byte written at a non-cell offset in an unrelated block, or a marker parked forever inMarkedBlock::aboutToMarkSlow→CountingLock::lockSlowwhile the mutator waits inHeap::runFixpointPhase. glibc'smemsethappens to use 8-byte-or-wider stores for these shapes, so glibc builds don't show it, but that is not something to rely on.Fix
Clear those slots with
gcSafeZeroMemory(), the primitive JSC already uses for stores the concurrent marker can observe (unshiftCountSlowCaseuses it a few lines away, next to the samegcSafeMemmove()calls). No other change.Verification
objdumpof a JSCOnly release build (clang 21):memset@pltinJSArray::setLengthandJSArray::shiftCountWithAnyIndexingTypebefore, no libc calls in either after. Every otherWriteBarrierclear loop that the compiler turns intomemset/memcpyin this tree (creation paths inJSArray,JSObject,JSCellButterfly,JSOrderedHashTable,JSPropertyNameEnumerator, …, and thecellLock()-protected ArrayStorage shift/unshift) writes storage the marker cannot be scanning, so they are left alone.LD_PRELOADmemsetthat reproduces musl's store sequence (checked byte-for-byte against libcmemsetfor all offsets < 40 and sizes < 500), the loop above with 2048 arrays underjsc --useGenerationalGC=false --collectContinuously=true: before 14/14 runs crash within 4 s, after 0/16; with default options before 4/6, after 0/14. A mixed splice/length/front-splice/unshift variant: before 1/4, after 0/4. glibcmemset: 0/9 before and after.push/pop/shift/unshift/splice/length/fill/reverse/slice/deletesequences gives identical digests before and after, also under continuous GC;splice,shift,unshift,lengthtruncation andnew Array(n)microbenchmarks are unchanged.