Skip to content
Closed
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
16cf9b3
fix(workers): add WebWorkerLifecycleHandle to prevent use-after-free
robobun Mar 20, 2026
fc1066d
[autofix.ci] apply automated fixes
autofix-ci[bot] Mar 20, 2026
b60ac7e
fix: detach handle.worker before destroying WebWorker
robobun Mar 20, 2026
1fb6692
[autofix.ci] apply automated fixes
autofix-ci[bot] Mar 20, 2026
979d855
fix: null handle.worker in destroy() and use unrefConcurrently
robobun Mar 20, 2026
403354b
simplify: drop WebWorkerLifecycleHandle — put ThreadSafeRefCount dire…
alii Mar 20, 2026
18069fd
Merge branch 'main' into farm/8b799671/worker-lifecycle-handle
alii Mar 20, 2026
e5af6fa
fix: spawn failure parent ref leak, name buffer leak, updatePtr ref leak
robobun Mar 20, 2026
f47a946
fix: release Zig WebWorker ref in updatePtr failure, add double-unref…
robobun Mar 20, 2026
3cb9b1b
fix: move parent_poll_ref unref after dispatchExit, fix spawn failure…
robobun Mar 20, 2026
df4b3b7
fix: restore unref in notifyNeedTermination to prevent parent hang
robobun Mar 20, 2026
2859dc0
fix: release heap resources synchronously in exitAndDeinit
alii Mar 20, 2026
3cd267d
fix: guard releaseResources frees with length checks
robobun Mar 20, 2026
ed28231
fix: remove flaky double-terminate test
robobun Mar 20, 2026
8d7f8e7
test: add back double-terminate test (sequential, not racy)
robobun Mar 20, 2026
47161c9
test: add concurrent terminate test (fire-and-forget, no await)
robobun Mar 20, 2026
42ed136
fix(workers): keep parent keep-alive ref'd until exitAndDeinit
alii Mar 20, 2026
9c30d51
fix: explicit unrefConcurrently in spawn failure path
robobun Mar 20, 2026
d133a93
Revert "fix(workers): keep parent keep-alive ref'd until exitAndDeinit"
robobun Mar 20, 2026
d254d52
ci: retrigger build
robobun Mar 20, 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
28 changes: 20 additions & 8 deletions src/bun.js/bindings/webcore/Worker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ namespace WebCore {

WTF_MAKE_TZONE_ALLOCATED_IMPL(Worker);

extern "C" void WebWorker__notifyNeedTermination(
void* worker);
extern "C" void WebWorker__requestTermination(void* worker);
extern "C" void WebWorker__release(void* worker);

static Lock allWorkersLock;
static HashMap<ScriptExecutionContextIdentifier, Worker*>& allWorkers() WTF_REQUIRES_LOCK(allWorkersLock)
Expand Down Expand Up @@ -133,14 +133,22 @@ extern "C" void WebWorker__setRef(

void Worker::setKeepAlive(bool keepAlive)
{
WebWorker__setRef(impl_, keepAlive);
if (impl_)
WebWorker__setRef(impl_, keepAlive);
}

bool Worker::updatePtr()
{
if (!WebWorker__updatePtr(impl_, this)) {
m_onlineClosingFlags = ClosingFlag;
m_terminationFlags.fetch_or(TerminatedFlag);
// Release the C++ ref on the Zig WebWorker — the destructor
// won't do this since we're about to null impl_.
WebWorker__release(impl_);
impl_ = nullptr;
// Balance the ref() taken in create() — the Zig thread never
// started so WebWorker__dispatchExit will never run.
deref();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return false;
}

Expand Down Expand Up @@ -207,15 +215,15 @@ ExceptionOr<Ref<Worker>> Worker::create(ScriptExecutionContext& context, const S
execArgv.size(),
preloadModules.begin(),
preloadModules.size());
// now referenced by Zig
worker->ref();

preloadModuleStrings.clear();

if (!impl) {
return Exception { TypeError, errorMessage.toWTFString(BunString::ZeroCopy) };
}

// now referenced by Zig
worker->ref();
worker->impl_ = impl;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
worker->m_workerCreationTime = MonotonicTime::now();

Expand All @@ -228,7 +236,11 @@ Worker::~Worker()
Locker locker { allWorkersLock };
allWorkers().remove(m_clientIdentifier);
}
// m_contextProxy.workerObjectDestroyed();

if (auto* impl = std::exchange(impl_, nullptr)) {
WebWorker__requestTermination(impl);
WebWorker__release(impl);
}
}

ExceptionOr<void> Worker::postMessage(JSC::JSGlobalObject& state, JSC::JSValue messageValue, StructuredSerializeOptions&& options)
Expand Down Expand Up @@ -261,9 +273,9 @@ ExceptionOr<void> Worker::postMessage(JSC::JSGlobalObject& state, JSC::JSValue m

void Worker::terminate()
{
// m_contextProxy.terminateWorkerGlobalScope();
m_terminationFlags.fetch_or(TerminateRequestedFlag);
WebWorker__notifyNeedTermination(impl_);
if (impl_)
WebWorker__requestTermination(impl_);
}

// const char* Worker::activeDOMObjectName() const
Expand Down
120 changes: 88 additions & 32 deletions src/bun.js/web_worker.zig
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,19 @@ const log = Output.scoped(.Worker, .hidden);
/// null when haven't started yet
vm: ?*jsc.VirtualMachine = null,
status: std.atomic.Value(Status) = .init(.start),
/// To prevent UAF, the `spin` function (aka the worker's event loop) will call deinit once this is set and properly exit the loop.
/// Set via requestTermination(). Checked by hasRequestedTerminate()
/// from both threads. The atomic swap ensures only the first
/// terminate caller triggers notifyNeedTermination().
requested_terminate: std.atomic.Value(bool) = .init(false),
execution_context_id: u32 = 0,
parent_context_id: u32 = 0,
parent: *jsc.VirtualMachine,

/// Both the C++ Worker object (parent thread) and the worker thread
/// hold a ref. The struct survives until both release, so C++ can
/// safely call requestTermination/setRef after exitAndDeinit derefs.
ref_count: RefCount,

/// To be resolved on the Worker thread at startup, in spin().
unresolved_specifier: []const u8,
preloads: [][]const u8 = &.{},
Expand Down Expand Up @@ -40,6 +47,10 @@ execArgv: ?[]const WTFStringImpl,
/// Used to distinguish between terminate() called by exit(), and terminate() called for other reasons
exit_called: bool = false,

const RefCount = bun.ptr.ThreadSafeRefCount(@This(), "ref_count", destroy, .{});
pub const ref = RefCount.ref;
pub const deref = RefCount.deref;

pub const Status = enum(u8) {
start,
starting,
Expand All @@ -58,11 +69,7 @@ export fn WebWorker__getParentWorker(vm: *jsc.VirtualMachine) ?*anyopaque {
}

pub fn hasRequestedTerminate(this: *const WebWorker) bool {
return this.requested_terminate.load(.monotonic);
}

pub fn setRequestedTerminate(this: *WebWorker) bool {
return this.requested_terminate.swap(true, .release);
return this.requested_terminate.load(.acquire);
}

export fn WebWorker__updatePtr(worker: *WebWorker, ptr: *anyopaque) bool {
Expand All @@ -73,7 +80,11 @@ export fn WebWorker__updatePtr(worker: *WebWorker, ptr: *anyopaque) bool {
startWithErrorHandling,
.{worker},
) catch {
worker.deinit();
// Spawn failed — the worker thread never started so exitAndDeinit
// will never run. requestTermination → notifyNeedTermination handles
// unreffing parent_poll_ref via setRefInternal(false).
worker.requestTermination();
worker.deref();
return false;
};
thread.detach();
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
Expand Down Expand Up @@ -233,8 +244,11 @@ pub fn create(
}
}

var worker = bun.handleOom(bun.default_allocator.create(WebWorker));
worker.* = WebWorker{
var worker = bun.new(WebWorker, WebWorker{
// Start at 2 refs: one for the worker thread (released in
// exitAndDeinit), one for C++ (released in ~Worker via
// WebWorker__release).
.ref_count = .initExactRefs(2),
.cpp_worker = cpp_worker,
.parent = parent,
.parent_context_id = parent_context_id,
Expand All @@ -254,7 +268,7 @@ pub fn create(
.argv = if (argv_ptr) |ptr| ptr[0..argv_len] else &.{},
.execArgv = if (inherit_execArgv) null else (if (execArgv_ptr) |ptr| ptr[0..execArgv_len] else &.{}),
.preloads = preloads.items,
};
});

worker.parent_poll_ref.ref(parent);

Expand Down Expand Up @@ -367,17 +381,34 @@ pub fn start(
vm.global.vm().holdAPILock(this, callback);
}

/// Deinit will clean up vm and everything.
/// Early deinit may be called from caller thread, but full vm deinit will only be called within worker's thread.
fn deinit(this: *WebWorker) void {
log("[{d}] deinit", .{this.execution_context_id});
this.parent_poll_ref.unrefConcurrently(this.parent);
bun.default_allocator.free(this.unresolved_specifier);
/// Free owned heap data (name, source specifier, preloads). Called from
/// exitAndDeinit so large allocations are released synchronously at
/// worker exit, not held until the C++ Worker is GC'd and releases its
/// ref. Idempotent — destroy() also calls this for early-failure paths
/// (thread spawn failure) that never reach exitAndDeinit.
fn releaseResources(this: *WebWorker) void {
if (this.name.len > 0) {
bun.default_allocator.free(this.name);
this.name = "";
}
if (this.unresolved_specifier.len > 0) {
bun.default_allocator.free(this.unresolved_specifier);
this.unresolved_specifier = &.{};
}
for (this.preloads) |preload| {
bun.default_allocator.free(preload);
}
bun.default_allocator.free(this.preloads);
bun.default_allocator.destroy(this);
if (this.preloads.len > 0) {
bun.default_allocator.free(this.preloads);
this.preloads = &.{};
}
}

/// Called when the ref count reaches zero. Both sides have released.
fn destroy(this: *WebWorker) void {
log("[{d}] destroy", .{this.execution_context_id});
this.releaseResources();
bun.destroy(this);
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
}

fn flushLogs(this: *WebWorker) void {
Expand Down Expand Up @@ -410,7 +441,7 @@ fn onUnhandledRejection(vm: *jsc.VirtualMachine, globalObject: *jsc.JSGlobalObje
var array = std.Io.Writer.Allocating.init(bun.default_allocator);
defer array.deinit();

var worker = vm.worker orelse @panic("Assertion failure: no worker");
const worker = vm.worker orelse @panic("Assertion failure: no worker");

const writer = &array.writer;
// we buffer this because it'll almost always be < 4096
Expand Down Expand Up @@ -441,8 +472,8 @@ fn onUnhandledRejection(vm: *jsc.VirtualMachine, globalObject: *jsc.JSGlobalObje
jsc.markBinding(@src());
WebWorker__dispatchError(globalObject, worker.cpp_worker, bun.String.cloneUTF8(array.written()), error_instance);
if (vm.worker) |worker_| {
_ = worker.setRequestedTerminate();
worker.parent_poll_ref.unrefConcurrently(worker.parent);
worker_.exit_called = true;
worker_.requestTermination();
worker_.exitAndDeinit();
}
}
Expand Down Expand Up @@ -548,7 +579,6 @@ pub fn setRef(this: *WebWorker, value: bool) callconv(.c) void {
if (this.hasRequestedTerminate()) {
return;
}

this.setRefInternal(value);
}

Expand All @@ -563,25 +593,21 @@ pub fn setRefInternal(this: *WebWorker, value: bool) void {
/// Implement process.exit(). May only be called from the Worker thread.
pub fn exit(this: *WebWorker) void {
this.exit_called = true;
this.notifyNeedTermination();
this.requestTermination();
}

/// Request a terminate from any thread.
pub fn notifyNeedTermination(this: *WebWorker) callconv(.c) void {
/// Wake the worker event loop so it exits and unref the parent keep-alive
/// so the parent doesn't hang waiting for the worker.
fn notifyNeedTermination(this: *WebWorker) void {
if (this.status.load(.acquire) == .terminated) {
return;
}
if (this.setRequestedTerminate()) {
return;
}
log("[{d}] notifyNeedTermination", .{this.execution_context_id});

if (this.vm) |vm| {
vm.eventLoop().wakeup();
// TODO(@190n) notifyNeedTermination
}
Comment thread
claude[bot] marked this conversation as resolved.
Resolved

// TODO(@190n) delete
this.setRefInternal(false);
}

Expand All @@ -591,6 +617,10 @@ pub fn notifyNeedTermination(this: *WebWorker) callconv(.c) void {
pub fn exitAndDeinit(this: *WebWorker) noreturn {
jsc.markBinding(@src());
this.setStatus(.terminated);
// Mark terminated so any late requestTermination/setRef from the
// parent thread is a no-op. Idempotent — exit() or C++ terminate()
// may have already set this.
this.requested_terminate.store(true, .release);
bun.analytics.Features.workers_terminated += 1;

log("[{d}] exitAndDeinit", .{this.execution_context_id});
Expand All @@ -611,6 +641,13 @@ pub fn exitAndDeinit(this: *WebWorker) noreturn {
var arena = this.arena;

WebWorker__dispatchExit(globalObject, cpp_worker, exit_code);
// destroy() might not run here if C++ still holds its ref. Release
// resources that would otherwise wait on GC: parent keep-alive
// (blocks parent exit) and source specifier / preloads (can be
// large for eval workers). Must be after dispatchExit so the posted
// close-event task is queued while the parent loop is still ref'd.
this.parent_poll_ref.unrefConcurrently(this.parent);
this.releaseResources();
if (loop) |loop_| {
loop_.internal_loop_data.jsc_vm = null;
}
Expand All @@ -625,7 +662,7 @@ pub fn exitAndDeinit(this: *WebWorker) noreturn {
bun.windows.libuv.Loop.shutdown();
}

this.deinit();
this.deref();

if (vm_to_deinit) |vm| {
vm.deinit(); // NOTE: deinit here isn't implemented, so freeing workers will leak the vm.
Expand All @@ -638,11 +675,30 @@ pub fn exitAndDeinit(this: *WebWorker) noreturn {
bun.exitThread();
}

/// Atomically request termination. Only the first caller triggers
/// notifyNeedTermination — subsequent calls (double terminate(),
/// terminate() + ~Worker()) are no-ops.
fn requestTermination(this: *WebWorker) void {
if (this.requested_terminate.swap(true, .acq_rel)) return;
this.notifyNeedTermination();
}

export fn WebWorker__requestTermination(worker: ?*WebWorker) void {
const w = worker orelse return;
w.requestTermination();
}

export fn WebWorker__release(worker: ?*WebWorker) void {
const w = worker orelse return;
w.deref();
}

comptime {
@export(&create, .{ .name = "WebWorker__create" });
@export(&notifyNeedTermination, .{ .name = "WebWorker__notifyNeedTermination" });
@export(&setRef, .{ .name = "WebWorker__setRef" });
_ = WebWorker__updatePtr;
_ = &WebWorker__requestTermination;
_ = &WebWorker__release;
}

const std = @import("std");
Expand Down
Loading
Loading