Skip to content
Merged
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
1e11d48
timers: root armed wrappers via a segmented table; free AbortSignal.t…
robobun Jul 26, 2026
761cded
timers: root segments as a linked list on ZigGlobalObject; reclaim em…
robobun Jul 26, 2026
1504052
AbortSignal: keep timeout wrapper alive while an any() dependent obse…
robobun Jul 26, 2026
f44f4ea
timers: keep timeout wrapper for all observer kinds; survive --isolat…
robobun Jul 26, 2026
f9d1f87
AbortSignal: protect this before toJS() in the CommonAbortReason over…
robobun Jul 26, 2026
9241d72
timers: tombstone root_slot in finalize; disarm in the is_timer_done …
robobun Jul 26, 2026
be1170c
timers: arm_root uses vm.global so ShadowRealm timers share the per-V…
robobun Jul 26, 2026
585aa62
timers: arm after reschedule in do_refresh; report segment extra memo…
robobun Jul 26, 2026
7f5d48d
test: isolate the refresh() re-root check from module-scope bindings
robobun Jul 26, 2026
e8e8e79
test: actually GC between refresh() fires
robobun Jul 26, 2026
5afb514
test: widen the AbortSignal.timeout RSS leak margin
robobun Jul 26, 2026
d751816
test: make the refresh() re-root test actually probe the segment slot
robobun Jul 26, 2026
53d93c9
Merge branch 'main' into farm/f99b9100/timer-gc-roots
Jarred-Sumner Jul 29, 2026
43d1705
ci: retrigger
robobun Jul 29, 2026
e6ef252
Merge branch 'main' into farm/f99b9100/timer-gc-roots
robobun Jul 30, 2026
0c572ec
JSTimerRootSegment: inline std::array slots; AbortSignal: atomic algo…
robobun Jul 30, 2026
ae24e3e
AbortSignal: hasTimeoutObserver() reads one atomic
robobun Jul 30, 2026
c52323f
JSTimerRootSegment: shrink capacity so the cell fits in a MarkedBlock
robobun Jul 30, 2026
0ae22a9
AbortSignal: balance m_timeoutObserverCount across markAborted and du…
robobun Jul 30, 2026
f87d271
Strong: back bun_jsc::Strong with StrongRootBlock instead of HandleSet
robobun Jul 30, 2026
8043b1a
StrongRootBlock: root from JSVMClientData via a marking constraint; e…
robobun Jul 30, 2026
f7c60e6
StrongRootBlock: add an allocation cursor so acquire() is O(1) in the…
robobun Jul 30, 2026
c9abf29
StrongRootBlock: inline get/clear on the Rust side via slot-pointer e…
robobun Jul 30, 2026
b3ba56c
Sweep stale AbortSignal self-ref/cycle comments in Response/jsc_hooks…
robobun Jul 30, 2026
6dfdb66
Strong: tolerate destroy() off the JS thread and Bun__StrongRef__dele…
robobun Jul 30, 2026
6a1524b
StrongRef: drop the s_clientData thread_local; debug_assert off-threa…
robobun Jul 30, 2026
2c02882
Sweep remaining HandleSet/HandleSlot rationale comments; drop redunda…
robobun Jul 30, 2026
dc8e2c3
clippy: ptr_as_ptr + undocumented_unsafe_blocks in Strong.rs
robobun Jul 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 17 additions & 13 deletions src/jsc/AbortSignal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -290,11 +290,10 @@ pub struct Timeout {
/// this field, so it must stay at a fixed offset (hence `#[repr(C)]`).
pub event_loop_timer: EventLoopTimer,

/// The `Timeout`'s lifetime is owned by the AbortSignal.
/// But this does have a ref count increment.
// AbortSignal is an opaque C++ type with intrusive WebCore
// refcounting (ref/unref) that crosses FFI — PORTING.md §Pointers: never
// Arc here. Kept as raw `*mut` with manual unref.
/// Raw back-pointer to the owning `AbortSignal`; no refcount held. The
/// `Timeout` is owned by the signal (`m_timeout`, freed via
/// `~AbortSignal` → `cancelTimer` → [`AbortSignal__Timeout__deinit`]),
/// so while this box is live the signal is too.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub signal: *mut AbortSignal,

/// "epoch" is reused.
Expand Down Expand Up @@ -371,15 +370,19 @@ impl Timeout {

// The signal and its handlers belong to a previous isolated test
// file's global; firing now would run them against the new global.
// Drop the extra ref that signalAbort() would have released.
// The `Timeout` box is still owned by the signal and will be freed
// via `~AbortSignal` → `cancelTimer` when the wrapper is collected.
Comment thread
robobun marked this conversation as resolved.
Resolved
if (*this).generation != (*vm).test_isolation_generation {
(*(*this).signal).unref();
return;
}

// Dispatching the signal may cause the Timeout to get freed.
// Capture the raw ptr before `this` may dangle.
// `signal` is a raw back-pointer with no refcount of its own;
// see the field doc for why it is valid here. `dispatch` may free
// `this` re-entrantly (markAborted → cancelTimer → deinit), so
// capture the pointer first. Nulled at VM teardown; that path does
// not re-enter `run`.
Comment thread
robobun marked this conversation as resolved.
Resolved
let signal_ptr: *mut AbortSignal = (*this).signal;
debug_assert!(!signal_ptr.is_null());
Self::dispatch(vm, signal_ptr);
}
}
Expand All @@ -391,10 +394,10 @@ impl Timeout {
// drop even if `signal` unwinds, and holds the raw VM-owned pointer so
// borrowck doesn't see two live `&mut EventLoop` across re-entrant JS.
let _guard = vm.enter_event_loop_scope();
// signalAbort() releases the extra ref from timeout() after all
// abort work completes, so we must not unref here.
// `AbortSignal` is an `opaque_ffi!` ZST handle; `opaque_ref` is the
// centralised non-null deref proof (held alive by the extra ref above).
// centralised non-null deref proof. `signalAbort()` takes
// `Ref protectedThis` internally so `signal_ptr` stays valid for the
// whole dispatch even though abort listeners can trigger GC.
Comment thread
robobun marked this conversation as resolved.
Resolved
AbortSignal::opaque_ref(signal_ptr).signal(vm.global(), CommonAbortReason::Timeout);
}

Expand All @@ -410,7 +413,8 @@ impl Timeout {
}
}

/// Caller is expected to have already ref'd the AbortSignal.
/// The returned `Timeout` is owned by `signal_` (stored in `m_timeout`) and
/// holds a raw back-pointer to it; caller retains its own ref on `signal_`.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[unsafe(no_mangle)]
extern "C" fn AbortSignal__Timeout__create(
vm: *mut VirtualMachine,
Expand Down
8 changes: 4 additions & 4 deletions src/jsc/JSRef.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@ use crate::{JSGlobalObject, JSValue};
/// See ServerWebSocket, UDPSocket, MySQLConnection, and ValkeyClient for examples.
///
/// `JsRef` is `!Send + !Sync` (transitively via `JSValue` and `Strong`): the
/// `HandleSlot` backing `Strong` is owned by the VM's `HandleSet` and must be
/// dropped on the JS thread.
/// `StrongRootBlock` slot backing `Strong` hangs off the per-VM JSVMClientData
/// and must be dropped on the JS thread.
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
pub enum JsRef {
Weak(JSValue),
Strong(Strong),
Expand Down Expand Up @@ -151,7 +151,7 @@ impl JsRef {
match self {
JsRef::Weak(_) => {}
JsRef::Strong(_) => {
// `Strong`'s `Drop` deallocates the HandleSlot when `*self` is
// `Strong`'s `Drop` releases the block slot when `*self` is
// overwritten below, so no explicit deinit is needed.
}
JsRef::Finalized => {
Expand Down Expand Up @@ -222,7 +222,7 @@ impl JsRef {

pub fn finalize(&mut self) {
// Overwriting `*self` drops the prior variant (releasing the `Strong`
// HandleSlot via its `Drop`), so no explicit deinit step is needed.
// block slot via its `Drop`), so no explicit deinit step is needed.
// External `jsref.deinit()` callers become `*jsref = JsRef::empty()`.
*self = JsRef::Finalized;
}
Expand Down
74 changes: 53 additions & 21 deletions src/jsc/Strong.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
pub struct Strong {
handle: NonNull<Impl>,
// NonNull<T> is already !Send + !Sync, matching the requirement that
// Strong must be dropped on the JS thread (HandleSet is VM-owned).
// Strong must be dropped on the JS thread (the StrongRootBlock list hangs
// off the per-VM JSVMClientData).
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
}

impl Strong {
Expand Down Expand Up @@ -160,65 +161,96 @@
}

bun_opaque::opaque_ffi! {
/// Opaque FFI handle. Backed by a `JSC::JSValue`-sized HandleSlot; see Strong.cpp.
/// Opaque FFI handle to a `Bun::StrongRef` (one occupied slot in a
/// `Bun::StrongRootBlock`); see StrongRef.cpp.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub struct Impl;
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
}

impl Impl {
// Low 48 bits of the handle point at the `WriteBarrier<Unknown>` slot (a
// `JSC::JSValue`); see `encodeStrongRef` in StrongRef.cpp.
Comment thread
robobun marked this conversation as resolved.
Resolved
const SLOT_MASK: usize = (1usize << 48) - 1;

#[inline(always)]
fn slot_ptr(this: NonNull<Impl>) -> *mut crate::DecodedJSValue {
(this.as_ptr() as usize & Self::SLOT_MASK) as *mut crate::DecodedJSValue
}

pub(crate) fn init(global: &JSGlobalObject, value: JSValue) -> NonNull<Impl> {
crate::mark_binding!();
NonNull::new(Bun__StrongRef__new(global, value)).expect("Bun__StrongRef__new returned null")
}

#[inline(always)]
pub fn get(this: NonNull<Impl>) -> JSValue {
// `this` is actually a pointer to a `JSC::JSValue`; see Strong.cpp.
// SAFETY: HandleSlot storage is a live, aligned JSC::JSValue for the
// lifetime of the Impl handle; `DecodedJSValue` is its `#[repr(C)]`
// ABI-compatible mirror.
unsafe { (*this.as_ptr().cast::<crate::DecodedJSValue>()).encode() }
// SAFETY: StrongRef.cpp guarantees the low 48 bits address a live
// `JSC::JSValue`-sized slot for the lifetime of the handle;
// `DecodedJSValue` is its `#[repr(C)]` ABI mirror.
unsafe { (*Self::slot_ptr(this)).encode() }
}

pub fn set(this: NonNull<Impl>, global: &JSGlobalObject, value: JSValue) {
crate::mark_binding!();
Bun__StrongRef__set(Impl::opaque_ref(this.as_ptr()), global, value);
}

#[inline(always)]
pub(crate) fn clear(this: NonNull<Impl>) {
crate::mark_binding!();
Bun__StrongRef__clear(Impl::opaque_ref(this.as_ptr()));
// SAFETY: same slot-pointer invariant as `get`; clearing holds no
// barrier (WriteBarrier<Unknown>::clear() just stores encoded 0).
unsafe { (Self::slot_ptr(this) as *mut i64).write(0) };

Check failure on line 201 in src/jsc/Strong.rs

View workflow job for this annotation

GitHub Actions / cargo clippy

`as` casting between raw pointers without changing their constness
}

/// SAFETY: `this` must be a valid handle from `init`; consumed here (do not reuse).
pub(crate) unsafe fn destroy(this: NonNull<Impl>) {
crate::mark_binding!();
// Defensive: a corrupted slot pointer here segfaults inside JSC's
// HandleBlock::handleSet (the backing block is recovered by masking
// the slot to the block base, then `+0x10` is read), which loses the
// Rust caller frame. With panic=abort the crash-handler hook captures
// a Rust backtrace, so a `panic!` at this layer surfaces the *exact*
// call site that holds the corrupted Strong. The 0x10000 floor is
// Windows' default null-page guard; legitimate `Impl*` are bmalloc'd
// far above it.
if cfg!(debug_assertions) {
assert!(
(this.as_ptr() as usize) >= 0x10000,
"Strong<Impl>* corrupted ({:p}); owning struct was overwritten",
this.as_ptr(),
);
}
// destructOnExit / WebWorker__teardownJSCVM unprotect the global and
// run a final full GC whose sweep-time finalizers (and
// deinit_runtime_state after ~VM) can drop `Strong`s; past that point
// the encoded StrongRootBlock cell may be unmarked or the heap freed.
// `is_shutting_down` is set before either path reaches the final
// collection, and the handle carries no allocation, so skipping the
// slot release is the whole of teardown. The Rust VM TLS outlives ~VM.
Comment thread
robobun marked this conversation as resolved.
Resolved
match crate::virtual_machine::VirtualMachine::get_or_null() {
Some(vm) => {
if unsafe { (*vm).is_shutting_down() } {

Check failure on line 223 in src/jsc/Strong.rs

View workflow job for this annotation

GitHub Actions / cargo clippy

unsafe block missing a safety comment
return;
}
}
None => {
// Off the JS thread. `Strong` is !Send, so reaching here means
// an `unsafe impl Send` wrapper carried one by value and
// dropped it on a pool thread; the slot (and its rooted value)
// leak until that VM's teardown. The block bitset/count are
// not thread-safe to touch here. Flag in debug so the owning
// wrapper can queue the drop back to the JS thread instead.
Comment thread
robobun marked this conversation as resolved.
Resolved
debug_assert!(
false,
"bun_jsc::Strong dropped off the JS thread; slot leaks"
);
return;
}
}
// SAFETY: caller contract guarantees `this` is a live handle from
// `Bun__StrongRef__new`; ownership is transferred to C++ which frees it.
// `Bun__StrongRef__new`; C++ releases the block slot it encodes.
unsafe { Bun__StrongRef__delete(this.as_ptr()) };
}
}

// `Impl` and `JSGlobalObject` are opaque `UnsafeCell`-backed ZST handles, so
// `&Impl`/`&JSGlobalObject` are ABI-identical to non-null `*const T` and C++
// mutating through them (HandleSet slot write) is interior mutation invisible
// to Rust. `delete` consumes the C++ allocation and so stays `unsafe fn`.
// mutating through them (block slot write) is interior mutation invisible to
// Rust. The handle's low 48 bits point at the slot and the top 16 hold the
// index (no heap allocation); `delete` releases the slot and so stays `unsafe fn`.
Comment thread
robobun marked this conversation as resolved.
Resolved
unsafe extern "C" {
fn Bun__StrongRef__delete(this: *mut Impl);
safe fn Bun__StrongRef__new(global: &JSGlobalObject, value: JSValue) -> *mut Impl;
safe fn Bun__StrongRef__set(this: &Impl, global: &JSGlobalObject, value: JSValue);
safe fn Bun__StrongRef__clear(this: &Impl);
}
2 changes: 1 addition & 1 deletion src/jsc/VirtualMachine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1591,7 +1591,7 @@ impl VirtualMachine {
// `on_progress_update` would have dropped the JS-side ref, and
// without it the tasklet ⇄ `Box<AsyncHTTP>` cycle leaks. Must
// precede `destructOnExit` so `FetchTasklet::deinit` can drop its
// JSC `Strong`/`Weak` handles against a live HandleSet.
// JSC `Strong`/`Weak` handles against a live heap.
self.event_loop_mut().release_queued_tasks_for_shutdown();

if let Some(rare) = self.rare_data.as_deref_mut() {
Expand Down
2 changes: 1 addition & 1 deletion src/jsc/bindings/Bindgen/ExternTraits.h
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ template<> struct ExternTraits<JSC::JSValue> {
};

template<> struct ExternTraits<Bun::StrongRef> {
using ExternType = JSC::JSValue*;
using ExternType = Bun::StrongRefImpl*;

static ExternType convertToExtern(Bun::StrongRef&& cppValue)
{
Expand Down
47 changes: 46 additions & 1 deletion src/jsc/bindings/BunClientData.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
#include <JavaScriptCore/HeapInlines.h>
#include <JavaScriptCore/IsoHeapCellType.h>
#include <JavaScriptCore/JSDestructibleObjectHeapCellType.h>
// #include <JavaScriptCore/MarkingConstraint.h>
#include <JavaScriptCore/SimpleMarkingConstraint.h>
#include <JavaScriptCore/SubspaceInlines.h>
#include <JavaScriptCore/VM.h>
#include <wtf/MainThread.h>
Expand All @@ -27,6 +27,7 @@
#include "../../runtime/bake/BakeGlobalObject.h"
#include "napi_handle_scope.h"
#include "NativePromiseContext.h"
#include "StrongRootBlock.h"

namespace WebCore {
using namespace JSC;
Expand Down Expand Up @@ -121,6 +122,50 @@ void JSVMClientData::create(VM* vm, void* bunVM)
clientData->m_normalWorld = DOMWrapperWorld::create(*vm, DOMWrapperWorld::Type::Normal);

vm->heap.addMarkingConstraint(makeUnique<WebCore::DOMGCOutputConstraint>(*vm, clientData->heapData()));

// Root the StrongRootBlock list from the VM instead of any one global.
//
// JSC's collector alternates Fixpoint (world stopped: mutator suspended via
// finishChangingPhase / stopTheMutator; see worldShouldBeSuspended in
// CollectorPhase.cpp) with Concurrent (mutator running) phases. The
// constraint set is solved only during Fixpoint, so the lambda below never
// races the mutator's writes to m_strongRootBlockHead/Free.
//
// `GreyedByExecution` puts this in the "root" bucket
// (MarkingConstraintSet::didStartMarking tags it as an unexecuted root for
// iteration 1 and re-evaluates it on every return to Fixpoint after a
// mutator resumption), mirroring the "Sh" strong-handle constraint in
// Heap::addCoreConstraints: anything the mutator linked onto the list while
// running is picked up on the next Fixpoint.
//
// Eden vs. full: `appendUnbarriered` early-returns when `isMarked()`; eden
// keeps the previous full GC's `m_markingVersion`
// (MarkedSpace::beginMarking), so an old-gen head reads as marked and its
// `visitChildren` does not run on eden. Slots written into such a block
// since the last GC already fired `WriteBarrier::set` on the block cell
// (Heap::writeBarrierSlowPath -> addToRememberedSet -> m_mutatorMarkStack),
// and Fixpoint drains that stack to visit the dirtied block. A full GC
// bumps `m_markingVersion`, every cell reads unmarked, and the constraint
// seeds the whole `m_next` chain. Net: this body is O(1) per collection.
//
// `Concurrent` here means the constraint may run on a GC helper thread via
// MarkingConstraintSolver::runExecutionThread (MarkingConstraintSet still
// runs each constraint once per fixpoint iteration, gated by `m_executed`);
// it does not mean concurrent with the mutator. The lambda only reads three
// pointers and appends to the per-thread visitor, so helper-thread
// execution is safe. `clientData` outlives the Heap
// (~VM -> lastChanceToFinalize -> delete clientData), so the capture stays
// valid for every collection.
Comment thread
robobun marked this conversation as resolved.
Resolved
vm->heap.addMarkingConstraint(makeUnique<JSC::SimpleMarkingConstraint>(
"Srb", "Bun StrongRootBlocks",
MAKE_MARKING_CONSTRAINT_EXECUTOR_PAIR(([clientData](auto& visitor) {
JSC::SetRootMarkReasonScope rootScope(visitor, JSC::RootMarkReason::StrongHandles);
visitor.appendUnbarriered(clientData->m_strongRootBlockHead);
visitor.appendUnbarriered(clientData->m_strongRootBlockFree);
visitor.appendUnbarriered(clientData->m_strongRootBlockStructure);
})),
JSC::ConstraintVolatility::GreyedByExecution));

vm->m_typedArrayController = adoptRef(new WebCoreTypedArrayController(true));
clientData->builtinFunctions().exportNames();
}
Expand Down
16 changes: 16 additions & 0 deletions src/jsc/bindings/BunClientData.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ namespace Zig {
class GlobalObject;
}

namespace Bun {
class StrongRootBlock;
}

namespace WebCore {
using namespace JSC;
using namespace Zig;
Expand Down Expand Up @@ -127,6 +131,18 @@ class JSVMClientData : public JSC::VM::ClientData {
void* bunVM;
Bun::JSCTaskScheduler deferredWorkTimer;

// Linked list of StrongRootBlock cells backing bun_jsc::Strong handles
// (see StrongRootBlock.h). Raw pointers into the GC heap: they are rooted
// by a SimpleMarkingConstraint registered in JSVMClientData::create(), so
// no HandleSet node is needed and no GlobalObject owns them (ShadowRealm /
// node:vm / `bun test --isolate` globals share one list).
Comment thread
robobun marked this conversation as resolved.
Resolved
Bun::StrongRootBlock* m_strongRootBlockHead { nullptr };
Bun::StrongRootBlock* m_strongRootBlockFree { nullptr };
// Last block acquire() found room in; always on the active list (cleared by
// release() if unlinked), so it is already rooted via m_strongRootBlockHead.
Comment thread
robobun marked this conversation as resolved.
Resolved
Bun::StrongRootBlock* m_strongRootBlockCursor { nullptr };
JSC::Structure* m_strongRootBlockStructure { nullptr };

// Backing storage for Bun::IsolatedModuleCache (see IsolatedModuleCache.h).
// All access should go through that class. Stored as the JSC base type to
// avoid pulling ZigSourceProvider.h into this header; the cache class
Expand Down
Loading
Loading