Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 5 additions & 0 deletions src/jsc/VirtualMachine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,7 @@ unsafe extern "C" {
safe fn Bun__Process__resetArgv(global: &JSGlobalObject);
safe fn Bun__TestFile__leaveModuleGraph(global: &JSGlobalObject);
safe fn Zig__GlobalObject__retireDerivedRealmsForTestIsolation(global: &JSGlobalObject);
safe fn V8GlobalHandleRegistry__retireHandlesOfObjects(global: &JSGlobalObject);
safe fn Zig__GlobalObject__destructOnExit(global: &JSGlobalObject);
safe fn WebWorker__teardownJSCVM(global: &JSGlobalObject);
}
Expand Down Expand Up @@ -2778,6 +2779,8 @@ impl VirtualMachine {
Teardown::Worker => WebWorker__teardownJSCVM(vm.global()),
Teardown::MainThreadExit => Zig__GlobalObject__destructOnExit(vm.global()),
}
// This thread's default global object is destroyed. Null rather than `None`, which would cache the freed `global` again.
VMHolder::set_cached_global_object(Some(core::ptr::null_mut()));
// Finalizers just closed the sockets only they owned; `us_socket_close`
// queues onto `loop->data.closed_head`, normally freed on the next tick.
vm.uws_loop_mut().drain_closed_sockets();
Expand Down Expand Up @@ -6588,6 +6591,8 @@ impl VirtualMachine {
// The cleanup of an addon does not run when its file is retired, and an isolate that its hooks use goes with the realm.
rare.environment_cleanup_hooks.clear_and_free();
}
// No cleanup of the finished file ran, so its addons did not reset their `v8::Global`s. Those of objects let go here, so that none keeps the realm of the file alive.
V8GlobalHandleRegistry__retireHandlesOfObjects(self.global());

self.undo_process_env_side_effects();
self.undo_synthetic_allocation_limit();
Expand Down
1 change: 1 addition & 0 deletions src/jsc/bindings/BunClientData.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
#include "ModuleGraph.h"
#include "StrongRootBlock.h"
#include "IsolatedModuleCache.h"
#include "v8/shim/GlobalHandleRegistry.h"

namespace WebCore {
using namespace JSC;
Expand Down
9 changes: 9 additions & 0 deletions src/jsc/bindings/BunClientData.h
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,12 @@ class DecoderStringTable;
class PrelinkedModuleGraph;
}

namespace v8 {
namespace shim {
class GlobalHandleRegistry;
}
}

namespace Bun {
// Out-of-line `JSC::Structure::create` / `JSC::reifyStaticProperties` for the
// once-per-class setup paths, so each wrapper class doesn't inline them.
Expand Down Expand Up @@ -310,6 +316,9 @@ class JSVMClientData : public JSC::VM::ClientData {
WTF::UncheckedKeyHashMap<WTF::String, RefPtr<JSC::SourceProvider>> isolationSourceProviderCache;
Vector<Bun::IsolatedInternalModule> isolationInternalModules;

// The handles of this VM's v8::Globals (v8/shim/GlobalHandleRegistry.h). Null until a realm of the VM uses the V8 API.
std::unique_ptr<v8::shim::GlobalHandleRegistry> v8GlobalHandleRegistry;

void reconcileWeakReferencesAtGCEnd(JSC::VM&, JSC::CollectionScope) final;

JSC::DecoderStringTable* decoderStringTable() final { return m_decoderStringTable.get(); }
Expand Down
2 changes: 1 addition & 1 deletion src/jsc/bindings/StrongRef.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ extern "C" void Bun__StrongRef__set(StrongRefImpl* _Nonnull ref, JSC::JSGlobalOb
decodeStrongRefBlock(ref)->write(JSC::getVM(globalObject), decodeStrongRefIndex(ref), JSC::JSValue::decode(encodedValue));
}

// The Rust caller (Strong.rs Impl::destroy) skips this call once
// Both callers (Strong.rs Impl::destroy, and GlobalHandleRegistry::dispose for the handle of a v8::Global) skip this call once
// VirtualMachine.is_shutting_down is true, so the block cell is guaranteed
// live here: destructOnExit / WebWorker__teardownJSCVM set that flag before
// their final collectNow, which is the only point the block can go dead while
Expand Down
13 changes: 13 additions & 0 deletions src/jsc/bindings/v8/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ src/jsc/bindings/v8/
│ ├── TaggedPointer.h # V8-style tagged pointer implementation
│ ├── Map.h # V8 Map objects for inline function compatibility
│ ├── GlobalInternals.h # V8 global state management
│ ├── GlobalHandleRegistry.h # The handles of a VM's v8::Globals (see "Global Handles" below)
│ ├── InternalFieldObject.h # Objects with internal fields
│ └── Oddball.h # Primitive values (undefined, null, true, false)
├── node.h # Node.js module registration compatibility
Expand Down Expand Up @@ -228,6 +229,18 @@ For `ObjectTemplate` or `FunctionTemplate` implementations, see existing pattern
- Handle scopes automatically clean up when destroyed
- Node-API and the V8 API share one handle scope implementation, `Bun::HandleScopeImpl` (`src/jsc/bindings/napi_handle_scope.h`). `v8::HandleScope` and `Bun::NapiHandleScope` both open one, and `currentHandleScope()` returns the V8 handle storage of the innermost one, so V8 calls made from a Node-API callback work without any V8 scope of their own. Addons built against Node 26 headers never construct Bun's `v8::HandleScope` at all (it is inline); their scopes reach Bun only through `HandleScope::Extend` and `DeleteExtensions`.

### Global Handles

- A `v8::Global` (or `Persistent`) holds the address of a 24-byte handle. The per-VM `v8::shim::GlobalHandleRegistry` (`shim/GlobalHandleRegistry.h`, owned by `JSVMClientData`) owns the handles, in 512-byte blocks of 19 at addresses that are multiples of 512. So `DisposeGlobal`, `MakeWeak` and `ClearWeak` find the block, and with it the Bun VM that owns the handle (`ownerBunVM`), from the address of the handle alone.
- No realm owns a Global handle, and the collector never reads one. A handle that holds a cell has a strong root from `Bun__StrongRef__new` (`StrongRef.h`, what `bun_jsc::Strong` uses). So a Global keeps its value, and what the value references, until it is reset, until it is retired, or until its VM ends.
- A retired handle is what a Global of an object becomes when `bun test --isolate` replaces the global object after a file (`retireHandlesOfObjects()`, called by `swap_global_for_test_isolation`), so that no Global keeps the realm of a finished file alive. Its root is deleted, and it holds `undefined`. An addon reads a Global inline, so Bun cannot make one empty: `IsEmpty()` stays false and `Get()` returns `undefined`. The handle stays live until the addon's own `Reset()`, which frees it as any other, and `SetWeak()` and `ClearWeak()` still work on it. A handle of a string, a symbol, a BigInt or a number is not retired: these keep no realm alive, and such a Global keeps its value for the later files.
- `Reset()` marks the handle as disposed. The handle is released (root deleted, handle cleared and put on the free list) once no realm of the VM has an open scope with V8 handles: V8's inline `Local::New(isolate, global)` copies the Global's word, so a `Local` points into the Global's handle. The registry counts the `HandleScopeBuffer`s of the VM for that (`didOpenScope()`, `didCloseScope()`), and the last one to close releases the handles that wait.
- Once the Bun VM is shutting down, `Reset()` only marks the handle, because `Bun__StrongRef__delete` must not run then.
- `Reset()`, `SetWeak()` and `ClearWeak()` do nothing unless the Bun VM of the calling thread is the one that owns the block: not on a thread that has no VM, and not in another Worker. A thread id is not compared, because the system uses one again.
- When the VM ends, `~GlobalHandleRegistry` frees every block that has no live handle. A block with a Global that is still set is kept for the life of the process, with `registry` null: a later `Reset()` of that Global reads valid memory, and no later handle gets its address. Such a Global must not be read, as in V8.
- A Global of `undefined`, `null`, `true` or `false` has no cell: its handle holds the word that points at the Oddball. The four Oddballs are constants of the process (`shim/Oddball.h`), and the roots of every isolate point at them, so such a Global equals `Undefined(isolate)` (or the other three) in every realm, also after the realm that made it is collected.
- `SetWeak()` only stores its parameter for `ClearWeak()`. The value stays strongly rooted and the callback never runs.

### JSC Integration

- Use `localToJSValue()` to convert V8 handles to JSC values
Expand Down
13 changes: 13 additions & 0 deletions src/jsc/bindings/v8/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ src/jsc/bindings/v8/
│ ├── TaggedPointer.h # V8-style tagged pointer implementation
│ ├── Map.h # V8 Map objects for inline function compatibility
│ ├── GlobalInternals.h # V8 global state management
│ ├── GlobalHandleRegistry.h # The handles of a VM's v8::Globals (see "Global Handles" below)
│ ├── InternalFieldObject.h # Objects with internal fields
│ └── Oddball.h # Primitive values (undefined, null, true, false)
├── node.h # Node.js module registration compatibility
Expand Down Expand Up @@ -228,6 +229,18 @@ For `ObjectTemplate` or `FunctionTemplate` implementations, see existing pattern
- Handle scopes automatically clean up when destroyed
- Node-API and the V8 API share one handle scope implementation, `Bun::HandleScopeImpl` (`src/jsc/bindings/napi_handle_scope.h`). `v8::HandleScope` and `Bun::NapiHandleScope` both open one, and `currentHandleScope()` returns the V8 handle storage of the innermost one, so V8 calls made from a Node-API callback work without any V8 scope of their own. Addons built against Node 26 headers never construct Bun's `v8::HandleScope` at all (it is inline); their scopes reach Bun only through `HandleScope::Extend` and `DeleteExtensions`.

### Global Handles

- A `v8::Global` (or `Persistent`) holds the address of a 24-byte handle. The per-VM `v8::shim::GlobalHandleRegistry` (`shim/GlobalHandleRegistry.h`, owned by `JSVMClientData`) owns the handles, in 512-byte blocks of 19 at addresses that are multiples of 512. So `DisposeGlobal`, `MakeWeak` and `ClearWeak` find the block, and with it the Bun VM that owns the handle (`ownerBunVM`), from the address of the handle alone.
- No realm owns a Global handle, and the collector never reads one. A handle that holds a cell has a strong root from `Bun__StrongRef__new` (`StrongRef.h`, what `bun_jsc::Strong` uses). So a Global keeps its value, and what the value references, until it is reset, until it is retired, or until its VM ends.
- A retired handle is what a Global of an object becomes when `bun test --isolate` replaces the global object after a file (`retireHandlesOfObjects()`, called by `swap_global_for_test_isolation`), so that no Global keeps the realm of a finished file alive. Its root is deleted, and it holds `undefined`. An addon reads a Global inline, so Bun cannot make one empty: `IsEmpty()` stays false and `Get()` returns `undefined`. The handle stays live until the addon's own `Reset()`, which frees it as any other, and `SetWeak()` and `ClearWeak()` still work on it. A handle of a string, a symbol, a BigInt or a number is not retired: these keep no realm alive, and such a Global keeps its value for the later files.
- `Reset()` marks the handle as disposed. The handle is released (root deleted, handle cleared and put on the free list) once no realm of the VM has an open scope with V8 handles: V8's inline `Local::New(isolate, global)` copies the Global's word, so a `Local` points into the Global's handle. The registry counts the `HandleScopeBuffer`s of the VM for that (`didOpenScope()`, `didCloseScope()`), and the last one to close releases the handles that wait.
- Once the Bun VM is shutting down, `Reset()` only marks the handle, because `Bun__StrongRef__delete` must not run then.
- `Reset()`, `SetWeak()` and `ClearWeak()` do nothing unless the Bun VM of the calling thread is the one that owns the block: not on a thread that has no VM, and not in another Worker. A thread id is not compared, because the system uses one again.
- When the VM ends, `~GlobalHandleRegistry` frees every block that has no live handle. A block with a Global that is still set is kept for the life of the process, with `registry` null: a later `Reset()` of that Global reads valid memory, and no later handle gets its address. Such a Global must not be read, as in V8.
- A Global of `undefined`, `null`, `true` or `false` has no cell: its handle holds the word that points at the Oddball. The four Oddballs are constants of the process (`shim/Oddball.h`), and the roots of every isolate point at them, so such a Global equals `Undefined(isolate)` (or the other three) in every realm, also after the realm that made it is collected.
- `SetWeak()` only stores its parameter for `ClearWeak()`. The value stays strongly rooted and the callback never runs.

### JSC Integration

- Use `localToJSValue()` to convert V8 handles to JSC values
Expand Down
10 changes: 6 additions & 4 deletions src/jsc/bindings/v8/V8Isolate.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include "V8Isolate.h"
#include "V8HandleScope.h"
#include "V8String.h"
#include "shim/GlobalHandleRegistry.h"
#include "shim/GlobalInternals.h"
#include "ZigGlobalObject.h"
#include "real_v8.h"
Expand Down Expand Up @@ -167,11 +168,12 @@ Isolate::Isolate(shim::GlobalInternals* globalInternals)
// (next/limit/level, see HandleScope::Extend) inside this region, and relies on it starting
// out zeroed just like real V8's HandleScopeData::Initialize() leaves it.
, m_padding {}
, m_globalHandleRegistry(&shim::GlobalHandleRegistry::ensure(m_globalObject->vm()))
{
m_roots[kUndefinedValueRootIndex] = TaggedPointer(&globalInternals->m_undefinedValue);
m_roots[kNullValueRootIndex] = TaggedPointer(&globalInternals->m_nullValue);
m_roots[kTrueValueRootIndex] = TaggedPointer(&globalInternals->m_trueValue);
m_roots[kFalseValueRootIndex] = TaggedPointer(&globalInternals->m_falseValue);
m_roots[kUndefinedValueRootIndex] = TaggedPointer(const_cast<shim::Oddball*>(&shim::Oddball::undefined_value()));
m_roots[kNullValueRootIndex] = TaggedPointer(const_cast<shim::Oddball*>(&shim::Oddball::null_value()));
m_roots[kTrueValueRootIndex] = TaggedPointer(const_cast<shim::Oddball*>(&shim::Oddball::true_value()));
m_roots[kFalseValueRootIndex] = TaggedPointer(const_cast<shim::Oddball*>(&shim::Oddball::false_value()));
}

shim::HandleScopeBuffer* Isolate::currentHandleScope()
Expand Down
5 changes: 5 additions & 0 deletions src/jsc/bindings/v8/V8Isolate.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class HeapProfiler;
class Isolate;

namespace shim {
class GlobalHandleRegistry;
class GlobalInternals;
class HandleScopeBuffer;
}
Expand Down Expand Up @@ -90,6 +91,7 @@ class Isolate final {
Zig::GlobalObject* globalObject() { return m_globalObject; }
JSC::VM& vm() { return globalObject()->vm(); }
shim::GlobalInternals* globalInternals() { return m_globalInternals; }
shim::GlobalHandleRegistry& globalHandleRegistry() { return *m_globalHandleRegistry; }
// Returns the innermost open handle scope, where new handles are created (see GlobalInternals::currentHandleScope).
shim::HandleScopeBuffer* currentHandleScope();

Expand All @@ -115,6 +117,9 @@ class Isolate final {
// include in this layout-sensitive header). Placed after m_roots so the
// kIsolateRootsOffset static_assert is unaffected.
void* m_heapProfiler { nullptr };

// The v8::Global handles of the VM of this isolate's realm. JSVMClientData owns it, so it outlives the isolate.
shim::GlobalHandleRegistry* m_globalHandleRegistry;
};

} // namespace v8
Loading
Loading