Repository navigation
Conversation
…nced from past its end A word equal to the end of a MarkedBlock marked the last cell of that block when the block held Auxiliary or JSCellWithIndexingHeader cells, because a Butterfly* can point past the end of its storage. The memory after a MarkedBlock belongs to whoever the allocator gave it to. With mimalloc the JSC::VM itself can start there, and a VM* is in a register or a frame at every collection, so that cell never dies. For an Auxiliary cell that costs the cell. A JSCellWithIndexingHeader cell is a JSCellButterfly and has children. When it is a Map or Set table that the collection has replaced (rehash or clear), it points at the table that replaced it. So it keeps every later table, and each of those keeps the keys and values it held when it was replaced. A Set of two or three live 2 KB entries, one added and one deleted per cycle, grew the heap by 2.8 KB per cycle. A Map that only ever became empty again grew it by 56 bytes per set + delete. The past-the-end case exists for Auxiliary storage only: a butterfly with no IndexingHeader and no indexed payload is computed sizeof(IndexingHeader) past its end. A JSCellButterfly holds its IndexingHeader inside the cell, and toButterfly() is the cell plus sizeof(JSCellButterfly). That is the end of the cell only for a zero-length butterfly, which is a 16-byte cell. In a longer one it is an interior pointer, and an interior pointer finds its cell without the past-the-end rule. So apply the rule to JSCellWithIndexingHeader only for 16-byte cells and only at exactly the end. Auxiliary cells keep the full sizeof(IndexingHeader) slack. The same test now guards the previous-block rule, the left-neighbour rule and PreciseAllocation::contains().
There was a problem hiding this comment.
I reviewed this and didn't find any bugs — the reasoning and arithmetic check out — but since it narrows conservative GC root scanning (the direction where a mistake is a use-after-free) and Source/JavaScriptCore is CODEOWNERS-gated, a human JSC reviewer should still sign off.
What was reviewed:
mayBeReferencedFromPastTheEndis strictly narrower than the oldmayHaveIndexingHeadergate only forJSCellWithIndexingHeader;JSCellandAuxiliarybehavior is unchanged.JSCellButterfly::toButterfly()iscell + offsetOfData()(=cell + 16), so itsButterfly*is past-the-end only for a 16-byte cell and then exactly at the end — matchescellSize == sizeof(JSCellButterfly) && !bytesPastTheEnd.- The three call sites' overshoot arithmetic:
pointer - candidatefor the previous block,pointer - alignedPointerfor the left neighbour, and the PreciseAllocation gate falling through to the<= endbound forJSCellWithIndexingHeader. JSCellWithIndexingHeaderis used only byimmutableButterflyAuxiliarySpace(JSCellButterfly), so no other cell type loses coverage.
Extended reasoning...
Overview
This PR tightens the past-the-end pointer handling in Source/JavaScriptCore/heap/ConservativeRoots.cpp. It replaces the coarse mayHaveIndexingHeader(kind) gate at three sites (PreciseAllocation bounds, previous-MarkedBlock last-cell, and left-neighbour-in-same-block) with a new mayBeReferencedFromPastTheEnd(kind, cellSize, bytesPastTheEnd) predicate that encodes exactly when a Butterfly* can legitimately land at or past a cell's end. For Auxiliary the 8-byte slack is preserved; for JSCellWithIndexingHeader only the exact end of a sizeof(JSCellButterfly)-sized cell is accepted; JSCell remains excluded. The motivation is a real leak where a VM* in a register at every collection aliases the end of a MarkedBlock of Map/Set tables, pinning a NextTable chain forever.
Security risks
Conservative root scanning is what keeps C++-visible JS objects alive across GC. Narrowing it is the memory-safety-risky direction: a false negative means an object is collected while a live Butterfly* still refers to it, i.e. use-after-free. I verified the invariant the change relies on — JSCellButterfly::toButterfly() returns cell + offsetOfData() (rounded sizeof(JSCellButterfly), i.e. 16), so the only past-the-end case is a zero-length 16-byte cell with the pointer exactly at its end — and that JSCellWithIndexingHeader is used solely by immutableButterflyAuxiliarySpace. The overshoot computations at each call site are correct (pointer - candidate is the offset into the next block = distance past the previous block's end; pointer - alignedPointer is the offset into the right-hand cell; the PreciseAllocation site passes sizeof(IndexingHeader) so JSCellWithIndexingHeader falls to the <= end branch, which still covers the zero-length case). There is no injection/auth/data-exposure surface here; the risk is purely GC correctness.
Level of scrutiny
High. This is core GC marking logic where an off-by-one or a missed producer of past-the-end pointers would manifest as rare, allocator-layout-dependent UAFs. The path is also under CODEOWNERS (/Source/JavaScriptCore → WebKit/jsc-reviewers). Per the approval guidelines, CODEOWNERS coverage plus memory-safety-critical narrowing means a human reviewer with JSC heap expertise should confirm the invariant that no other code path (including JIT lowerings of toButterfly) can produce a Butterfly* more than 0 bytes past a JSCellWithIndexingHeader cell.
Other factors
The PR description reports targeted testing under collectContinuously=1, slowPathAllocsBetweenGCs, useJIT=0, and scribbleFreeCells=1 sweepSynchronously=1, plus the Map/Set repros going flat, which is the right kind of coverage for this change. The diff is small, well-commented, and self-contained to one file. I found no logic errors, but the correctness argument leans on layout invariants (sizeof(JSCellButterfly) == 16, size-class alignment, JSCellButterfly being the sole JSCellWithIndexingHeader occupant) that a JSC reviewer should ratify.
Preview Builds
|
|
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 (1)
Included review availability: Your plan provides up to 5 included reviews per hour; 1 remains after this review. WalkthroughThe change adds cell-kind- and offset-aware validation for past-the-end pointers in conservative root detection. Precise allocations, previous-block butterflies, and adjacent-cell fallback checks now use this validation. ChangesConservative root boundary validation
Priority: ➖ Normal Merge Risk: ⚪ Minimal · up to No actionable merge-blocking risk is currently supported. 🚥 Pre-merge checks | ✅ 3 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description provides a detailed, relevant explanation of the bug, fix, reproductions, and validation. It does not include the required Bugzilla link, review status line, or changed-file and function list from the repository template.
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 |
|
Closing: #636 is the same fix for the same bug and was opened first. The one difference and the evidence from this PR are noted there. |
Problem
MaporSetwhose entries come and go leaks: 56 bytes perset+deleteon an empty Map (534 MB after 10M cycles), 2.8 KB per cycle with two live 2 KB entries. A full GC frees nothing.node:httptracks connections in such a Set.genericAddPointer(heap/ConservativeRoots.cpp:139) takes a word equal to the end of a MarkedBlock for a reference to its lastAuxiliaryorJSCellWithIndexingHeadercell. With mimalloc theJSC::VMstarts there, and aVM*is in a register at every collection, so that cell is immortal. When it is a replaced Map or Set table, itsNextTablepointer keeps every later table and their entries.Fix
mayBeReferencedFromPastTheEnd()guards the previous-block rule, the left-neighbour rule andPreciseAllocation::contains().Auxiliarykeeps its 8 bytes of slack.JSCellWithIndexingHeaderkeeps only the exact end of a 16-byte cell.Butterfly*"for a zero-vector-length butterfly without an indexing header is computed one header past the end". OnlyAuxiliarystorage can lack the header.JSCellButterfly::toButterfly()iscell + 16: the end of a zero-length (16-byte) cell, an interior pointer in any longer one.add #2seessize=0. The Bun PR that pins this preview build adds the test: unfixed keeps 2.2 to 9 MB, fixed 5 KB.Background
Butterfly*can sit 8 bytes past its storage, so kinds that hold butterfly storage get that slack. [JSC] ConservativeRoots: no past-the-end butterfly slack for cells that cannot hold a butterfly (MarkedBlock rule + PreciseAllocation::contains) #398 removed it for plainJSCell.JSCellButterfly(anIndexingHeaderplus JSValues) isMapandSetstorage. A rehash or a clear links the old table to the new one (NextTable) so that a live iterator can move forward.Notes
Repros, release build of Bun main (WebKit cf1b36e), Linux x64, CommonJS entry point:
How the retainer was found:
JSCellButterfly::visitChildrenappends its slots hidden, so the snapshot has no edge from one table to the next: in a leaking run, 102,430 of 102,434Cell Butterflynodes have no incoming edge and no root entry, and only the first of them lacks a real referrer./proc/<pid>/mem, collected every cell with the table's header, and walked theNextTablechain backwards fromm_storage. It ends at a table atVM - 0xe0: the last cell of the MarkedBlock whose end is theVM(JSC__VM__runGC'srdi, and them_vmfield of that block's header).ConservativeRoots::add(void*, void*, JITStubRoutineSet&, CodeBlockSet&)during the thirdBun.gc(true). The only word in the register range that is in or near that cell is theVM*. The stack range holds the sameVM*in about 30 more slots. After the stack scan the root set holds the table 5 times and 112 other cells.VMstill follows a table block,add #2seessize=0, and after the stack scan none of the 96 roots isVM - 0xe0.It is layout dependent, not a regression in one release. With the same two scripts Bun 1.2.0, 1.3.11, 1.3.12 and 1.4.3 leak, and 1.1.34, 1.2.23, 1.3.0 and 1.3.5 do not. On 1.4.3 the script leaks as a CommonJS entry point and does not leak as ESM. In 1.3.11 the block before the
VMholds 320-byte tables and the mechanism is the same.An
Auxiliarycell that the rule keeps costs only the cell: the collector does not visit an auxiliary cell. AJSCellButterflyis visited, which is what makes the chain possible.PreciseAllocationkeeps #398's inclusive<= endbound for every kind that gets no slack.Also run on the fixed build:
test/js/bun/jsc-stress/,test/js/bun/jsc/,test/js/bun/gc/,inspect.test.js,structured-clone.test.ts,expect.test.js, and a Map/Set/spread script (iteration across replaced and cleared tables, a live iterator across 100 rehashes, zero-length spreads) undercollectContinuously=1,slowPathAllocsBetweenGCs=3and5,useJIT=0, andscribbleFreeCells=1 sweepSynchronously=1. All give the same output as the unfixed build.