Skip to content

HandleSet: assert the VM's API lock is held when mutating handles - #387

Open
robobun wants to merge 1 commit into
mainfrom
bun/handleset-api-lock-assert
Open

HandleSet: assert the VM's API lock is held when mutating handles#387
robobun wants to merge 1 commit into
mainfrom
bun/handleset-api-lock-assert

Conversation

@robobun

@robobun robobun commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

What does this PR do?

Adds a debug-only assertion to HandleSet::allocate, deallocate, and writeBarrier: the owning VM's API lock must be held by the current thread.

These three functions mutate m_strongList, which the GC's strong-handles marking constraint scans. The API lock is what orders those mutations with the scan, so a mutation from a thread that does not hold it is a data race. Heap::protect/unprotect already assert exactly this for the protect set; the Strong handle set never got the same assertion. Strong's own ShouldStrongDestructorGrabLock::Yes variant (which takes a JSLockHolder before deallocating) is existing acknowledgement of the invariant.

The motivating bug class is a Strong captured by value in a lambda that another thread destroys: the destructor then unlinks a node from the owner VM's m_strongList with no synchronization against that VM's GC. oven-sh/bun#30185 was exactly this (worker thread destroying a parent-VM Strong<JSPromise> captured in a cross-thread task), and it surfaced only as a rare, scheduling-dependent segfault at 0x10 (or a livelock) in the "Sh" marking constraint. Measurements in oven-sh/bun#36952 show that after bun's GC scheduling changed, the same reintroduced bug produced 0 crashes in 18,000 iterations of the old probabilistic stress guard, i.e. the bug class had no effective detector left.

With this assertion, any debug build reports the violating call site deterministically on the first mutation.

Implementation notes

  • assertMayMutate() is out-of-line in HandleSet.cpp because HandleSet.h cannot include VM.h (Heap.h includes HandleSet.h). Release builds get an empty inline and compile it out. Same shape as the existing isLiveNode debug helper.
  • VM member order keeps the check safe through teardown: m_apiLock is declared before heap, so member Strongs and the Heap's HandleSet are destroyed while the lock object is still alive, and VM::~VM already asserts the lock is held.

Verification

Validated in a bun debug+ASAN build linked against this JSC (linux x64):

  • Reintroducing the worker: fix cross-thread HandleSet race in getHeapSnapshot bun#30185 by-value Strong<JSPromise> capture in Worker.getHeapSnapshot()'s cross-thread lambda: the assertion fires on the first round-trip, every run, naming this invariant (previously: 0 detections in 18,000 iterations of the stress workload).
  • Without the reintroduced bug: bun's worker_threads and web worker suites (486 tests), including the heap snapshot/statistics cross-VM round-trip stress tests, pass with no assertion failures. Further suite coverage is being run via a bun PR pinned to this build.

HandleSet::allocate, deallocate, and writeBarrier mutate m_strongList,
which the GC's strong-handles marking constraint scans. The API lock is
what orders those mutations with the scan, so mutating from a thread
that does not hold it is a data race. Heap::protect/unprotect already
assert exactly this for the protect set; this adds the same assertion
to the Strong handle set.

The scheduling-dependent crash this turns deterministic: a Strong
captured by value in a cross-thread lambda, destroyed on the other
thread, corrupts the owner VM's m_strongList (oven-sh/bun#30185). That
class of bug previously surfaced only as a rare segfault or livelock in
the marking constraint; with this assertion any debug build reports the
violating call site on the first mutation.

Debug-only: assertMayMutate() compiles to an empty inline in release
builds.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't find any issues, but this adds an assertion to every Strong handle allocate/deallocate/writeBarrier — one of the most fundamental paths in JSC — so a maintainer should confirm the invariant is truly universal before it lands.

What was reviewed:

  • Confirmed Heap::protect/unprotect already assert the identical invariant, and ShouldStrongDestructorGrabLock::Yes takes a JSLockHolder before deallocating — the invariant is already acknowledged in-tree.
  • Verified the header-cycle rationale (Heap.h includes HandleSet.h) and that the out-of-line shape mirrors the existing isLiveNode helper; release builds get an empty inline.
  • Checked the teardown-safety claim: m_apiLock (VM.h:439) is declared before heap (VM.h:470), so the lock outlives the HandleSet.
Extended reasoning...

Overview

This PR adds a debug-only assertion (assertMayMutate()) to HandleSet::allocate, deallocate, and writeBarrier, requiring that the owning VM's API lock is held by the current thread. The implementation is out-of-line in HandleSet.cpp under #if ASSERT_ENABLED (because HandleSet.h cannot include VM.h — Heap.h includes HandleSet.h), with an empty inline stub in release builds. Two files touched, ~20 lines added, no logic changed.

Security risks

None. This is a debug-only diagnostic that reads thread/lock state and calls ASSERT_WITH_MESSAGE. It is compiled out entirely in release builds. It cannot introduce injection, auth, or data-exposure issues.

Level of scrutiny

Higher than the diff size suggests. HandleSet::allocate/deallocate/writeBarrier sit underneath every Strong<T> construction, destruction, and assignment in the engine. Asserting an invariant here is asserting it across the entire JSC codebase and every downstream consumer (Bun, and any WebCore paths this fork retains). If any legitimate call site — VM construction edge cases, compiler-thread teardown, inspector paths, etc. — mutates a handle without the API lock held, every debug build breaks. The PR description addresses teardown ordering and reports 486 passing tests in Bun's worker suites, which is good evidence, but Bun's test surface is not the same as JSC's own stress/test262 surface.

Other factors

  • The pattern is well-precedented: Heap::protect/unprotect already ASSERT(vm().currentThreadIsHoldingAPILock()) for the analogous protect set, and Strong's ShouldStrongDestructorGrabLock::Yes variant explicitly takes a JSLockHolder before calling deallocate. So the invariant being asserted is not novel — it is already documented behaviorally elsewhere in the tree.
  • The out-of-line-under-ASSERT / inline-empty-otherwise shape exactly mirrors the existing isLiveNode helper in the same file, so it is idiomatic for this code.
  • The PR description notes further suite coverage is still being run via a pinned Bun PR — results from that broader run would be useful signal.

Given the guideline that changes touching critical code paths should get human eyes even when they look correct, I'm deferring rather than approving.

@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown

Review Change Stack

Walkthrough

Summary

HandleSet now verifies VM API lock ownership before mutating strong-handle state. The check applies to allocation, deallocation, and write-barrier operations in assertion builds.

Changes

HandleSet mutation safety

Layer / File(s) Summary
Define mutation permission assertion
Source/JavaScriptCore/heap/HandleSet.cpp, Source/JavaScriptCore/heap/HandleSet.h
HandleSet::assertMayMutate() checks VM API lock ownership when assertions are enabled. The implementation adds the required VM header.
Guard HandleSet mutation entry points
Source/JavaScriptCore/heap/HandleSet.h
allocate, deallocate, and writeBarrier call assertMayMutate() before changing handle state.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the added VM API lock assertion for HandleSet mutations.
Description check ✅ Passed The description explains the bug, implementation, affected functions, rationale, and verification, but omits the repository template metadata.

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown

Preview Builds

Commit Release Date
f6049b84 autobuild-preview-pr-387-f6049b84 2026-08-05 11:33:15 UTC

@robobun

robobun commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Validation of this change inside bun is done in oven-sh/bun#36958, which pins this PR's preview build (autobuild-preview-pr-387-f6049b84):

  • Reintroducing the worker: fix cross-thread HandleSet race in getHeapSnapshot bun#30185 by-value Strong<JSPromise> capture in getHeapSnapshot's cross-thread lambda aborts on the first round-trip, every run, with ASSERTION FAILED: Strong handles may only be created, written, or destroyed while holding their VM's API lock (the old probabilistic guard: 0 detections in 18,000 iterations).
  • Without the planted bug: no assertion failures across bun's worker_threads, web workers, sqlite, Bun.password, node:vm, timers, plugin, bun:jsc, node:http2, and mock suites (~1,700 tests) on linux x64 debug+ASAN.

Once bun's CI is green over the preview build, this is ready to merge; the bun PR then flips its pin to the merge commit.

@robobun

robobun commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Heads-up for the next upstream merge: WebKit/WebKit@ff64aee116 (Aug 3, "[JSC] Introduce StrongBlock") deletes HandleSet.{h,cpp} in favor of StrongSet/StrongBlock, so this change will surface as a delete/modify conflict and needs porting:

  • the allocate/deallocate legs map mechanically onto StrongSet's slot acquire/release;
  • the writeBarrier leg has no single successor choke point in StrongSet, so the assert belongs wherever a slot's value is rewritten outside allocation.

bun-side enforcement exists as of oven-sh/bun#36958: a debug-lane test deliberately violates the contract from another thread and asserts the child dies with this assertion's message, so a bump that drops the port fails bun's debug CI instead of silently losing the detector.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant