From 0f56f187d0b4ca0c33dbe9ac16239feb69b3bc33 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 22 Sep 2026 07:38:02 +0000 Subject: [PATCH 1/7] bun:ffi: a JSCallback can be the deallocator of toArrayBuffer() and toBuffer() The collector calls the deallocator of a toArrayBuffer() / toBuffer() buffer when it frees the buffer. A JSCallback's ptr is a C function pointer, so it can be that deallocator, and its dispatch entered JS from inside the collection: a segfault at address 0x0 in release builds, a deadlock when an idle collection ends on the collector thread, and JS in a VM that is being destroyed when a Worker exits. The engine now queues such a call through the dispatch a threadsafe callback uses. That dispatch needs the script execution context of the callback, so Bun__CreateJSCFFICallback registers the dispatch and passes the context id for every JSCallback, not only for a threadsafe one. --- docs/runtime/ffi.mdx | 16 ++++ src/jsc/bindings/JSCFFIBridge.cpp | 25 +++-- test/js/bun/ffi/ffi-test.c | 7 ++ test/js/bun/ffi/ffi.test.js | 151 ++++++++++++++++++++++++++++++ 4 files changed, 185 insertions(+), 14 deletions(-) diff --git a/docs/runtime/ffi.mdx b/docs/runtime/ffi.mdx index 4ff9af5abda2..5c60d3610ebb 100644 --- a/docs/runtime/ffi.mdx +++ b/docs/runtime/ffi.mdx @@ -501,6 +501,22 @@ toArrayBuffer( ); ``` +The callback can also be the `ptr` of a `JSCallback`. JavaScript cannot run during a garbage collection, so Bun queues the call and runs the function on the JavaScript thread after the collection. The same applies when a C callback calls a `JSCallback` from inside the collection: the C caller gets `0` back, as it does from a thread-safe callback. Keep the `JSCallback` open until the last call arrives. + +```ts +import { JSCallback, toArrayBuffer } from "bun:ffi"; + +const deallocator = new JSCallback( + (bytes, deallocatorContext) => { + // runs on the JavaScript thread, after the collection that freed the ArrayBuffer + myNativeLibraryFree(bytes); + }, + { args: ["ptr", "ptr"], returns: "void" }, +); + +toArrayBuffer(bytes, byteOffset, byteLength, deallocator.ptr); +``` + ### Memory safety Don't use raw pointers outside of FFI. A future version of Bun may add a CLI flag to disable `bun:ffi`. diff --git a/src/jsc/bindings/JSCFFIBridge.cpp b/src/jsc/bindings/JSCFFIBridge.cpp index cf8c923b7107..789dbeb94eb4 100644 --- a/src/jsc/bindings/JSCFFIBridge.cpp +++ b/src/jsc/bindings/JSCFFIBridge.cpp @@ -73,12 +73,12 @@ extern "C" JSC::EncodedJSValue Bun__CreateJSCFFICallback( auto& vm = JSC::getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); - if (threadsafe) { - static std::once_flag registerDispatch; - std::call_once(registerDispatch, [] { - JSC::FFI::FFIContext::setThreadsafeDispatch(Bun__jscFFIThreadsafeDispatch); - }); - } + // Not only for a threadsafe callback: any JSCallback the collector calls (the deallocator of a toArrayBuffer() + // buffer) goes through the dispatch, with the context below, because JS cannot run during a collection. + static std::once_flag registerDispatch; + std::call_once(registerDispatch, [] { + JSC::FFI::FFIContext::setThreadsafeDispatch(Bun__jscFFIThreadsafeDispatch); + }); JSC::JSObject* callable = JSC::JSValue::decode(callableValue).getObject(); if (!callable || !callable->isCallable()) [[unlikely]] { @@ -97,15 +97,12 @@ extern "C" JSC::EncodedJSValue Bun__CreateJSCFFICallback( RELEASE_AND_RETURN(scope, {}); } - void* embedderContext = nullptr; - if (threadsafe) { - auto* scriptExecutionContext = globalObject->scriptExecutionContext(); - if (!scriptExecutionContext) [[unlikely]] { - JSC::throwTypeError(globalObject, scope, "bun:ffi: no script execution context for a threadsafe JSCallback"_s); - RELEASE_AND_RETURN(scope, {}); - } - embedderContext = reinterpret_cast(static_cast(scriptExecutionContext->identifier())); + auto* scriptExecutionContext = globalObject->scriptExecutionContext(); + if (!scriptExecutionContext) [[unlikely]] { + JSC::throwTypeError(globalObject, scope, "bun:ffi: no script execution context for a JSCallback"_s); + RELEASE_AND_RETURN(scope, {}); } + void* embedderContext = reinterpret_cast(static_cast(scriptExecutionContext->identifier())); JSC::JSFFICallback* callback = JSC::FFI::createCallback(globalObject, signature.releaseNonNull(), callable, threadsafe, embedderContext); RETURN_IF_EXCEPTION(scope, {}); if (!callback) diff --git a/test/js/bun/ffi/ffi-test.c b/test/js/bun/ffi/ffi-test.c index ae7ba120bb8d..8a78ad248469 100644 --- a/test/js/bun/ffi/ffi-test.c +++ b/test/js/bun/ffi/ffi-test.c @@ -135,6 +135,13 @@ FFI_EXPORT void *getDeallocatorBuffer() { } FFI_EXPORT int getDeallocatorCalledCount() { return deallocatorCalled; } +// A C deallocator that calls a second one. A test sets the second one to a JSCallback. +typedef void (*deallocator_fn)(void *ptr, void *userData); +static deallocator_fn forwardedDeallocator; +FFI_EXPORT void setForwardedDeallocator(deallocator_fn fn) { forwardedDeallocator = fn; } +FFI_EXPORT void forwardingDeallocator(void *ptr, void *userData) { forwardedDeallocator(ptr, userData); } +FFI_EXPORT void *getForwardingDeallocator() { return &forwardingDeallocator; } + FFI_EXPORT bool is_null(int32_t *ptr) { return ptr == NULL; } FFI_EXPORT bool does_pointer_equal_42_as_int32_t(int32_t *ptr); bool does_pointer_equal_42_as_int32_t(int32_t *ptr) { return *ptr == 42; } diff --git a/test/js/bun/ffi/ffi.test.js b/test/js/bun/ffi/ffi.test.js index b82a25035990..187a17c979bb 100644 --- a/test/js/bun/ffi/ffi.test.js +++ b/test/js/bun/ffi/ffi.test.js @@ -1498,6 +1498,157 @@ describe("toBuffer borrowed-pointer ownership (no bad-free on GC)", () => { ); }); +// The collector calls the deallocator, and JS cannot run during a collection, so the call is queued for +// the JS thread. Subprocess because unpatched builds crash when the collection runs on the JS thread, and +// deadlock when it ends on the collector thread. +describe("a JSCallback as the deallocator of toArrayBuffer() and toBuffer()", () => { + const passedDirectly = `deallocator.ptr`; + // The deallocator is a C function, which calls the JSCallback from inside the collection. + const calledFromC = `(() => { + const { symbols } = dlopen(process.env.FFI_FIXTURE_PATH, { + setForwardedDeallocator: { args: ["ptr"], returns: "void" }, + getForwardingDeallocator: { args: [], returns: "ptr" }, + }); + symbols.setForwardedDeallocator(deallocator.ptr); + return symbols.getForwardingDeallocator(); + })()`; + + const collectOnJSThread = ` + globalThis.buffers = null; + Bun.gc(true); + if (freed.size) throw new Error("the deallocator ran inside the collection"); + for (let i = 0; i < 100 && freed.size < count; i++) { + await nextTick(); + Bun.gc(true); + } + `; + // The JS thread parks without heap access during an idle collection, so its end phase runs on the collector thread. + const collectWhileParked = ` + // Old objects: only a full collection frees them, and the next one is the idle one. + Bun.gc(true); + await nextTick(); + globalThis.buffers = null; + // Keeps the parked process alive, and ends it if the calls never arrive. + const deadline = setTimeout(() => process.exit(1), 20_000); + await allFreed; + clearTimeout(deadline); + `; + const idleCollectionEnv = { + BUN_IDLE_GC_SECONDS: "1", + BUN_GC_TIMER_DISABLE: undefined, + BUN_GC_TIMER_INTERVAL: undefined, + BUN_GC_RUNS_UNTIL_SKIP_RELEASE_ACCESS: "0", + }; + + async function run(deallocatorPointer, collect, env = {}) { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + import { dlopen, JSCallback, ptr, toArrayBuffer, toBuffer } from "bun:ffi"; + const count = 64, size = 16; + const backing = new Uint8Array(count * size); + const base = ptr(backing); + const freed = new Map(); + const { promise: allFreed, resolve } = Promise.withResolvers(); + let repeated = 0; + const deallocator = new JSCallback( + (bytes, context) => { + if (freed.has(context)) repeated++; + freed.set(context, bytes); + if (freed.size === count) resolve(); + }, + { args: ["ptr", "ptr"], returns: "void" }, + ); + const deallocatorPointer = ${deallocatorPointer}; + globalThis.buffers = []; + for (let i = 0; i < count; i++) { + buffers.push((i & 1 ? toBuffer : toArrayBuffer)(base, i * size, size, i + 1, deallocatorPointer)); + } + const nextTick = () => new Promise(resolve => setImmediate(resolve)); + ${collect} + let wrongArguments = 0; + for (let i = 0; i < count; i++) if (freed.get(i + 1) !== base + i * size) wrongArguments++; + console.log(JSON.stringify({ calls: freed.size, repeated, wrongArguments })); + deallocator.close(); + `, + ], + env: { ...bunEnv, FFI_FIXTURE_PATH, ...env }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { result: JSON.parse(stdout.trim() || "null"), stderr, exitCode, signalCode: proc.signalCode }; + } + const allCallsArrived = { + result: { calls: 64, repeated: 0, wrongArguments: 0 }, + stderr: "", + exitCode: 0, + signalCode: null, + }; + + it.concurrent("a collection on the JS thread", async () => { + expect(await run(passedDirectly, collectOnJSThread)).toEqual(allCallsArrived); + }); + + it.concurrent.skipIf(!FFI_FIXTURE_PATH)("a C deallocator that calls the JSCallback", async () => { + expect(await run(calledFromC, collectOnJSThread)).toEqual(allCallsArrived); + }); + + // Windows keeps the collection on the JS thread. + it.concurrent.skipIf(isWindows)( + "an idle collection that ends on the collector thread", + async () => { + expect(await run(passedDirectly, collectWhileParked, idleCollectionEnv)).toEqual(allCallsArrived); + }, + 30_000, + ); + + // The last sweep of a worker's heap frees the buffers that are still alive. JS cannot run in a VM that is + // being destroyed, so those calls are dropped. 'close' fires after the worker's VM is destroyed. + it.concurrent("a Worker that exits while its buffers are alive", async () => { + using dir = tempDir("ffi-jscallback-deallocator-worker", { + "main.js": ` + const worker = new Worker(new URL("./worker.js", import.meta.url).href); + await new Promise((resolve, reject) => { + worker.onmessage = resolve; + worker.onerror = reject; + }); + const closed = new Promise(resolve => worker.addEventListener("close", resolve)); + worker.terminate(); + await closed; + console.log("done"); + `, + "worker.js": ` + import { JSCallback, ptr, toArrayBuffer } from "bun:ffi"; + const count = 64, size = 16; + const backing = new Uint8Array(count * size); + // A first call that resolves a variable is what a debug build asserts on in a VM that is shutting down. + let calls = 0; + const deallocator = new JSCallback(() => { calls++; }, { args: ["ptr", "ptr"], returns: "void" }); + globalThis.buffers = []; + for (let i = 0; i < count; i++) buffers.push(toArrayBuffer(ptr(backing), i * size, size, deallocator.ptr)); + postMessage("made"); + `, + }); + await using proc = Bun.spawn({ + cmd: [bunExe(), "main.js"], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect({ stdout, stderr, exitCode, signalCode: proc.signalCode }).toEqual({ + stdout: "done\n", + stderr: "", + exitCode: 0, + signalCode: null, + }); + }); +}); + // toBuffer hands an arbitrary (pointer, byteLength) pair straight to the Buffer // hand-off that spawnSync, Bun.$ and others use for their output. That makes it // the one way to reach the hand-off with a byteLength above kMaxLength (2^32) From f285cd0127f8658bc206af3a3c404c42daa09e41 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 22 Sep 2026 08:30:17 +0000 Subject: [PATCH 2/7] test(ffi): end a deadlocked child of the deallocator tests with a spawn timeout --- test/js/bun/ffi/ffi.test.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/js/bun/ffi/ffi.test.js b/test/js/bun/ffi/ffi.test.js index 187a17c979bb..bb20da81b360 100644 --- a/test/js/bun/ffi/ffi.test.js +++ b/test/js/bun/ffi/ffi.test.js @@ -1577,6 +1577,9 @@ describe("a JSCallback as the deallocator of toArrayBuffer() and toBuffer()", () env: { ...bunEnv, FFI_FIXTURE_PATH, ...env }, stdout: "pipe", stderr: "pipe", + // Ends a deadlocked process, which does not act on SIGTERM, before the test times out. + timeout: 25_000, + killSignal: "SIGKILL", }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); return { result: JSON.parse(stdout.trim() || "null"), stderr, exitCode, signalCode: proc.signalCode }; From 9ee3d265dfcbdb31bd703fe72fa27fe7ade6f1aa Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 22 Sep 2026 09:42:59 +0000 Subject: [PATCH 3/7] test(ffi): a buffer with a JSCallback deallocator that is transferred to a Worker --- docs/runtime/ffi.mdx | 2 +- test/js/bun/ffi/ffi.test.js | 215 ++++++++++++++++++++---------------- 2 files changed, 120 insertions(+), 97 deletions(-) diff --git a/docs/runtime/ffi.mdx b/docs/runtime/ffi.mdx index 5c60d3610ebb..5018f6113ad5 100644 --- a/docs/runtime/ffi.mdx +++ b/docs/runtime/ffi.mdx @@ -501,7 +501,7 @@ toArrayBuffer( ); ``` -The callback can also be the `ptr` of a `JSCallback`. JavaScript cannot run during a garbage collection, so Bun queues the call and runs the function on the JavaScript thread after the collection. The same applies when a C callback calls a `JSCallback` from inside the collection: the C caller gets `0` back, as it does from a thread-safe callback. Keep the `JSCallback` open until the last call arrives. +The callback can also be the `ptr` of a `JSCallback`. JavaScript cannot run during a garbage collection, so Bun queues the call and runs the function later, on the JavaScript thread that created the `JSCallback`. That is also the case when the buffer was transferred to a `Worker` and freed there. The same applies when a C callback calls a `JSCallback` from inside the collection: the C caller gets `0` back, as it does from a thread-safe callback. Keep the `JSCallback` open until the last call arrives. ```ts import { JSCallback, toArrayBuffer } from "bun:ffi"; diff --git a/test/js/bun/ffi/ffi.test.js b/test/js/bun/ffi/ffi.test.js index bb20da81b360..6132a7b89238 100644 --- a/test/js/bun/ffi/ffi.test.js +++ b/test/js/bun/ffi/ffi.test.js @@ -1500,80 +1500,12 @@ describe("toBuffer borrowed-pointer ownership (no bad-free on GC)", () => { // The collector calls the deallocator, and JS cannot run during a collection, so the call is queued for // the JS thread. Subprocess because unpatched builds crash when the collection runs on the JS thread, and -// deadlock when it ends on the collector thread. +// deadlock when it runs on another thread. describe("a JSCallback as the deallocator of toArrayBuffer() and toBuffer()", () => { - const passedDirectly = `deallocator.ptr`; - // The deallocator is a C function, which calls the JSCallback from inside the collection. - const calledFromC = `(() => { - const { symbols } = dlopen(process.env.FFI_FIXTURE_PATH, { - setForwardedDeallocator: { args: ["ptr"], returns: "void" }, - getForwardingDeallocator: { args: [], returns: "ptr" }, - }); - symbols.setForwardedDeallocator(deallocator.ptr); - return symbols.getForwardingDeallocator(); - })()`; - - const collectOnJSThread = ` - globalThis.buffers = null; - Bun.gc(true); - if (freed.size) throw new Error("the deallocator ran inside the collection"); - for (let i = 0; i < 100 && freed.size < count; i++) { - await nextTick(); - Bun.gc(true); - } - `; - // The JS thread parks without heap access during an idle collection, so its end phase runs on the collector thread. - const collectWhileParked = ` - // Old objects: only a full collection frees them, and the next one is the idle one. - Bun.gc(true); - await nextTick(); - globalThis.buffers = null; - // Keeps the parked process alive, and ends it if the calls never arrive. - const deadline = setTimeout(() => process.exit(1), 20_000); - await allFreed; - clearTimeout(deadline); - `; - const idleCollectionEnv = { - BUN_IDLE_GC_SECONDS: "1", - BUN_GC_TIMER_DISABLE: undefined, - BUN_GC_TIMER_INTERVAL: undefined, - BUN_GC_RUNS_UNTIL_SKIP_RELEASE_ACCESS: "0", - }; - - async function run(deallocatorPointer, collect, env = {}) { + async function exec(cmd, { cwd, env = {} } = {}) { await using proc = Bun.spawn({ - cmd: [ - bunExe(), - "-e", - ` - import { dlopen, JSCallback, ptr, toArrayBuffer, toBuffer } from "bun:ffi"; - const count = 64, size = 16; - const backing = new Uint8Array(count * size); - const base = ptr(backing); - const freed = new Map(); - const { promise: allFreed, resolve } = Promise.withResolvers(); - let repeated = 0; - const deallocator = new JSCallback( - (bytes, context) => { - if (freed.has(context)) repeated++; - freed.set(context, bytes); - if (freed.size === count) resolve(); - }, - { args: ["ptr", "ptr"], returns: "void" }, - ); - const deallocatorPointer = ${deallocatorPointer}; - globalThis.buffers = []; - for (let i = 0; i < count; i++) { - buffers.push((i & 1 ? toBuffer : toArrayBuffer)(base, i * size, size, i + 1, deallocatorPointer)); - } - const nextTick = () => new Promise(resolve => setImmediate(resolve)); - ${collect} - let wrongArguments = 0; - for (let i = 0; i < count; i++) if (freed.get(i + 1) !== base + i * size) wrongArguments++; - console.log(JSON.stringify({ calls: freed.size, repeated, wrongArguments })); - deallocator.close(); - `, - ], + cmd, + cwd, env: { ...bunEnv, FFI_FIXTURE_PATH, ...env }, stdout: "pipe", stderr: "pipe", @@ -1582,28 +1514,132 @@ describe("a JSCallback as the deallocator of toArrayBuffer() and toBuffer()", () killSignal: "SIGKILL", }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - return { result: JSON.parse(stdout.trim() || "null"), stderr, exitCode, signalCode: proc.signalCode }; + return { stdout, stderr, exitCode, signalCode: proc.signalCode }; } + + // Makes 64 buffers over one backing array, each with the JSCallback as its deallocator and its index + 1 + // as the context. `report()` prints what the JSCallback received. + const makeBuffers = ` + import { dlopen, JSCallback, ptr, toArrayBuffer, toBuffer } from "bun:ffi"; + const count = 64, size = 16; + const backing = new Uint8Array(count * size); + const base = ptr(backing); + const freed = new Map(); + const { promise: allFreed, resolve } = Promise.withResolvers(); + let repeated = 0; + const deallocator = new JSCallback( + (bytes, context) => { + if (freed.has(context)) repeated++; + freed.set(context, bytes); + if (freed.size === count) resolve(); + }, + { args: ["ptr", "ptr"], returns: "void" }, + ); + const makeBuffers = (deallocatorPointer, make = i => (i & 1 ? toBuffer : toArrayBuffer)) => + Array.from({ length: count }, (_, i) => make(i)(base, i * size, size, i + 1, deallocatorPointer)); + const nextTick = () => new Promise(resolve => setImmediate(resolve)); + function report() { + let wrongArguments = 0; + for (let i = 0; i < count; i++) if (freed.get(i + 1) !== base + i * size) wrongArguments++; + console.log(JSON.stringify({ calls: freed.size, repeated, wrongArguments })); + deallocator.close(); + } + `; const allCallsArrived = { - result: { calls: 64, repeated: 0, wrongArguments: 0 }, + stdout: JSON.stringify({ calls: 64, repeated: 0, wrongArguments: 0 }) + "\n", stderr: "", exitCode: 0, signalCode: null, }; + const collectOnJSThread = ` + Bun.gc(true); + if (freed.size) throw new Error("the deallocator ran inside the collection"); + for (let i = 0; i < 100 && freed.size < count; i++) { + await nextTick(); + Bun.gc(true); + } + report(); + `; + it.concurrent("a collection on the JS thread", async () => { - expect(await run(passedDirectly, collectOnJSThread)).toEqual(allCallsArrived); + const script = `${makeBuffers} + makeBuffers(deallocator.ptr); + ${collectOnJSThread}`; + expect(await exec([bunExe(), "-e", script])).toEqual(allCallsArrived); }); it.concurrent.skipIf(!FFI_FIXTURE_PATH)("a C deallocator that calls the JSCallback", async () => { - expect(await run(calledFromC, collectOnJSThread)).toEqual(allCallsArrived); + const script = `${makeBuffers} + const { symbols } = dlopen(process.env.FFI_FIXTURE_PATH, { + setForwardedDeallocator: { args: ["ptr"], returns: "void" }, + getForwardingDeallocator: { args: [], returns: "ptr" }, + }); + symbols.setForwardedDeallocator(deallocator.ptr); + makeBuffers(symbols.getForwardingDeallocator()); + ${collectOnJSThread}`; + expect(await exec([bunExe(), "-e", script])).toEqual(allCallsArrived); }); - // Windows keeps the collection on the JS thread. + // The JS thread parks without heap access during an idle collection, so its end phase runs on the collector + // thread. Windows keeps the collection on the JS thread. it.concurrent.skipIf(isWindows)( "an idle collection that ends on the collector thread", async () => { - expect(await run(passedDirectly, collectWhileParked, idleCollectionEnv)).toEqual(allCallsArrived); + const script = `${makeBuffers} + globalThis.buffers = makeBuffers(deallocator.ptr); + // Old objects: only a full collection frees them, and the next one is the idle one. + Bun.gc(true); + await nextTick(); + globalThis.buffers = null; + // Keeps the parked process alive, and ends it if the calls never arrive. + const deadline = setTimeout(() => process.exit(1), 20_000); + await allFreed; + clearTimeout(deadline); + report();`; + const env = { + BUN_IDLE_GC_SECONDS: "1", + BUN_GC_TIMER_DISABLE: undefined, + BUN_GC_TIMER_INTERVAL: undefined, + BUN_GC_RUNS_UNTIL_SKIP_RELEASE_ACCESS: "0", + }; + expect(await exec([bunExe(), "-e", script], { env })).toEqual(allCallsArrived); + }, + 30_000, + ); + + // The collection that frees a transferred buffer runs on the Worker's thread, which cannot run the JS of this one. + it.concurrent( + "a buffer transferred to a Worker", + async () => { + using dir = tempDir("ffi-jscallback-deallocator-transfer", { + "main.js": `${makeBuffers} + const worker = new Worker(new URL("./worker.js", import.meta.url).href); + const reply = () => new Promise((resolve, reject) => { + worker.onmessage = resolve; + worker.onerror = reject; + }); + const buffers = makeBuffers(deallocator.ptr, () => toArrayBuffer); + let replied = reply(); + worker.postMessage(buffers, buffers); + await replied; + // The buffers are garbage in the worker once its first handler returns. It collects on each message. + for (let i = 0; i < 100 && freed.size < count; i++) { + replied = reply(); + worker.postMessage("collect"); + await replied; + } + report(); + worker.terminate(); + `, + "worker.js": ` + onmessage = () => { + Bun.gc(true); + postMessage("collected"); + }; + `, + }); + expect(await exec([bunExe(), "main.js"], { cwd: String(dir) })).toEqual(allCallsArrived); }, 30_000, ); @@ -1623,27 +1659,14 @@ describe("a JSCallback as the deallocator of toArrayBuffer() and toBuffer()", () await closed; console.log("done"); `, - "worker.js": ` - import { JSCallback, ptr, toArrayBuffer } from "bun:ffi"; - const count = 64, size = 16; - const backing = new Uint8Array(count * size); - // A first call that resolves a variable is what a debug build asserts on in a VM that is shutting down. - let calls = 0; - const deallocator = new JSCallback(() => { calls++; }, { args: ["ptr", "ptr"], returns: "void" }); - globalThis.buffers = []; - for (let i = 0; i < count; i++) buffers.push(toArrayBuffer(ptr(backing), i * size, size, deallocator.ptr)); + "worker.js": `${makeBuffers} + // A first call that resolves a variable (the callback reads \`freed\`) is what a debug build asserts on + // in a VM that is shutting down. + globalThis.buffers = makeBuffers(deallocator.ptr); postMessage("made"); `, }); - await using proc = Bun.spawn({ - cmd: [bunExe(), "main.js"], - env: bunEnv, - cwd: String(dir), - stdout: "pipe", - stderr: "pipe", - }); - const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - expect({ stdout, stderr, exitCode, signalCode: proc.signalCode }).toEqual({ + expect(await exec([bunExe(), "main.js"], { cwd: String(dir) })).toEqual({ stdout: "done\n", stderr: "", exitCode: 0, From 4b5d22ab2cc9d9ad95e1bc2a98f0cd8168aadb21 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 22 Sep 2026 09:49:09 +0000 Subject: [PATCH 4/7] Pin WebKit to the preview build of oven-sh/WebKit#717 --- scripts/build/deps/webkit.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/build/deps/webkit.ts b/scripts/build/deps/webkit.ts index 3c68f4fae4c8..34e7bea6e395 100644 --- a/scripts/build/deps/webkit.ts +++ b/scripts/build/deps/webkit.ts @@ -3,7 +3,7 @@ * for local mode. Override via `--webkit-version=` to test a branch. * From https://github.com/oven-sh/WebKit releases. */ -export const WEBKIT_VERSION = "564ac2a6cad8da6a358f3d331690e1ec65e5d67e"; +export const WEBKIT_VERSION = "autobuild-preview-pr-717-03fc8d8e"; /** * WebKit (JavaScriptCore) — the JS engine. From 93d3efb81d3b539240e832eab6b2c2a6517536e8 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 22 Sep 2026 18:27:47 +0000 Subject: [PATCH 5/7] Pin WebKit to the latest preview build of oven-sh/WebKit#717 --- scripts/build/deps/webkit.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/build/deps/webkit.ts b/scripts/build/deps/webkit.ts index 34e7bea6e395..7e2eac074b49 100644 --- a/scripts/build/deps/webkit.ts +++ b/scripts/build/deps/webkit.ts @@ -3,7 +3,7 @@ * for local mode. Override via `--webkit-version=` to test a branch. * From https://github.com/oven-sh/WebKit releases. */ -export const WEBKIT_VERSION = "autobuild-preview-pr-717-03fc8d8e"; +export const WEBKIT_VERSION = "autobuild-preview-pr-717-6b5d5c13"; /** * WebKit (JavaScriptCore) — the JS engine. From b9a7e8ec3782ab2c6bd79010052c63d1b080dfd8 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 22 Sep 2026 18:29:36 +0000 Subject: [PATCH 6/7] JSCFFIBridge: shorten the comment on the dispatch registration --- src/jsc/bindings/JSCFFIBridge.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/jsc/bindings/JSCFFIBridge.cpp b/src/jsc/bindings/JSCFFIBridge.cpp index 789dbeb94eb4..7aa23b3b168a 100644 --- a/src/jsc/bindings/JSCFFIBridge.cpp +++ b/src/jsc/bindings/JSCFFIBridge.cpp @@ -73,8 +73,7 @@ extern "C" JSC::EncodedJSValue Bun__CreateJSCFFICallback( auto& vm = JSC::getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); - // Not only for a threadsafe callback: any JSCallback the collector calls (the deallocator of a toArrayBuffer() - // buffer) goes through the dispatch, with the context below, because JS cannot run during a collection. + // For every JSCallback: the engine also queues a call to one that is not threadsafe when it cannot run JS inline. static std::once_flag registerDispatch; std::call_once(registerDispatch, [] { JSC::FFI::FFIContext::setThreadsafeDispatch(Bun__jscFFIThreadsafeDispatch); From b6f067bd154ac32bf02dc9a0481c1067a12e4bb7 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 22 Sep 2026 18:58:02 +0000 Subject: [PATCH 7/7] docs(ffi): a queued JSCallback deallocator call is dropped when its thread exits first --- docs/runtime/ffi.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/runtime/ffi.mdx b/docs/runtime/ffi.mdx index 5018f6113ad5..21b1ea50332e 100644 --- a/docs/runtime/ffi.mdx +++ b/docs/runtime/ffi.mdx @@ -501,7 +501,7 @@ toArrayBuffer( ); ``` -The callback can also be the `ptr` of a `JSCallback`. JavaScript cannot run during a garbage collection, so Bun queues the call and runs the function later, on the JavaScript thread that created the `JSCallback`. That is also the case when the buffer was transferred to a `Worker` and freed there. The same applies when a C callback calls a `JSCallback` from inside the collection: the C caller gets `0` back, as it does from a thread-safe callback. Keep the `JSCallback` open until the last call arrives. +The callback can also be the `ptr` of a `JSCallback`. JavaScript cannot run during a garbage collection, so Bun queues the call and runs the function later, on the JavaScript thread that created the `JSCallback`. That is also the case when the buffer was transferred to a `Worker` and freed there. The same applies when a C callback calls a `JSCallback` from inside the collection: the C caller gets `0` back, as it does from a thread-safe callback. Keep the `JSCallback` open until the last call arrives. Bun drops the call when the thread that created the `JSCallback` exits first, for example a `Worker` that ends while such a buffer is alive. ```ts import { JSCallback, toArrayBuffer } from "bun:ffi";