Skip to content

process: deliver exceptions reported against a node:vm context to uncaughtException - #39992

Closed
robobun wants to merge 6 commits into
mainfrom
farm/f60a1c61/vm-uncaught-exception-process
Closed

robobun wants to merge 6 commits into
mainfrom
farm/f60a1c61/vm-uncaught-exception-process

Conversation

@robobun

@robobun robobun commented Aug 21, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • An exception that bun reports against a node:vm context never reaches process.on('uncaughtException'), the monitor, or the capture callback. Bun prints it and exits 1. In a worker it crashes instead: Segmentation fault at address 0x101 in WebWorker__dispatchError (Worker.cpp:200).
  • Cause: Bun__handleUncaughtException (src/jsc/bindings/BunProcess.cpp:1285) returns false when its global is not a Zig::GlobalObject. A context's global is a NodeVMGlobalObject. The caller takes false as "no handler" and runs the fatal path, which in a worker reads Zig::GlobalObject fields from that global.
  • On the EventTarget path, reportException (src/jsc/bindings/JSDOMExceptionHandling.cpp:61) downcasts the same global. Debug builds assert there.

Fix

  • Bun__handleUncaughtException maps its global through defaultGlobalObject(). A Zig::GlobalObject maps to itself, so the main realm, workers, and ShadowRealm behave as before. A NodeVMGlobalObject maps to the thread's default global, which owns process.
  • The worker's fallback (src/jsc/web_worker.rs) dispatches on vm.global(), the global WebWorker__dispatchError expects, not on the realm it is handed.
  • Correct because a context has no process of its own. The exception can only go to the process of the thread that runs the context. promiseRejectionTrackerForNodeVM (NodeVM.cpp:955) already routes a context's rejections this way. Matches node: every child in the new test prints the same lines and exit codes under node v26.
  • Verified: test/js/node/vm/vm.test.ts, six new children, all fail on stock bun. The worker child without a handler still crashes with only the C++ part. Other suites in Notes.

Background

  • The main realm, a worker, and a ShadowRealm each get a Zig::GlobalObject, which holds the Bun state: process, the worker's event scope. vm.createContext() makes a NodeVMGlobalObject, a bare realm with none of that.
  • defaultGlobalObject(global) (ZigGlobalObject.h:914) returns global if it is a Zig::GlobalObject, else the thread's default global. Bindings that a context can reach use it to find process.
  • VirtualMachine::uncaught_exception is the one sink for uncaught exceptions. Reporting sites pass it the realm of the object that threw. It tries Bun__handleUncaughtException, then the thread's fallback: print and exit 1 on the main thread, the Worker's 'error' event in a worker.
Notes

Repro from the report (release 1.4.0 prints the error, exits 1, reported: 0):

import vm from "node:vm";
let reported = 0;
process.on("uncaughtException", () => { reported++; });
const context = vm.createContext({});
vm.runInContext(`
  globalThis.registry = new FinalizationRegistry(() => { throw new Error("cleanup"); });
  for (let i = 0; i < 3; i++) registry.register({}, i);
`, context);
Bun.gc(true);
await Bun.sleep(1);
console.log("reported:", reported);

Worker crash, release 1.4.0 (panic: Segmentation fault at address 0x101, the debug build reports the SEGV in WebWorker__dispatchError at Worker.cpp:200):

const { Worker } = require("node:worker_threads");
new Worker(`
  const vm = require("node:vm");
  const t = new EventTarget();
  t.addEventListener("x", vm.runInNewContext('(function () { throw new Error("x"); })'));
  t.dispatchEvent(new Event("x"));
`, { eval: true }).on("error", e => console.log("error event:", e.message));

Affected reporting sites, each with a child in the new test: JSCTaskScheduler::runPendingWork (JSCTaskScheduler.cpp:119, FinalizationRegistry), EventEmitter::innerInvokeEventListeners (EventEmitter.cpp:268, a process listener created in a context, the test uses 'exit'), JSEventListener::handleEvent through reportException (JSEventListener.cpp:227, an EventTarget listener created in a context, with both on('uncaughtException') and setUncaughtExceptionCaptureCallback). Two worker children: with a handler in the worker (handled there, worker exits 0) and without one (Worker 'error' event, worker exits 1, the process exits 0). The reportException children fail on a stock debug build by the assertion, on a release build by the exit code. The worker children crash on stock bun.

The other consumers of the realm global in uncaught_exception were checked with a context global on the fixed debug build: the main-thread printer (prints, exit 1, as before), Bun__Process__exit (uses the VM only), and the bun test runner (the error is charged to the running test, as for a main-realm throw). process._fatalException() called from inside a context now works too, it used to return false.

Also checked on the fixed debug build, each matching node v26: a throwing beforeExit listener created in a context with a handler installed (handled, exit 0), --unhandled-rejections=strict with a promise rejected inside a context (delivered with origin unhandledRejection), and a ShadowRealm FinalizationRegistry throw (unchanged: printed, exit 1, see below).

Probed and not affected, they pass the main global already: setTimeout(vmFn) (the timer's global), queueMicrotask(vmFn), process.nextTick(vmFn).

Bun__handleUnhandledRejection and Bun__emitHandledPromiseEvent have the same guard and are left as they are. A context's rejections are mapped before they get there, by promiseRejectionTrackerForNodeVM, and handleRejectedPromises runs on the Zig::GlobalObject that holds the list.

Out of scope: a ShadowRealm gets a full Zig::GlobalObject and so a process object of its own. A throwing FinalizationRegistry callback in a ShadowRealm goes to that realm's process, which has no listeners, and exits 1 today. defaultGlobalObject() keeps that unchanged. Routing every realm to the thread's process would be a separate decision.

NodeVMGlobalObject's method table entry for reportUncaughtExceptionAtEventLoop is JSC's default no-op. Bun reports through Zig::GlobalObject::reportUncaughtExceptionAtEventLoop directly, never through the table, and a context exposes no queueMicrotask, so the entry is not reachable and is not touched.

Suites run with the fixed debug build: test/js/node/vm/, test/js/node/process/process.test.js, test/js/node/process/process-on.test.ts, test/js/web/abort/, test/js/node/events/, test/js/web/workers/worker.test.ts, worker-terminate-funnels.test.ts, worker-terminate-lifetime.test.ts. Upstream files, all exit 0: the 25 test-worker-* files whose names mention uncaught, exit, error, unhandled, or exception, plus test-process-exit-code, test-emit-after-uncaught-exception, test-event-target, test-events-uncaught-exception-stack, test-eventtarget, test-process-exception-capture, test-process-exception-capture-errors, test-process-exception-capture-should-abort-on-uncaught, test-process-uncaught-exception-monitor, test-timers-uncaught-exception, test-uncaught-exception-handler-stack-overflow, test-vm-parse-abort-on-uncaught-exception, test-worker-nested-uncaught, test-worker-non-fatal-uncaught-exception, test-worker-uncaught-exception, test-worker-uncaught-exception-async, test-shadow-realm, test-shadow-realm-gc, test-whatwg-events-eventtarget-this-of-listener.

Local noise in this debug ASAN container, all reproduced without the worker change: script-leak.test.ts hits the 5 s default timeout (16 s for 10000 compiles), process.test.js fails once because the container has no USER variable, three timing tests in worker.test.ts (message flood, preload import, fs.readFile terminate) fail on worker startup time, and the c-ares terminate test in worker-terminate-lifetime.test.ts reports a LeakSanitizer leak of node_fs_binding::Binding after printing its ok.


no test proof · iteration 0 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/node/vm/vm.test.ts

@coderabbitai

coderabbitai Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Warning

Review limit reached

  • Run on-demand review

On-demand reviews are free for the next 5 days. After that, they cost $0.25 per reviewed file.

Or wait 7 minutes for your next included review.

Check out review usage here.

View limit details

Limit details: You’ve used all 10 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Essentials

Run ID: fa06424f-6465-45d2-9d40-abe31e815c07

📥 Commits

Reviewing files that changed from the base of the PR and between 7d2bec9 and 08c08c8.

📒 Files selected for processing (1)
  • test/js/node/vm/vm.test.ts

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Essentials

Run ID: 9ab76b09-4211-4b35-b76f-d70ede9761f9

📥 Commits

Reviewing files that changed from the base of the PR and between f937cf4 and a130265.

📒 Files selected for processing (4)
  • src/jsc/bindings/BunProcess.cpp
  • src/jsc/bindings/JSDOMExceptionHandling.cpp
  • src/jsc/web_worker.rs
  • test/js/node/vm/vm.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.


Walkthrough

Changes

VM-context exceptions now use the owning process or worker global object for uncaught-exception reporting, capture callbacks, exits, and unhandled rejection dispatch. New subprocess tests cover process and worker handling paths.

VM exception routing

Layer / File(s) Summary
Process exception routing
src/jsc/bindings/JSDOMExceptionHandling.cpp, src/jsc/bindings/BunProcess.cpp
Exception reporting passes generic lexical globals. Uncaught-exception handling resolves the default global object for callbacks and exits.
Worker exception routing
src/jsc/web_worker.rs
Unhandled rejection handling obtains the global object from the worker VM before converting and dispatching the error.
VM exception-routing tests
test/js/node/vm/vm.test.ts
Subprocess tests cover process handlers, capture callbacks, worker handlers, worker error events, output, stderr, and exit codes.

Suggested reviewers: jarred-sumner

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 7d2be

The VM and worker exception-routing change has no confirmed actionable regression in the available evidence and is ready for normal merge checks.

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: routing exceptions from node:vm contexts to uncaughtException handling.
Description check ✅ Passed The description explains the problem, cause, fix, scope, and verification results. It does not use the exact template headings, but it provides the required information in equivalent sections.
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.

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

@robobun

robobun commented Aug 21, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: the fix is complete and the review comments are addressed. The PR is ready for a maintainer.

CI on the current head finished (build 116311, 179 of 181 jobs passed). It is red on two tests. This PR touches neither, and test/js/node/vm/vm.test.ts passed on every lane:

  • test/js/bun/http/serve-pending-promise-abort-leak.test.ts on debian 13 x64-asan. It fails the same way on main.
  • test/integration/next-pages/test/dev-server-ssr-100.test.ts on windows 2019 x64. test/flaky-tests.txt lists it with this signature: ConnectionRefused from the next dev server after 98 of 100 requests.

Both are reported for triage. The same source change passed a full run before the latest merges from main (build 103060, 181 of 181 jobs).

How I reproduced the bug, with release 1.4.0 and with a debug build of main:

  • The script in the PR body prints the error, exits 1, and reports 0 listener calls.
  • A process listener or an EventTarget listener whose function was created in a vm context behaves the same way. On a debug build the EventTarget case aborts in reportException.
  • In a worker, the same report segfaults (WebWorker__dispatchError, Worker.cpp:200) on both builds. The worker repro is in the Notes of the PR body.

The six new children in test/js/node/vm/vm.test.ts fail on stock bun and pass with this branch. Node v26 prints the same lines and exit codes for each of them.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM — small, well-scoped fix that routes vm-context exceptions through defaultGlobalObject() to reach the thread's process.

What was reviewed:

  • Verified defaultGlobalObject() returns the input unchanged for Zig::GlobalObject, so main-realm/worker/ShadowRealm behavior is identical.
  • Traced reportUncaughtExceptionAtEventLoop → Bun__reportUnhandledError → bun_vm() (thread-local) → uncaught_exception; none require the passed global to be a Zig::GlobalObject.
  • The removed uncheckedDowncast<JSDOMGlobalObject> in reportException was dead — its result was only forwarded to a function typed JSGlobalObject*.
  • Tests cover all three affected reporting paths (FinalizationRegistry, EventEmitter, EventTarget) plus the capture callback, subprocess-isolated with exact stdout/stderr/exit assertions.
Extended reasoning...

Overview

Two C++ changes plus tests. In Bun__handleUncaughtException (BunProcess.cpp), the early-return when the incoming global is not a Zig::GlobalObject is replaced with defaultGlobalObject(lexicalGlobalObject), and the two downstream uses of lexicalGlobalObject (calling the capture callback and Bun__Process__exit) are switched to the mapped global. In reportException (JSDOMExceptionHandling.cpp), an uncheckedDowncast<JSDOMGlobalObject> — which asserted on debug builds when the listener's realm was a NodeVMGlobalObject — is removed; the raw lexicalGlobalObject is passed on directly. Four new subprocess tests in test/js/node/vm/vm.test.ts.

Security risks

None identified. This is an exception-routing fix; no parsing of untrusted input, no auth/crypto/permissions. Mapping a vm context to the thread's default global is the existing pattern (promiseRejectionTrackerForNodeVM does the same for rejections) and cannot expose anything the context couldn't already reach via the host.

Level of scrutiny

Moderate. Bun__handleUncaughtException is the single sink for uncaught exceptions, so a mistake would affect every error path. However the change is provably a no-op for the existing Zig::GlobalObject case (defaultGlobalObject returns its argument via dynamicDowncast), and only widens behavior for NodeVMGlobalObject from "return false → fatal path" to "deliver to the thread's process" — which matches Node. I traced the downstream Rust path (Bun__reportUnhandledError → global.bun_vm() reads a thread-local, uncaught_exception takes &JSGlobalObject) and confirmed nothing there requires a Zig::GlobalObject.

Other factors

The tests are well-constructed per the repo's review guidance: subprocess-isolated, test.concurrent, exact stdout/stderr/exitCode assertions, and the FinalizationRegistry case polls a bounded window for the observable condition rather than sleeping. The PR description documents verification against Node v26 and 21 upstream node test files. The removed downcast in reportException was genuinely dead (its result was passed to a parameter typed JSGlobalObject*). No prior human reviews or outstanding comments.

@robobun

robobun commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator Author

The automated review above raised no action items, so there is nothing to change from it. My own self-review of the diff is still in progress. I will post here if it turns up anything.

Comment thread src/jsc/bindings/BunProcess.cpp Resolved
Comment thread src/jsc/web_worker.rs Resolved
@robobun

robobun commented Aug 22, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 9:54 PM PT - Sep 15th, 2026

❌ @robobun, your commit 08c08c8 has 2 failures in Build #116311 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 39992

That installs a local version of the PR into your bun-39992 executable, so you can run:

bun-39992 --bun

@robobun

robobun commented Aug 22, 2026

Copy link
Copy Markdown
Collaborator Author

While checking the fallback paths for this fix, I found that the same report crashes a worker. The worker's last-resort handler passed the context's global to WebWorker__dispatchError, which reads Zig::GlobalObject fields from it (segfault at Worker.cpp:200, also on release 1.4.0). Commit 43108ab makes that handler use the worker's own global, and the test block gained two worker children: one with a handler in the worker, one without (Worker 'error' event, exit code 1, as in node). The child without a handler still crashes with only the C++ part of the fix, so both parts are load-bearing. The PR body is updated for this.

The two comment-length review threads are addressed in 56584f9.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I reviewed this PR and didn't find any bugs. Because it changes the uncaught-exception routing path (Bun__handleUncaughtException, reportException, and the worker's last-resort error dispatch), a human look would still be worthwhile.

What was reviewed:

  • defaultGlobalObject() semantics — a Zig::GlobalObject maps to itself, so main/worker/ShadowRealm are unchanged; only NodeVMGlobalObject is newly routed.
  • reportUncaughtExceptionAtEventLoop takes JSGlobalObject* and just forwards to Bun__reportUnhandledError, so dropping the dead uncheckedDowncast<JSDOMGlobalObject> is safe.
  • The worker's on_unhandled_rejection now dispatches on vm.global() (the worker's own Zig::GlobalObject), which is what WebWorker__dispatchError reads fields from.
  • Tests: six subprocess children, concurrent, drain pipes together, assert exact output before exit code; the FinalizationRegistry case polls a bounded loop and fails visibly if the callback never runs.
Extended reasoning...

Overview

Three tightly-scoped native changes plus a test block:

  • src/jsc/bindings/BunProcess.cpp: Bun__handleUncaughtException maps its incoming global through defaultGlobalObject() instead of returning false for non-Zig::GlobalObject realms. Also swaps lexicalGlobalObject → the mapped globalObject for the capture-callback call() and Bun__Process__exit.
  • src/jsc/bindings/JSDOMExceptionHandling.cpp: removes a dead uncheckedDowncast<JSDOMGlobalObject> (only fed a commented-out block) and passes lexicalGlobalObject straight to Zig::GlobalObject::reportUncaughtExceptionAtEventLoop, whose signature is (JSGlobalObject*, Exception*) and whose body just calls Bun__reportUnhandledError.
  • src/jsc/web_worker.rs: on_unhandled_rejection ignores the realm global it is handed and uses vm.global() for WebWorker__dispatchError, create_syntax_error_instance, and format2.
  • test/js/node/vm/vm.test.ts: six test.concurrent subprocess children covering FinalizationRegistry, a process 'exit' listener, an EventTarget listener, the capture callback, and both worker paths (handler present / absent).

Security risks

None identified. This is exception-routing plumbing; no user input parsing, no privilege boundary. The change replaces an uncheckedDowncast (assertion in debug, type-confusion in release) with a safe dynamicDowncast-based mapping, and replaces a segfault path in the worker with the intended dispatch — both strictly reduce risk.

Level of scrutiny

High. This is the one sink for uncaught exceptions (VirtualMachine::uncaught_exception → Bun__handleUncaughtException) and the worker's fatal-error fallback. A regression here changes process exit behavior or crashes workers. That said, the diff is minimal and the mapping (defaultGlobalObject) is the established idiom the codebase uses to find the thread's process from a bare realm — promiseRejectionTrackerForNodeVM already does the same for rejections, per the PR body.

I checked:

  • defaultGlobalObject(g) at ZigGlobalObject.h:914 — returns g if it is a Zig::GlobalObject, else the per-thread default. So the main realm, workers, and ShadowRealm (all Zig::GlobalObject) behave exactly as before; only a NodeVMGlobalObject is newly routed. There is no third realm type in Bun that would silently change behavior.
  • reportUncaughtExceptionAtEventLoop at ZigGlobalObject.cpp:1036 — parameter is JSGlobalObject*, body is Bun__reportUnhandledError(globalObject, ...); passing the vm-context global here is fine and matches JSCTaskScheduler.cpp:124.
  • uncaught_exception at VirtualMachine.rs:1531 — when Bun__handleUncaughtException used to return 0 for a vm-context global, control fell through to (self.on_unhandled_rejection)(self, global_object, err) with the vm-context global, which in a worker is the crashing WebWorker__dispatchError path the Rust hunk fixes. Both hunks are load-bearing, as the PR states.
  • The capture-callback call() and Bun__Process__exit now receive the mapped Zig::GlobalObject rather than the vm context — consistent with the callback belonging to process, and covered by the setUncaughtExceptionCaptureCallback test child.

Other factors

  • The PR description is unusually thorough: it enumerates every reporting site, every consumer of the realm global downstream, sibling functions with the same guard and why they are unaffected, and out-of-scope ShadowRealm behavior. Node v26 parity was verified for every child.
  • The two comment-cop bot threads are resolved (comments shortened in 56584f9).
  • Tests follow harness conventions: bunEnv/bunExe, test.concurrent, Promise.all on stdout/stderr/exited, exact-string assertions before the exit-code check. The FinalizationRegistry child polls Bun.gc(true) in a bounded loop and asserts a sentinel line if it never fires (so the test can't vacuously pass).

I'm deferring rather than approving because the touched path decides process termination and worker crash behavior; a maintainer should confirm that routing every non-Zig::GlobalObject realm to the thread's default process is the intended policy going forward.

@robobun

robobun commented Aug 22, 2026

Copy link
Copy Markdown
Collaborator Author

The second automated review found no defects either. It asks a maintainer to confirm the routing policy. For the record, the policy this PR implements is narrow: only a realm that has no process object at all (a node:vm context, the one non-Zig::GlobalObject realm in bun) is routed to the thread's process. Every Zig::GlobalObject realm, including a ShadowRealm, keeps the process object it has today. This is the same mapping the vm rejection tracker (promiseRejectionTrackerForNodeVM) has used for rejections. Whether a ShadowRealm should also share the thread's process is a separate question, noted in the PR body.

Nothing is left open from the reviews. Waiting on CI.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated review found no bugs. This changes uncaught-exception routing for node:vm contexts (previously print + exit 1, now delivered to process.on('uncaughtException')) and touches the worker's last-resort error handler, so a maintainer should confirm the routing policy before merge.

Checked: defaultGlobalObject() maps a Zig::GlobalObject to itself (main/worker/ShadowRealm behaviour unchanged) and only remaps a NodeVMGlobalObject to the thread's default global. reportUncaughtExceptionAtEventLoop takes a plain JSGlobalObject* and forwards to Bun__reportUnhandledError, so dropping the JSDOMGlobalObject downcast is safe. The worker's on_unhandled_rejection now dispatches on vm.global(), which is what WebWorker__dispatchError expects; the ignored parameter was only ever the realm the error was raised in. The six new subprocess tests cover FinalizationRegistry, EventEmitter, EventTarget, capture callback, and both worker paths.

Extended reasoning...

Overview

The PR routes exceptions reported against a node:vm context's NodeVMGlobalObject to the thread's process uncaughtException machinery instead of returning false (which previously fell through to print-and-exit-1 on the main thread and to a segfault in a worker). Three source changes: Bun__handleUncaughtException in BunProcess.cpp now maps its lexical global through defaultGlobalObject() and uses that mapped global for the capture callback and Bun__Process__exit; reportException in JSDOMExceptionHandling.cpp drops an uncheckedDowncast<JSDOMGlobalObject> (which asserts on debug builds when handed a vm context global) and passes the lexical global straight to reportUncaughtExceptionAtEventLoop; and the worker's on_unhandled_rejection in web_worker.rs dispatches on vm.global() instead of the realm global handed in. Six new subprocess tests in vm.test.ts.

Security risks

None identified. This is error-routing plumbing; no untrusted input parsing, no auth/crypto/permission surfaces. The change makes previously-fatal errors catchable by user handlers, which matches Node semantics — it does not weaken any check.

Level of scrutiny

Medium-high. The mechanical change is small and the defaultGlobalObject() pattern is already the established idiom for reaching the thread's Bun state from a vm context (promiseRejectionTrackerForNodeVM uses it). But it changes the observable behaviour of uncaught-exception handling — code that used to exit 1 will now run user handlers and continue — and it also fixes a worker segfault path. The author explicitly noted the routing policy (only NodeVMGlobalObject, not ShadowRealm) as something a maintainer should confirm. Both of those warrant a human sign-off rather than an automated approval.

Other factors

The tests are thorough (six subprocess children, each verified against Node v26, covering FinalizationRegistry / EventEmitter / EventTarget / capture callback and both worker paths with and without a handler) and the PR description enumerates every reporting site checked and the upstream Node test suites run. The two comment-cop threads about long comments were addressed in 56584f9 and are resolved. I verified defaultGlobalObject(JSC::JSGlobalObject*) at ZigGlobalObject.h:914 returns the argument when it is already a Zig::GlobalObject, so main-realm/worker/ShadowRealm behaviour is preserved; and reportUncaughtExceptionAtEventLoop at ZigGlobalObject.h:194 / ZigGlobalObject.cpp:1036 accepts a plain JSGlobalObject* and only forwards it to Bun__reportUnhandledError, so no downcast is needed there.

…aughtException

Bun__handleUncaughtException returned false for a global object that is
not a Zig::GlobalObject. The deferred-work runner (FinalizationRegistry
callbacks), the native EventEmitter and JSEventListener all report an
exception with the realm of the object that raised it. For a
FinalizationRegistry or a listener function created in a node:vm context
that realm is a NodeVMGlobalObject, so the exception was printed and the
exit code set to 1 without the uncaughtException listeners, the monitor
or the capture callback running.

Map the realm to the thread's default global, which owns the process
object, the way promiseRejectionTrackerForNodeVM already does for
rejections. reportException no longer downcasts the listener's realm to
a Zig::GlobalObject before passing it on; debug builds asserted there.
The worker's last-resort error handler passed the realm the error was
reported against to WebWorker__dispatchError, which reads Zig::GlobalObject
fields from it. For an exception raised against a node:vm context that realm
is a NodeVMGlobalObject, and the worker crashed with a segmentation fault
(Worker.cpp:200) instead of emitting the Worker 'error' event.
@robobun
robobun force-pushed the farm/f60a1c61/vm-uncaught-exception-process branch from d26417c to b5ad45c Compare August 25, 2026 06:28
@robobun

robobun commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased on main (e3bd3e4). The one conflict was in reportException (JSDOMExceptionHandling.cpp): #40410 added RETURN_IF_EXCEPTION(scope, ); after the call this PR changes. The resolution keeps both: the call passes lexicalGlobalObject, and the exception check follows it. The six new tests and the whole of test/js/node/vm/vm.test.ts pass on the rebased branch (283 pass, 0 fail). The empty retrigger commit was dropped.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I reviewed this PR and didn't find any bugs. The fix is small and follows the established defaultGlobalObject() pattern (same mapping promiseRejectionTrackerForNodeVM already uses for rejections), and the six new subprocess tests cover each reporting site plus both worker paths. Because it changes uncaught-exception routing and worker error dispatch — critical process-exit paths — a maintainer look would still be worthwhile, particularly to confirm the routing policy for non-Zig::GlobalObject realms.

What was reviewed:

  • defaultGlobalObject() is identity for Zig::GlobalObject (main/worker/ShadowRealm unchanged); only NodeVMGlobalObject maps to the thread's default global.
  • reportException's removed uncheckedDowncast<JSDOMGlobalObject> was only fed to reportUncaughtExceptionAtEventLoop, which takes JSGlobalObject* and reaches the VM via a thread-local — safe with the vm-context global.
  • on_unhandled_rejection now dispatches on vm.global(); on a worker thread that IS the worker's Zig::GlobalObject, so the main-realm path is unchanged and the vm-context crash is fixed.
  • The call()/Bun__Process__exit() swap to globalObject runs the capture callback in the realm that owns process, matching Node.
Extended reasoning...

Overview

Four files: Bun__handleUncaughtException in BunProcess.cpp now maps its incoming global through defaultGlobalObject() instead of returning false for a non-Zig::GlobalObject; reportException in JSDOMExceptionHandling.cpp drops an uncheckedDowncast<JSDOMGlobalObject> that asserted on a NodeVMGlobalObject in debug builds; on_unhandled_rejection in web_worker.rs dispatches on vm.global() instead of the realm global it is handed (which WebWorker__dispatchError reads as a Zig::GlobalObject and segfaulted on); and six new subprocess tests in vm.test.ts.

Security risks

None identified. This is error-routing plumbing; no untrusted input parsing, no auth/crypto, no new user-reachable API surface.

Level of scrutiny

Moderate-to-high. The diff is small (~15 production lines) and mechanical — defaultGlobalObject() is the standard idiom used throughout the bindings for exactly this case, and promiseRejectionTrackerForNodeVM already routes vm-context rejections the same way. But the code path is uncaught-exception delivery and worker error dispatch, which decides process exit codes and whether user handlers run. I traced each change: defaultGlobalObject() is identity for a Zig::GlobalObject, so the main realm, workers, and ShadowRealm are unchanged; reportUncaughtExceptionAtEventLoop takes a plain JSGlobalObject* and only calls Bun__reportUnhandledError, which reaches the VM via bun_vm()'s thread-local, so passing the vm-context global there is safe; and on a worker thread vm.global() is the worker's own global, so the Rust change is a no-op except when the passed-in global is a vm context (the crash case).

Other factors

The PR body documents extensive verification (Node v26 parity for every new test child, ~40 upstream test-worker-*/test-process-* files run clean, CI green on build 103060). The comment-cop threads about long comments were addressed and resolved. The tests follow harness conventions (test.concurrent, drained stdout/stderr/exitCode in one Promise.all, bounded poll for the FinalizationRegistry callback rather than a bare sleep, exact-output assertions). The one open item is a policy confirmation — that a vm context's uncaught exception should reach the thread's process — which the PR argues from Node parity and existing precedent, but is worth a maintainer's explicit sign-off given it governs process exit behavior.

@robobun

robobun commented Sep 12, 2026 •

Copy link
Copy Markdown
Collaborator Author

A fuzz run reached the debug assert in reportException with a listener object ({ handleEvent }) from a node:vm context, so I checked whether this change covers that shape too. It does.

JSEventListener::handleEvent takes lexicalGlobalObject from the listener itself (jsFunction->globalObject()), so a listener object made in a context reports against the NodeVMGlobalObject exactly like a listener function does. All of its reportException calls go through the function this PR changes.

Four shapes, each target.addEventListener("x", vm.runInNewContext(<source>)) then dispatchEvent, on the main thread and in a worker that has an uncaughtException handler:

listener source main b993710, debug this branch merged with main b993710, debug
(function () { throw new Error("x") }) ASSERTION FAILED: !source || is<Target>(*source) uncaughtException handler runs, exit 0
({ handleEvent() { throw new Error("x") } }) same assert same
({ get handleEvent() { throw new Error("x") } }) same assert same
({ handleEvent: 1 }) same assert handler gets TypeError: 'handleEvent' property of event listener should be callable, exit 0

All 8 runs (4 shapes, main thread and worker) assert before and pass after. On release 1.4.3-canary.1+6a92015fc the listener object shapes are not assert-only: on the main thread they print the error and exit 1 without running the handler, and in a worker all four end with panic: Segmentation fault at address 0x101, the same crash as the function listener in the description.

Jarred-Sumner pushed a commit that referenced this pull request Sep 12, 2026
…a node:vm context (#42521)

### Problem
- A `PerformanceObserver` whose callback was created in a `node:vm`
context crashes the process when it delivers entries. Release 1.4.2 and
canary: `panic(main thread): Segmentation fault at address 0x18`. Debug:
`ASSERTION FAILED: !source || is<Target>(*source)`, `uncheckedDowncast
[Target = Zig::GlobalObject, Source = JSC::JSGlobalObject]`. Node
v26.3.0 delivers.
- `JSPerformanceObserverCallback::handleEvent`
(`JSPerformanceObserverCallback.cpp:63`) casts
`callback->globalObject()` to `Zig::GlobalObject` with no check and
builds the wrappers for the observer and the entry list from it.
`JSCallbackData::invokeCallback` (`JSCallbackData.cpp:53`) repeats the
cast to read `scriptExecutionContext()`. The global of a context is a
`NodeVMGlobalObject`. It has neither.

### Fix
- Both sites map the realm through `defaultGlobalObject()`. A
`Zig::GlobalObject` maps to itself. A context maps to the default global
of the thread.
- Correct because that global owns `PerformanceObserver`, so the
wrappers come from the realm of the class. Node also builds the entry
list in the main realm. The callback still runs in its own realm.
- Verified: new case in `test/js/node/perf_hooks/perf_hooks.test.ts`. It
fails on canary (segfault) and on a debug build of main (assertion).
Notes lists the other suites.

### Background
- The main realm and each worker have a `Zig::GlobalObject`. It holds
the DOM wrapper structures and the `ScriptExecutionContext`.
`vm.createContext()` makes a `NodeVMGlobalObject`, a bare realm without
them.
- A context has no `PerformanceObserver`. A test runner or a sandbox
hands it the host class, so the callback is a function of the context's
realm.
- `defaultGlobalObject(global)` (`ZigGlobalObject.h:898`) returns
`global` if it is a `Zig::GlobalObject`, else the default global of the
thread. Other bindings already use it for contexts.

<details><summary>Notes</summary>

Repro from the report (`bun p.js`). Confirmed here on 1.4.3-canary.1:
exit 139. The report has the same on release 1.4.2. Node v26.3.0 prints
`survived, entries seen: 1`.

```js
const vm = require("vm");
const ctx = vm.createContext({ PerformanceObserver, performance });
vm.runInContext(`
  new PerformanceObserver(list => { globalThis.seen = list.getEntries().length; }).observe({ entryTypes: ["mark"] });
  performance.mark("hello");
`, ctx);
setTimeout(() => console.log("survived, entries seen:", vm.runInContext("globalThis.seen", ctx)), 100);
```

The same crash from the host side, all confirmed on 1.4.3-canary.1
before the fix and delivered after it:

- `new
PerformanceObserver(vm.runInNewContext("(function(){})")).observe({
entryTypes: ["mark"] }); performance.mark("x")`
- the same with the `PerformanceObserver` class of `node:perf_hooks` (it
extends the global class and passes the callback to it)
- `observe({ type: "measure", buffered: true })`, which delivers before
`observe()` returns and not from a task

The new test runs these four shapes in one child. For each one it checks
that the callback is not an instance of the host `Function`, that `this`
and the second argument are the observer, that the list is an instance
of the host `PerformanceObserverEntryList`, and the entry names that
`list.getEntries()` returns inside the context. Node v26.3.0 prints the
same JSON for the child script.

In a worker, the default global is the global of the worker
(`Bun__getDefaultGlobalObject` reads a thread-local). Checked by hand on
the fixed debug build: a context callback inside a `worker_threads`
Worker gets a list that is an instance of the
`PerformanceObserverEntryList` of the worker.

Not in this PR: a context callback that throws. `handleEvent` then calls
`reportException` with the realm of the callback, and `reportException`
(`JSDOMExceptionHandling.cpp:61`) has the same cast. A debug build
asserts there (checked on the fixed build). In a release build that cast
compiles to nothing, so the exception takes the reporting path that
#39992 describes. #39992 removes the cast and routes the exception to
`process`, for this path and for the `EventTarget` listener path. This
PR leaves the call as it is so that the two do not overlap.

`JSAbortAlgorithm.cpp:33` and `:64` have the same unchecked cast. They
are not changed. Its callbacks are never user functions:
`startPipeToOperation` (`JSStreamPipeToOperation.cpp:581`) passes a
bound builtin made in the global of the stream, and
`$addAbortAlgorithmToSignal` has no caller in `src/js`.

Suites run with the fixed debug build (ASAN, assertions on), all pass:
`test/js/node/perf_hooks/perf_hooks.test.ts`,
`test/js/node/vm/vm.test.ts`,
`test/js/web/workers/performance-observer-leak.test.ts`,
`test/js/deno/performance/performance.test.ts`, `test/js/web/abort/`,
`test/js/web/streams/pipeTo-signal-leak.test.ts`,
`test/js/web/streams/pipeTo-shutdown-gc.test.ts` (the abort algorithm of
`pipeTo` goes through `JSCallbackData::invokeCallback`). Upstream files,
all exit 0: test-performanceobserver-gc, test-performance-measure,
test-performance-measure-detail, test-performance-function-async,
test-perf-hooks-timerify-basic, test-perf-hooks-timerify-error,
test-perf-hooks-timerify-constructor, test-perf-gc-crash,
test-net-perf_hooks, test-http-perf_hooks. The child script of the new
test also runs clean with `BUN_JSC_validateExceptionChecks=1`.

</details>

<!-- robobun:evidence:begin -->

---

**[human-review]** gate passed · iteration 0 · 3 files touched

<details><summary>fails on main (without fix)</summary>

```console
ASAN without fix: 1 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/node/perf_hooks/perf_hooks.test.ts
bun test v1.4.3 (6a92015)

test/js/node/perf_hooks/perf_hooks.test.ts:
(pass) stubs [17.49ms]
(pass) doesn't throw [49.64ms]
(pass) Symbol name argument throws V8 wording [14.02ms]
(pass) measure(name, optionsWithoutStartOrEnd, endMark) honours the trailing endMark [6.73ms]
(pass) timerify entry shape [95.69ms]
(pass) timerify is exposed on both performance and as a top-level export (Node v25.2+) [3.17ms]
(pass) export surface matches Node v26.3.0 [11.30ms]
(pass) timerify and createHistogram survive Object.prototype option pollution [511.64ms]
(pass) timerify and AsyncResource.bind survive Object.prototype.get pollution [701.65ms]
(pass) net entries are instanceof PerformanceEntry [496.08ms]
(pass) re-wrapped native entries, timing and observer keep JS identity [20.26ms]
279 |     env: bunEnv,
280 |     stdout: "pipe",
281 |     stderr: "pipe",
282 |   });
283 |   const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
284 |   expect(stder
... (truncated)

release without fix: 1 FAILED
bun test v1.4.3-canary.1 (6a92015)

test/js/node/perf_hooks/perf_hooks.test.ts:
(pass) stubs [0.06ms]
(pass) doesn't throw [0.14ms]
(pass) Symbol name argument throws V8 wording [0.11ms]
(pass) measure(name, optionsWithoutStartOrEnd, endMark) honours the trailing endMark [0.09ms]
(pass) timerify entry shape [1.06ms]
(pass) timerify is exposed on both performance and as a top-level export (Node v25.2+) [0.03ms]
(pass) export surface matches Node v26.3.0 [0.12ms]
(pass) timerify and createHistogram survive Object.prototype option pollution [9.42ms]
(pass) timerify and AsyncResource.bind survive Object.prototype.get pollution [10.13ms]
(pass) net entries are instanceof PerformanceEntry [7.02ms]
(pass) re-wrapped native entries, timing and observer keep JS identity [0.29ms]
279 |     env: bunEnv,
280 |     stdout: "pipe",
281 |     stderr: "pipe",
282 |   });
283 |   const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
284 |   expect(stderr).toBe("");
                       ^
error: expect(received).toBe(expected)

- ""
+ "============================================================
+ Bun Canary v1.4.3-canary.1 (
... (truncated)
```

</details>

<details><summary>passes on PR (with fix)</summary>

```console
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/node/perf_hooks/perf_hooks.test.ts
bun test v1.4.3 (6a92015)

test/js/node/perf_hooks/perf_hooks.test.ts:
(pass) stubs [13.18ms]
(pass) doesn't throw [35.30ms]
(pass) Symbol name argument throws V8 wording [10.58ms]
(pass) measure(name, optionsWithoutStartOrEnd, endMark) honours the trailing endMark [5.53ms]
(pass) timerify entry shape [54.00ms]
(pass) timerify is exposed on both performance and as a top-level export (Node v25.2+) [2.02ms]
(pass) export surface matches Node v26.3.0 [8.04ms]
(pass) timerify and createHistogram survive Object.prototype option pollution [405.22ms]
(pass) timerify and AsyncResource.bind survive Object.prototype.get pollution [508.57ms]
(pass) net entries are instanceof PerformanceEntry [418.48ms]
(pass) re-wrapped native entries, timing and observer keep JS identity [15.11ms]
(pass) PerformanceObserver delivers entries to a callback created in a node:vm context [611.63ms]
(pass) mark/measure toJSON and inspection include detail without perf_hooks being loaded [931.56ms]

 13 pass
 0 fail
 76 expec
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped)
  target       linux-x64-gnu
  build type   Release
  build dir    ./build/release
  revision     558e6ee
  features     baseline

23 deps, 131 codegen, 1172 objects in 687ms

ninja: Entering directory `/workspace/bun/build/release'
[1/1244] install /workspace/bun
bun install v1.4.3-canary.1 (6a92015)

Checked 22 installs across 61 packages (no changes) [9.00ms]
[2/1244] install /workspace/bun/packages/bun-error
bun install v1.4.3-canary.1 (6a92015)

Checked 1 install across 2 packages (no changes) [1.00ms]
[3/1244] gen bindgenv2
[4/1244] install /workspace/bun/src/node-fallbacks
bun install v1.4.3-canary.1 (6a92015)

Checked 111 installs across 104 packages (no changes) [8.00ms]
[5/1244] gen ErrorCode+*.h
[6/1244] gen node-fallbacks/react-refresh.js
Bundled 1 module in 11ms

  react-refresh.js  4.81 KB  (entry point)

[7/1244] fetch libjpeg-turbo
[libjpeg-turbo] up to date
[8/1217] fetch tinycc
[tinycc] up to date
[9/1216] fetch zlib
[zlib] up to date
[10/1216] gen .bind.ts → GeneratedBindings.cpp
[11/1216] gen bake.{client,server,error}.js
-> bake.client.js, bake.server
... (truncated)
```

</details>

<details><summary>diff hotspot</summary>

```
src/jsc/bindings/webcore/JSCallbackData.cpp        |  3 +-
 .../webcore/JSPerformanceObserverCallback.cpp      |  3 +-
 test/js/node/perf_hooks/perf_hooks.test.ts         | 86 ++++++++++++++++++++++
 3 files changed, 90 insertions(+), 2 deletions(-)
```

</details>

**gate history** · 1 passed · 0 rejected · iteration 0

<details><summary>evidence per changed file</summary>

```
file                                                      reads  edits  tests
src/jsc/bindings/webcore/JSCallbackData.cpp                   1      1      6
…/jsc/bindings/webcore/JSPerformanceObserverCallback.cpp      1      1      6
test/js/node/perf_hooks/perf_hooks.test.ts                    2      1      6
```

</details>

**root cause** · written by the author bot

The callback delivery path in
`JSPerformanceObserverCallback::handleEvent` and
`JSCallbackData::invokeCallback` took the callback's own global object
and unchecked-downcast it to the Bun global, which is invalid when the
callback was created inside a `node:vm` context, since a
`NodeVMGlobalObject` is a `Bun::GlobalScope` rather than a
`Zig::GlobalObject`. Reading the wrapper caches and script execution
context off that mis-typed pointer produced a segfault in release builds
and a downcast assertion in debug builds. Both cast sites now route
through `defaultGlobalObject(callback->globalObjec…

<!-- robobun:evidence:end -->
…ught-exception-process

# Conflicts:
#	test/js/node/vm/vm.test.ts
@robobun

robobun commented Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator Author

Merged main to clear the conflict. The head is now 7d2bec9, on main at 877a3f9.

The only conflict was in test/js/node/vm/vm.test.ts. This branch and #42795 each appended a block at the end of the file. The merge keeps both blocks. The src/ changes of this PR are the same as before.

Checked with a debug ASAN build: test/js/node/vm/vm.test.ts gives 308 pass, 0 fail on the first merge (a130265), and the 6 tests of this PR pass on 7d2bec9. The 6 tests still fail on the current canary (09bb546) with panic: Segmentation fault at address 0x101.

The first merge took main at f937cf4, where test/internal/build-post-link-ordering.test.ts was red on every lane (#42852). The second merge only adds #42863, which fixes that test. It passes here (11 pass).

CI can still show one failure that this diff does not cause: test/js/bun/http/serve-pending-promise-abort-leak.test.ts fails on the debian 13 x64-asan lane of most PR builds since 2026-09-15 22:42Z (expect(alive).toBe(0), Received: 1). #42190 covers it.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Comment thread test/js/node/vm/vm.test.ts Resolved
@robobun

robobun commented Sep 16, 2026

Copy link
Copy Markdown
Collaborator Author

The latest automated reviews have one optional item: two test comments described the earlier behavior. Commit 08c08c8 removes those sentences, and the thread is resolved. No other action items are open.

The branch now includes main up to 877a3f9. The diff against main is still the same four files. I built that head with the debug build and ran the six new tests again: all pass.

About the red run on the previous head (build 116295): the only test that failed on every lane was test/internal/build-post-link-ordering.test.ts. This PR does not touch it, it failed the same way on main, and #42863 (now merged into this branch) fixes it.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM — the comment cleanup from the previous round is in, and the three native edits are small and consistent with each other.

What was reviewed:

  • Bun__handleUncaughtException: every downstream use of the global (processObject(), getVM, the capture-callback call, both Bun__Process__exit sites) now uses the defaultGlobalObject() result; a Zig::GlobalObject maps to itself, so main-thread, worker, and ShadowRealm realms are unchanged.
  • Thread affinity of the fallback: Bun__getDefaultGlobalObject reads a #[thread_local] set per VM (Bun__setDefaultGlobalObject runs for worker globals too), so a worker's context maps to the worker's own process, which the two worker children assert via the parent-side monitor.
  • The other on_unhandled_rejection implementations (default_on_unhandled_rejection, run_command's before-close handler) ignore the realm argument, and Bun__Process__exit resolves the VM from the thread, so no sibling site still depends on the lexical global being a Zig::GlobalObject.
  • reportException: the removed uncheckedDowncast<JSDOMGlobalObject> fed only a JSGlobalObject* parameter, so dropping it changes no behavior beyond removing the unsound cast.
Extended reasoning...

Overview

The PR touches three native sites and one test file. src/jsc/bindings/BunProcess.cpp replaces an inherits(Zig::GlobalObject::info()) early-return in Bun__handleUncaughtException with defaultGlobalObject(lexicalGlobalObject) and switches the two remaining lexicalGlobalObject uses (the capture-callback call and the Bun__Process__exit(…, 1) after a throwing capture callback) to the resolved global. src/jsc/bindings/JSDOMExceptionHandling.cpp drops an uncheckedDowncast<JSDOMGlobalObject> and a commented-out block, passing the lexical global straight to Zig::GlobalObject::reportUncaughtExceptionAtEventLoop, which only forwards to Bun__reportUnhandledError. src/jsc/web_worker.rs makes the worker's on_unhandled_rejection dispatch on vm.global() instead of the realm it was handed. test/js/node/vm/vm.test.ts adds six spawned children covering FinalizationRegistry, process.on('exit'), EventTarget listeners, the capture callback, and two worker variants. The only change since the prior review is commit 08c08c8, which removed the two "used to" sentences flagged in the earlier nit.

Security risks

None identified. The change affects where an already-uncaught exception is delivered (the owning thread's process object rather than being dropped or crashing); it introduces no new parsing of untrusted data, no new allocations, and no new privilege or network surface. The worker fix removes a segfault path (reading Zig::GlobalObject fields off a NodeVMGlobalObject), which is a memory-safety improvement rather than a risk.

Level of scrutiny

Moderate: uncaught-exception routing is runtime-critical, so I traced every consumer of the global that the change rewires. defaultGlobalObject() (ZigGlobalObject.h:900) returns the input when it is already a Zig::GlobalObject, so the main realm, workers, and ShadowRealms are identity-mapped and their behavior is unchanged. The fallback Bun__getDefaultGlobalObject reads a #[thread_local] CACHED_GLOBAL_OBJECT that Bun__setDefaultGlobalObject populates for every global created through the standard creation paths (ZigGlobalObject.cpp:551 and :680), so on a worker thread a context maps to the worker's global, not the main thread's — the concern the REVIEW.md "never back per-VM state with thread-locals" rule is about does not apply here because the cached value is intentionally per-thread and each worker has its own VM on its own thread. Bun__Process__exit resolves the VM via bun_vm(), which is thread-based and works with any global. The remaining on_unhandled_rejection implementations (default_on_unhandled_rejection, on_quiet_unhandled_rejection_handler_capture_value, run_command's before-close variant) ignore the global argument; the jest handler does use it but is reached before Bun__handleUncaughtException via the isBunTest short-circuit and is unchanged by this PR. In reportException, the removed downcast produced a pointer that was only ever passed as JSGlobalObject*, so removing it is behavior-preserving apart from eliminating the assertion in debug builds.

Other factors

The test block uses test.concurrent.each, spawns with bunEnv, drains stdout/stderr/exit concurrently, and asserts exact stdout plus empty stderr, so each assertion can fail; the FinalizationRegistry case's Bun.sleep(1) sits inside a bounded poll loop and the "never ran" fallback line would break the exact-stdout match rather than pass silently. The parent-side uncaughtExceptionMonitor in the worker children doubles as a negative check that the exception did not reach the main thread. No CODEOWNERS entry covers the changed files, no human reviewer has requested changes, and the bug hunt ran dry. The one prior nit from this reviewer was addressed in the latest commit, and no new concerns surfaced, so approval is appropriate.

Jarred-Sumner added a commit that referenced this pull request Oct 20, 2026
… and CLI (#46021)

### What does this PR do?

Hardening. This collects the open pull requests that fix a crash in Bun
into one change, and fixes about 20 more crashes that had no pull
request.

"Crash" here means a segfault, a Rust panic, an abort, a failed
assertion, memory corruption that a sanitizer reports, a native stack
overflow, or an exception that ends the process and that the program
can't catch. With this PR those cases throw a normal error, print a
normal CLI error and exit 1, or just work.

306 pull requests are included: 227 whole, and 79 cut down to the crash
fix where the rest was a refactor, a feature or a behavior change. Each
one was checked against current `main` first. 45 more turned out to be
fixed already, and 17 were duplicates. The full list is at the bottom.

#### Crashes you could hit in normal use

- **`bun build` with macros and a `.env` file crashed at random.** In a
repro with many macro modules, more than a third of the builds crashed.
Now 3,000 of 3,000 produce the right bundle. (#45960)
- **`bun run` and `bunx` aborted if a signal arrived while the child was
being spawned.** (#38926, #45965)
- **`bun build --compile ./index.js ./public/*` panicked** if an
embedded file's name wasn't valid UTF-8.
- **A truncated or corrupted compiled executable** died with SIGBUS or a
panic at startup. It now prints an error. (#31787, #38251, #41360)
- **Dev server:** several `Option::unwrap()` panics after a failed or
deleted import (#38046, #44744, #44746), a segfault when an `onLoad`
plugin throws while another bundle is queued, a request that hung and
then panicked with `bundle active`, and `server.stop()` that never
resolved after a client aborted a waiting request.
- **`Bun.serve`:** `server.fetch(url, { headers: new Headers() })`
followed by a GC segfaulted (#40888). Routes were used after free after
`server.reload()` with `tls.serverName` (#38636).
- **`text()` and `json()` on a stream of string chunks** could abort the
process, a regression in 1.4.0. (#44269)
- **`Bun.Transpiler` with `exports.eliminate` or `exports.replace`**
aborted on `export default 1` and on most re-export clauses. (#44137)
- **A decorated `declare` field in a class expression** with
`experimentalDecorators` panicked. (#38095)
- **YAML and JSON5 files with a key that isn't a string** panicked with
`--no-bundle` and in `Bun.Transpiler`. (#41827)
- **`Bun.FileSystemRouter`:** reading `.params` segfaulted when a
rejected route candidate left its parameters behind. (#39290, #39291)
- **Native addons that call `uv_async_*`, `uv_timer_*`, `uv_idle_*`,
`uv_prepare_*`, `uv_check_*`, `uv_queue_work` or `uv_cwd`** aborted with
"unsupported uv function" on Linux and macOS. They're implemented now.
(#36609, #39652, #39892)
- **`--watch` and `--hot`** panicked when the system was out of inotify
instances or file descriptors, or when the reload `exec` failed. They
print an error now. (#39629, #39975, #44837)
- **Paths longer than the path buffer** panicked in `bun install`, the
resolver, the bundler, `--compile`, `tsconfig.json` `paths` and
`baseUrl`, `package.json` `main` and `sideEffects`, `bun run --filter`,
`bun pm diff`, source maps and snapshots. They're ordinary errors now,
or they work. (#36340, #37529, #39104, #39650, #43067)
- **A Worker that creates a `ShadowRealm` and imports
`node:worker_threads` in it** segfaulted.
- **`structuredClone` or `postMessage` of an X25519 key** gave an object
that aborted the process when read. (#45624)
- **`node:stream` web adapters and `node:http2`** could end the process
with an exception that no handler could catch. (#45076, #45975)
- **Windows:** a watcher panic in a burst of file changes (#44344), a
segfault after the machine resumes from sleep (#33015), crashes in the
shell's pipe reader (#39638, #43606), and addons that import from
`node.exe` without the delay-load hook (#35618).

Most of the rest needs unusual input: strings near the 2 GiB limit,
buffers that another thread or a getter resizes or detaches in the
middle of a call, `worker.terminate()` at a bad moment, running out of
memory or file descriptors, very deep nesting, or hostile arguments to
`bun:ffi`, `node:vm` and `bun:sqlite`.

#### Behavior changes

Things that didn't crash before and behave differently now:

- `new` on native functions that aren't constructors throws a
`TypeError`, as in Node: `util.types.*`, `buffer.isAscii`, `isUtf8`,
`transcode`, `resolveObjectURL`, `bun:jsc` exports, `cc()` symbols. It
used to return the call's result. They also stop printing as `[class
hostname]`. (#34575)
- `` $`cmd` `` throws `ERR_INVALID_ARG_VALUE` if an environment
variable's name or value contains a NUL byte. It used to cut the value
at the NUL. (#44981)
- `cc()` functions throw a `TypeError` for arguments that used to reach
C as garbage, and `read.*(ptr, NaN)` throws. (#37989, #38057, #40773)
- As PID 1, `bun` exits with 128 + the signal number on Ctrl+C or
`docker stop`. (#38877)
- A `NODE_MODULE` addon that's already loaded by the main thread throws
`ERR_DLOPEN_FAILED` when a live Worker loads it too, as in Node.
(#39968)
- An exception from a `node:vm` context reaches `uncaughtException`
handlers. (#39992) `vm.constants.DONT_CONTEXTIFY` returns the real
global proxy. (#34623)
- `createPrivateKey` rejects an EC JWK whose private value doesn't match
its public point. (#33752)
- `@dec static {}` is a syntax error, as in TypeScript and esbuild.
(#44883)
- `clearTimeout` ignores 0 and negative ids, and timer ids no longer
wrap. (#44771)
- HEAD for a `Response` whose body is an S3-backed `Blob` reports the
length that GET sends. (#44734)
- `bun:sqlite` and `node:sqlite`: if `iterate()` left a write unfinished
on a connection that has a hook, a user function or an authorizer, the
write is finished on the connection's next call instead of during
garbage collection. If the database is gone too, it's rolled back.
- `bun test --bail` runs exit listeners and closes SQLite databases.
(#39010)
- Dev server: a request for a client script waits while a bundle is in
flight (#42733), query strings reach framework routes (#33232), and a
request gets a 500 instead of hanging when plugins fail (#36812).

#### File formats

- `.jsc` bytecode files get a 24-byte footer so they can be verified
before decoding. Files from an older Bun are ignored and the source is
parsed instead. (#39396)
- `node:vm` `cachedData` gets an 8-byte checksum. A blob from an older
Bun is rejected, which the API allows. (#32839)
- The built-in modules section of a compiled executable changes from
format 1 to 2 and carries an engine stamp. (#44907)

#### Performance

Measured in instructions per operation on release builds of this branch
and its base, with an A/A run for the noise floor (0.0 to 0.2 %).

No change: `Bun.serve`, `node:http`, WebSocket echo and publish, `bun
build` of 3,807 modules, `bun run` with 2,000 imports, `readdir` /
`Glob` / `fs.cp` over 23,689 entries, startup and RSS. The binary grows
by 176 KB (0.17 %).

| Faster | Instructions |
| --- | --- |
| WebSocket echo of a 1 MB non-ASCII text message | −72 % |
| `Bun.inspect` of a large non-ASCII string | −39 % |
| `Bun.markdown.html` on large non-ASCII input | −33 % |
| `` $`cmd` `` with 300 environment variables | −6 % |
| `fs.readSync` | −5 % |
| `TextEncoder.encodeInto`, short ASCII strings | −4 % |
| async `crypto.pbkdf2`, 16-byte inputs | −17 % |

| Slower | Instructions | Why |
| --- | --- | --- |
| `cc()` calls | +5 to +51 per call | Argument count and type checks,
and a check for `close()` (#37989, #38057, #43802, #44921). `dlopen()`
calls don't change |
| `process.env.X = v` | 38 → 593 per write | Writes aren't cached. Reads
don't change (#38871) |
| async `crypto.pbkdf2`, inputs of 1 KB or more | +4 to +9 % | Password
and salt are copied (#40554) |
| `bun build` with an object `--define` used thousands of times | +4.5 %
| The object is copied per use (#45969) |

#### Not included

- Fixes that need a WebKit change: #39967, #42534, #42982, #43764,
#43786, #44226. #42185 too: a typed array that has no `ArrayBuffer` yet
can't be pinned, so `view.buffer.transfer()` during an async call can
still free its bytes. Creating the `ArrayBuffer` up front costs 7 to 12
% on every async `fs` call, so the fix belongs in JSC: an `ArrayBuffer`
created while the view is borrowed should start out pinned.
- #45442 (`calc()` sums as a flat list): it changes minified output for
real stylesheets to survive a `calc()` with 25,000 terms. It deserves
its own review.
- #40023 (Windows event loop redesign), #29928 (Windows exit path),
#40534, #43963, #39571, #42904, #42834, #36355, #43266: refactors or
features whose crash is already covered or isn't a crash.
- The pull requests marked *(crash fix only)* below should stay open for
their other half.

### How did you verify your code works?

- **Tests.** Every fix has a test that fails on `main` (a release or an
ASAN build) and passes on this branch, except where that isn't
practical: code that only runs on Windows or macOS, inputs that need
several GB of memory, and a few rare races. Those were checked by hand
or by reading.
- **Stored repro scripts.** 230 crash repros ran on release and ASAN
builds of this branch and of `main`, side by side. Release: 88 no longer
crash. ASAN: 106 no longer crash. None crashes that didn't before. What
still crashes needs WebKit, is SQLite's own bug, or isn't a crash. The
ASAN number is from a later commit than the release number.
- **Dev server.** Because one fix makes requests wait, 2,171 generated
programs ran random interleavings of edits, build errors, failing
plugins, reloads, stops and disconnects with about 120,000 requests. No
request hung, was answered twice or got a stale body. `main` hung in 82
of 1,161 programs. This also found the four dev server bugs listed
above.
- **Path helpers.** 336,000 boundary cases with buffers of exactly the
computed size, and 12,003 random calls through 30 JS APIs on an ASAN
build, compared with `main`. No sanitizer report, and the results match
wherever `main` doesn't panic.
- **What worked on 1.4.3 still works.** Reviewers compared behavior with
1.4.3 and took out what changed it: for example an output directory
layout change for 9 or more entry points, a `server.reload()` change,
and a changed error message for `import("file:///50%deposit.ts")`.
- **Not run locally:** the Windows, macOS and FreeBSD code paths. CI
compiles and tests them.

### Included pull requests

**Bundler, transpiler, CSS, macros** (33)

- #33881 bundler: allocate wrapper_ref for CommonJS modules with no
non-hoistable statements
- #35055 Bun.build plugins: handle filter RegExp flags beyond i/m/v
- #37769 bundler: fail the build instead of panicking when the bundle
thread cannot create its waker
- #37784 bundler: copy inlined env values into the define arena, and
give each Bun.build its own env copy *(crash fix only)*
- #37858 bundler: fail the build instead of panicking when a plugin
answer string cannot be converted
- #38046 bun build --server-components: require the bun target and
reject directives without a framework *(crash fix only)*
- #38095 js_parser: fix panic on decorated declare/abstract fields in
class expressions with experimentalDecorators
- #38966 bundler: keep deep CSS, export star and composes graphs from
overflowing the linker's stack
- #38984 bundler: stop an export star ambiguity that loops back into a
re-export chain from overflowing the stack
- #39113 css: reject stylesheets of 2 GiB or more instead of aborting on
an int cast
- #39396 bundler: frame .jsc bytecode sidecars and verify them before
decoding
- #39855 bundler: join the work still on the pools before the bundle is
torn down *(crash fix only)*
- #41157 dev server: leave out an html link to a cached json module
instead of panicking, and mark a new placeholder file stale
- #41801 css: decode ill-formed UTF-8 to U+FFFD before tokenizing
*(crash fix only)*
- #41827 bundler: handle YAML and JSON5 keys that are not strings
instead of panicking
- #42242 js_parser: compress symbol link chains when following merged
declarations
- #42387 bundler: check receivers on the Bun.build plugin object and
freeze its filters during a build
- #42413 Bounds-check the InternalSourceMap window reader
- #42657 macros: keep visited values alive so a reused address does not
get another value's Expr
- #43330 transpiler: do not print an empty `var` for a data file with no
named export
- #43355 bundler: fix "The memory limit has been exceeded." on large
HTML entries
- #43658 react-compiler: fix skipped functions and build aborts for dead
code in a try body *(crash fix only)*
- #44137 js_parser: fix four crashes of exports.eliminate and
exports.replace
- #44467 js_parser: replace skipped expressions with E::Missing and skip
argument checks after a stack overflow
- #44662 js_parser: walk binary chains on the heap and check the stack
when rewriting decorated #private accesses
- #44712 json5: reject sources of 2 GiB or more before parsing instead
of aborting on an int cast
- #44864 js_parser: walk conditional chains in import()/require() and
define keys in a loop
- #44883 js_parser: reject a decorator on a class static block, keep
decorators out of the body of `declare global` *(crash fix only)*
- #45045 Fix a segfault in new Bun.Transpiler(): re-point options.log
after the constructor moves its Log
- #45604 css: keep a url() in an at-rule prelude as written, and never
print the resolved path of a url() *(crash fix only)*
- #45748 bundler: put --banner/--footer in the bytecode ESM module
record (flags from a parse, entries from JSC) *(crash fix only)*
- #45960 macros: give each parse-worker macro VM its own env loader
- #45969 js_parser: copy object and array defines per use, and copy the
list of a lone JSX spread object *(crash fix only)*

**`bun build --compile` and standalone executables** (3)

- #31787 Don't crash at startup when a standalone executable's embedded
graph is corrupted *(crash fix only)*
- #38251 compile: exit with an error instead of SIGBUS when a standalone
executable is truncated
- #41360 standalone: check every offset in the embedded module graph
before reading it

**Resolver, module loading, plugins, paths** (25)

- #32269 Bun.plugin: validate the namespace without a shared regex
- #33183 bun:jsc: filter internal cells out of getProtectedObjects()
- #34575 Don't register native functions as their own constructors
- #36340 paths: size the thread-local join output buffers to
MAX_PATH_BYTES on Windows
- #37037 mock.module: reject async factory results that are not objects
- #37065 bun:jsc: propagate JSONParse exceptions from
samplingProfilerStackTraces
- #37529 resolver: don't abort on a package.json sideEffects entry
longer than the join buffer
- #38179 node:module: throw instead of crashing when module._compile is
set to a non-function
- #38273 bun test: report a test file or preload the loader cannot
resolve instead of exiting; keep the JUnit report valid U… *(crash fix
only)*
- #38732 paths: compute the common path of 9+ inputs with the same loop
as fewer *(crash fix only)*
- #39228 paths: strip C:\\ down to the drive root in
without_trailing_slash_windows_path *(crash fix only)*
- #39650 bun run --filter: stop panicking on workspace paths longer than
the path buffer
- #40186 resolver: stop deeply nested exports targets from overflowing
the stack
- #40258 resolver: publish Entry.abs_path through the per-entry mutex
- #42183 node:module: reject a _resolveFilename override result that
contains a null byte
- #42401 node:module: accept any `this` in Module.prototype.require
*(crash fix only)*
- #42405 Bun.plugin: transpile a copy of typed array onLoad contents
- #42414 node:module: end the Module._stat path at the first null byte
- #42685 resolver: strip the trailing separator inside bust_dir_cache
- #42735 Throw a RangeError instead of aborting when require.resolve
paths or Worker preload outgrows its Vector
- #43067 Report a path that does not fit a path buffer instead of
aborting *(crash fix only)*
- #44410 Fix a crash when code from a node:vm context reads
require.cache or require.extensions
- #44466 Trace the value an object or data module exports from its
JSSourceCode
- #45044 Bun.plugin: give onLoad's args.path its own bytes
- #45117 cjs: do not call an `__esModule` getter during the annotation
lookup

**Dev server, `bun bake`, routers, `--watch` and `--hot`** (28)

- #28793 Stop file watcher thread before Global.exit tears down memory
*(crash fix only)*
- #32143 bake: fix "Runtime file not found" panic in production builds
of custom frameworks
- #32443 watcher: don't free the Watcher in the spawn-to-start window
*(crash fix only)*
- #33232 bake: normalize the HTTP request-target before matching
framework routes
- #36812 bake: respond 500 and release both RequestContext refs when
on_plugins_rejected / OOM drains a deferred framework r…
- #37039 bake: report per-file print failures in the dev server instead
of serving empty modules
- #37276 hot_reloader: take entries_mutex for watcher-thread directory
cache probes
- #37444 bake: unregister Bake::SourceProvider from the source map table
when it is destroyed
- #39290 FileSystemRouter: match / against a root-level optional
catch-all route *(crash fix only)*
- #39291 FileSystemRouter: order dynamic routes by per-segment
precedence like Next.js *(crash fix only)*
- #39629 watch: report a failed watcher init as an error instead of a
crash
- #41185 bake: check for exceptions in the production build's module
loader hooks and helpers
- #41340 bake: skip the directory watch when the directory cannot be
opened
- #41617 Decide a directory watch event from the watchlist, not from the
resolver's cached listing *(crash fix only)*
- #42547 bake: re-arm the memory visualizer timer when it fires
- #42733 dev server: make a client script request wait for the bundle in
flight
- #42828 bake: serve routes from a router root outside the project root
instead of aborting or answering 404
- #42831 bake: resolve app.root and router roots through one checked
join
- #42836 bake: report route scan errors instead of aborting, and fail
bun build --app on them *(crash fix only)*
- #42840 dev server: map a router type's server entry point to the root
route of that type
- #42862 Bun.serve: return before a pending app.plugins setup() settles
*(crash fix only)*
- #42920 Do not create a mimalloc heap per FileSystemRouter, reload() or
:nth-child(An-B) selector
- #42934 dev server: register a client component without evaluating it
- #43329 dev server: check the route bundle index of a client script URL
before Index::init
- #44249 fs.watch: read each directory and close it before descending
- #44344 Windows: fix a watcher panic and lost events in a burst of file
changes, and a --hot that stops watching a deleted…
- #44744 dev server: answer a cached-file lookup only for a graph that
bundled the file
- #44746 dev server: keep an importer in its own graph when an import
fails or is deleted

**`Bun.serve`, sockets, HTTP, WebSocket, HTTP/2, QUIC, DNS** (28)

- #42667 Reland "usockets(windows): keep a closed poll alive until the
outer tick and libuv are done with it" (#39643)
- #33015 fix(windows): segfault in uv__wake_all_loops after system
resume *(crash fix only)*
- #35761 node:quic: detach lsquic ctx pointers before the finalize-order
sweep at worker VM teardown
- #37082 Bun.serve: terminate FIFO/pipe file responses at EOF
- #38024 dns: keep the c-ares uv_poll_t alive while its poll callback is
on the stack (Windows)
- #38636 serve: fix route use-after-free after reload() with
tls.serverName *(crash fix only)*
- #40888 server.fetch: copy a Headers argument instead of adopting the
wrapper's pointer
- #41337 Update lsquic to 4.9.4 and free unsent stateless resets on
destroy *(crash fix only)*
- #41384 usockets: hold a tick level for the whole of close_all
- #41412 Windows: wait for close completions when closing a worker's uv
loop
- #41516 node:http2: handle an empty byte range in respondWithFile and
respondWithFD
- #41521 udp: report every binaryType from the getter, reject a dgram
bind of the other family *(crash fix only)*
- #42188 net: do not assert a two-character host in SocketAddress.parse
- #42210 libuv(windows): keep a pipe's completed read counted until its
read callback returns
- #42334 fetch, Bun.serve: throw a RangeError for Headers that total 4
GiB or more *(crash fix only)*
- #43738 usockets: close a socket whose resume the kernel refuses from
the loop, not from the caller
- #44338 node:http: response trailers travel with the end call of the
response *(crash fix only)*
- #44433 bake: make the parked-request list non-owning and look up the
DevServer when a plugin load settles
- #44533 node:quic: capture the handshake while the conn is alive, set
the application at session creation
- #44734 Bun.serve: answer HEAD for an S3-backed Blob body without an S3
stat
- #44751 node:quic: close() waits only for opened streams, and lsquic
sends no GOAWAY before HTTP/3 starts *(crash fix only)*
- #44897 node:http2: throw instead of panic when the native
setNextStreamID() misses its argument
- #45076 node:http2: let close() and destroy() win over the refusal of a
request
- #45341 uws: AsyncSocket::write takes a size_t length, so res.end()
sends a body of 2 GiB or more whole
- #45522 node:http2: throw for an ALTSVC frame that is too long and for
a pushPromise id that is not a stream id
- #45676 node:quic: do not reset a stream lsquic has already finished
- #45822 node:quic: name a stream in queued session events by a
per-session key, not by its address
- #45858 Bun.serve WebSocket: a message that does not fit in memory
fails one connection, not the server *(crash fix only)*

**Streams, Blob, S3, files, `node:fs`** (28)

- #33845 io: propagate IoRequestLoop init failure instead of aborting
*(crash fix only)*
- #36365 prompt: drop debug_assert that rejects answers containing CR
- #37090 Deliver FIFO bodies whose writer connects after the reader
opens *(crash fix only)*
- #38039 node:fs: stop fs.copyFile(src, "") from segfaulting on Windows
- #38653 shell(cp): reject copying a directory into itself; walk cp
trees without recursion
- #39207 Convert scope-object receivers in the chaining functions and
inspect.custom fallbacks
- #39390 Blob deserialize: reject over-long paths, treat size >=
MAX_SIZE as unknown, make slice() non-panicking
- #39639 fetch: drop the upload and drain hop refs at VM teardown
*(crash fix only)*
- #40008 inspect hooks: copy user options with putDirectMayBeIndex
*(crash fix only)*
- #40462 Windows: FileSink.start({ path }) on a live writer: hand the
writer a libuv fd and close the old source *(crash fix only)*
- #41440 node:fs: pass the buffer to the read/readv/write/writev
callback on error
- #41584 Walk the timer pairing heap without recursion
- #41608 native-readable: accept a stream with no native handle
- #41710 JSSink write(): convert the chunk before resolving the native
sink *(crash fix only)*
- #42711 webstreams: bound the native recursion through a chain of tees
or text streams
- #43264 fetch: reject a file: URL whose path has an encoded NUL
- #43709 s3: fix double free of a multipart part's bytes on worker
terminate
- #43950 streams: link readers and writers last, reject their promises
as handled
- #44036 PipeReader: label a chunk Eof only when the reader is at its
end
- #44181 streams: throw instead of aborting when a direct stream's text
sink cannot take a string chunk
- #44195 fs: validate POSIX directory records in one parser, report a
malformed record as EIO *(crash fix only)*
- #44269 streams: join the string chunks of a text consumer with one
allocation
- #44490 watch(windows): report a failed child spawn as an error instead
of a panic *(crash fix only)*
- #44954 process.stdout/stderr with no FileSink: write synchronously,
reset after a failed write *(crash fix only)*
- #45004 streams: leave a stream alone when a consumer fails to lock it
- #45521 FileSink: throw ERR_ILLEGAL_CONSTRUCTOR from the constructor
that script reaches by writer.constructor
- #45738 s3: own the Blob store across the calls that run user JS
- #45975 node:stream: do not touch the web controller after the web side
is done

**Node-API, V8 API, `bun:ffi`, `process.dlopen`** (15)

- #36609 napi: implement uv_cwd on POSIX
- #37989 bun:ffi: stop cc() from turning non-numeric pointer arguments
into garbage pointers
- #38057 bun:ffi: make cc() reject non-numeric i64/u64 arguments instead
of passing garbage
- #38425 bun:ffi: throw on an empty cc() source array instead of
panicking
- #39652 napi: implement uv_async_t, uv_queue_work and uv_default_loop
on posix
- #39805 Share one handle scope implementation between Node-API and the
V8 API
- #39892 napi: implement uv_idle_t, uv_prepare_t, uv_check_t and
uv_timer_t on posix
- #40144 bun:ffi: return undefined for a NULL napi_value from cc() and
throw the scheduled napi exception
- #40773 bun:ffi: add the full byteOffset in read.*, do not truncate it
to int32
- #41704 napi: hand the thrown value to
napi_get_and_clear_last_exception after napi_run_script
- #42960 process.dlopen: run a V8 addon's init function after dlopen()
returns
- #43797 Fix debug assertion on an empty error message from a V8 addon
or SQLite *(crash fix only)*
- #43802 bun:ffi: throw a TypeError when a cc() symbol is called after
its library's close()
- #43940 napi: fail with ERR_BUFFER_TOO_LARGE instead of aborting above
the ArrayBuffer limit *(crash fix only)*
- #44921 bun:ffi: pad a short call to a cc() symbol with undefined

**`node:vm`, workers, process, timers** (19)

- #34623 node:vm: run DONT_CONTEXTIFY contexts directly against the real
global
- #32839 node:vm: reject invalid cachedData instead of crashing
- #36921 error printer: clear the pending exception when formatting a
non-Error uncaught value throws
- #37270 error printer: one render per error, [Circular] under the key
that closes the cycle
- #38740 bun:test: give each VM its own fake clock *(crash fix only)*
- #39864 Report a refused HTTP, bundle, IO or process waiter thread as
an error instead of a crash *(crash fix only)*
- #39992 process: deliver exceptions reported against a node:vm context
to uncaughtException
- #41654 node:vm: give each SourceTextModule request the import
attributes of the declaration that created it *(crash fix only)*
- #41739 Do not forward the inherited IPC channel to spawned scripts and
tools
- #41769 node:vm: stop compiling accepted cachedData, report each
cachedData decode to the GC *(crash fix only)*
- #42045 bun:test fake timers: never move the fake clock backwards
- #42308 process.execve: throw instead of aborting for a string past the
string limits
- #42734 node:vm: report cachedData of 2 GiB or more as rejected instead
of aborting
- #42843 process.dlopen: reject a filename of PATH_MAX or more before
dlopen()
- #43500 process: accept SIGSTKFLT, SIGPOLL and SIGPWR, and emit every
name of a signal number *(crash fix only)*
- #44486 worker: stop the start sequence when a handler it calls stops
the worker
- #44771 timers: allocate ids from one 64-bit counter that never wraps
- #44837 --hot: defer a reload during the preloads, and report a reload
that cannot start
- #44991 Fix a use-after-free in the VM ref-string intern for a string
over the length limit

**Shell, spawn, CLI, `bun test`, `bun install`** (31)

- #30642 Fail fast at startup when simdutf has no usable implementation
for this CPU
- #34223 Fix four crashes: HTMLRewriter disturbed body, S3 locked-stream
upload, ConnectionsList closed parser, shell brace… *(crash fix only)*
- #34884 Guard the console and test-runner formatters against native
stack overflow on deeply nested values *(crash fix only)*
- #36584 process.chdir: publish an immutable cwd slice so no thread sees
a torn cwd
- #37135 bun test --parallel: hold the JSC API lock while draining the
worker's final IPC backlog
- #37527 shell(mv): report ENAMETOOLONG instead of panicking when a
source name does not fit the path buffers
- #37528 cli: stop aborting on absolute script paths longer than 1024
bytes on Windows
- #38162 shell(cp): report ENAMETOOLONG instead of panicking on operands
longer than the path buffers
- #38205 shell(windows): report ENAMETOOLONG for operands that do not
fit the path buffer
- #39010 bun test: exit through the VM teardown path when --bail stops a
run
- #39104 bun test: report over-long coverage dir, JUnit outfile and
bunfig root instead of panicking *(crash fix only)*
- #39638 shell(cat): serve a second cat on the same stdin instead of
hanging or panicking
- #39641 usockets: report an out-of-descriptors event loop init as an
error, not a crash *(crash fix only)*
- #40181 shell: stop deeply nested if clauses from overflowing the
parser stack
- #40885 shell: throw instead of panicking when a ReadableStream is used
as a redirect
- #41155 ipc: send a queue item larger than 2 GiB in capped write
requests
- #42298 bun:test: print String objects with 16-bit storage correctly
- #42577 bun:test: root the return values toHaveReturnedWith collects
- #43606 shell(windows): report a failed pipe reader start through
on_reader_error instead of leaking the subprocess *(crash fix only)*
- #43838 node:cluster: read a worker's `ack` and `addressType` in the
primary only when they are int32
- #44172 node:cluster: refuse a descriptor of the wrong kind in the
primary *(crash fix only)*
- #44185 node:cluster: one handle for each descriptor that workers name
*(crash fix only)*
- #44491 bun test: run every callback when native code leaves an
exception pending *(crash fix only)*
- #44694 shell mv: refuse to copy a directory into itself on the
cross-device fallback
- #44752 shell: take the command-substitution capture and drop its NUL
bytes
- #44981 shell: reject NUL bytes in .cwd() and .env() at the native
setters
- #45206 ini: reject a source of 2 GiB or more in Parser::parse instead
of aborting on an int cast *(crash fix only)*
- #45348 bun test: fix a segfault in .not.toThrow(Class) when
Symbol.hasInstance accepts a thrown string, symbol or BigInt
- #45649 shell: replace the output counters in mkdir, cp, ls and touch
with the OutputTask queue
- #45792 bun test: SIGKILL a spawnSync child that is still running 500
ms after the test's timeout *(crash fix only)*
- #45910 create: own the remote-template response buffers instead of
parking them in the CLI arena

**Web APIs, Buffer, encoding, URL, crypto, zlib, SQLite, Redis and the
rest** (96)

- #29709 console: guard JSX/Proxy recursion in Bun.inspect (stack
overflow SIGSEGV)
- #30817 console.takeHeapSnapshot: clear prior snapshots before building
- #30956 spawnSync: make signal-forwarding register/unregister safe for
concurrent callers *(crash fix only)*
- #31505 node:zlib: reject invalid brotli flush values at validation
*(crash fix only)*
- #31735 node:path: fix win32 drive-relative resolve on non-Windows
hosts *(crash fix only)*
- #32085 Fix crash when RedisClient onclose/onconnect is set to a
non-callable
- #32240 Fix BroadcastChannel custom inspect crash with numeric option
keys
- #33181 Reject interior null bytes in Bun.mmap, Glob.scan, and
FileSystemRouter paths *(crash fix only)*
- #33752 node:crypto: validate EC JWK private scalar matches public
point in createPrivateKey
- #34976 spyOn: install and restore through one writer that throws when
the object refuses *(crash fix only)*
- #35562 structuredClone: purify NaN in deserialized Date timestamp so
getTime never returns a forged JSValue
- #35618 napi(windows): load addons that import node.exe without
win_delay_load_hook
- #35757 Coerce later arguments before capturing input buffers in
Bun.Transpiler and Bun.RedisClient
- #37252 Report UTF-16 to UTF-8 encode counts through size_t so exactly
2^32 written bytes doesn't wrap to 0
- #37338 node:module: build require.cache without user-writable globals
and propagate its exceptions *(crash fix only)*
- #37340 redis: accept unsubscribe acks that arrive outside subscriber
mode
- #37370 Error.appendStackTrace: make appending an error's trace to
itself a no-op
- #37443 node:crypto: fix null deref when worker.terminate() lands
during an EC JWK private key import
- #37448 jsc: check for exceptions before using a stored
constructEmptyArray result *(crash fix only)*
- #38009 MessagePort: fix a heap-use-after-free in contextDestroyed(),
release ref() when the last 'message' listener is rem… *(crash fix
only)*
- #38469 napi: settle or refuse async work queued during VM teardown
instead of taking a ticket
- #38708 Handle 16-bit module sources in the error preview, the
new-position fix-up and the REPL *(crash fix only)*
- #38821 process.env: make a failed env build throw instead of aborting
(Windows 0xC0000409 on Bun.$ / Bun.sql / process.env…
- #38871 process.env: coerce to string on every execution of an
assignment, not just the first
- #38877 cli: exit 128 + signo when bun cannot die from a re-raised
signal (bun as container PID 1)
- #38926 Clear the inherited signal mask at startup and exec children
with an empty one *(crash fix only)*
- #39382 Make a failed util.inspect load throw from custom inspect
functions instead of aborting
- #39481 Always create the error when a native error message exceeds the
string length limit
- #39651 performance: keep the user timing entry counts exact after
clearMarks(name) and clearMeasures(name)
- #39775 Turn seccomp SIGSYS traps into ENOSYS so the syscall fallbacks
run on Android
- #39968 process.dlopen: replay a non-context-aware V8 addon only while
no other live VM owns it
- #39975 watch: report a failed reload exec as an error instead of a
panic *(crash fix only)*
- #40346 Give Glob's native scan methods their own private names
- #40554 node:crypto: copy password and salt for async pbkdf2 and scrypt
- #40567 url: reject URL-encoded input over the WTF decode limit instead
of aborting
- #40577 url: throw a RangeError instead of aborting when
URLSearchParams or FormData outgrows its Vector
- #41073 Store array-index property names as indexed properties in
native object builders
- #41137 Write the sampling profiler report at exit from Bun, not JSC's
atexit hook
- #41365 webview: fail only the view when WebKit lacks
initWithDirectory:
- #41574 Decode a private copy of a JS buffer in the UTF-8 decoders
*(crash fix only)*
- #41652 console: read a BigInt depth option by value in console.dir
- #41749 Startup: reopen fd 0-2 as /dev/null only when the fd is closed
- #41819 Report an incoherent BUN_JSC_* option combination as a
configuration error, not a crash *(crash fix only)*
- #42158 webview: reject malformed Chrome replies instead of crashing
- #42179 shell: clamp a `> ${buf}` redirect to the target buffer's live
length
- #42187 node:crypto: throw ERR_OUT_OF_RANGE for >2 GiB buffer arguments
instead of aborting
- #42191 URLPattern: throw instead of aborting when a pattern string
passes the string limit
- #42192 Copy WebAssembly.Memory bytes for native borrows that outlive
the call *(crash fix only)*
- #42198 Make Bun.$, Bun.sql, Bun.postgres and Bun.SQL custom value
getters so reifying the Bun object passes exception chec…
- #42203 node:fs: fs.read into a WebAssembly.Memory view writes into the
block a grow freed
- #42214 Headers: throw a RangeError instead of aborting when the
set-cookie list cannot grow
- #42218 Headers: throw instead of aborting when a value passes the
string length limit
- #42220 URLPattern: throw instead of aborting when the token list
cannot grow
- #42225 Throw ERR_STRING_TOO_LONG from Bun.wrapAnsi instead of aborting
when the output passes the string length limit
- #42226 Throw instead of aborting when a MIME string does not fit in a
string *(crash fix only)*
- #42237 Bun.Cookie: throw instead of aborting when the Set-Cookie
string passes the string length limit
- #42249 Copy a shared input before libdeflate compresses it in
Bun.gzipSync and Bun.deflateSync
- #42253 bun test: walk nested describe scopes without native recursion
- #42259 Throw instead of aborting when a domainToASCII host passes the
string length limit
- #42310 Parse a private copy of a shared or resizable buffer in
Bun.Transpiler, Bun.markdown, Bun.YAML and Bun.TOML *(crash fix only)*
- #42312 YAML, JSON5, XML stringify: throw instead of aborting when the
output passes the string length limit
- #42318 Bound libdeflate's emit path so a racing input cannot overrun
the output
- #42338 inspector: check the type of process.argv in getModuleGraph
- #42364 node:perf_hooks: do not truncate the monitorEventLoopDelay
resolution to int32
- #42412 transpiler cache: reject an entry with no sourcemap section
- #42479 worker_threads: do not abort when
markAsUntransferable/markAsUncloneable gets a WebAssembly GC reference
- #42517 EventTarget: skip a listener object that has no realm
- #42518 fs.Stats: make the date accessors define the property like
Object.defineProperty *(crash fix only)*
- #42575 Stop natives from writing onto a foreign `this` with putDirect:
process.ppid, require.cache, StringDecoder, the nat… *(crash fix only)*
- #42631 JSStringView: pin the cell that owns the borrowed characters
- #42660 bun_core: read /dev/urandom when getrandom(2) answers ENOSYS or
EPERM
- #42780 node:crypto: treat a name too long to convert to UTF-8 as
unknown instead of aborting
- #42782 node:crypto: throw ERR_OUT_OF_RANGE for a passphrase larger
than INT_MAX bytes
- #42856 url: do not abort when a host is too long for the IDNA
conversion buffers
- #42868 sqlite, console, process: do not abort on a string too long to
convert to UTF-8 *(crash fix only)*
- #42941 Bun.sliceAnsi: throw instead of aborting when the result passes
the string length limit
- #43058 Bun.serve: fix crash and cross-request 500 when inspecting a
non-Response return value throws
- #43904 JSC bindings: build property keys from a BunString through
Bun::toIdentifier
- #44124 Bun.Image: decode WebP into a Bun-owned canvas and read ICCP
without the demuxer *(crash fix only)*
- #44190 Convert scope-object receivers before Buffer read*/write* and
vm.Script describe them
- #44211 Stop getsockname(out), useFakeTimers() and the stream source
pull() from writing onto a caller's object with putDirect
- #44295 bun test --coverage: append a final newline to a text that
lacks one *(crash fix only)*
- #44360 rust-argon2: return OutOfMemory instead of aborting when the
memory cost cannot be allocated
- #44421 node:zlib: free zstd's workers before the dictionary they read
- #44521 util.parseArgs: pick the default args start from a per-VM eval
flag, as Node v26 does *(crash fix only)*
- #44740 structured clone: tolerate a zero-sized shared
WebAssembly.Memory in computeMemoryCost()
- #44759 HTMLRewriter: park a suspended handler's token before the
output flush
- #44907 Builtins section format 2: an engine stamp says which buns
compile its modules
- #45188 Reject an oversized WebCrypto cipher output instead of aborting
- #45354 Throw for a `file:` URL whose path is not UTF-8 on Linux and
macOS, through one `fileSystemPath()` accessor *(crash fix only)*
- #45608 ipc: refuse an over-long message before the receive buffer
stores it
- #45624 webcrypto: write the key type into the X25519 structured-clone
record
- #45625 node:sqlite: refuse session.close() and Symbol.dispose inside a
SQLite callback
- #45653 glob: a group with `?` or a class matches when an alternative
takes 64 bytes or more
- #45820 Bun.file, S3Client.file and Bun.write no longer keep a buffer
path alive forever
- #45832 `bun check`: fix a panic on `export *` without a module
specifier, and a false error for one in parentheses

### Already fixed on `main`, or duplicates of a pull request above

Already fixed: #27323 #30401 #31011 #31206 #31566 #31626 #31695 #31702
#31945 #32773 #34154 #34697 #34744 #34964 #35655 #35816 #36020 #36181
#36296 #36342 #36581 #36602 #36807 #36818 #36857 #37172 #37235 #37239
#37267 #37420 #37731 #37914 #38113 #38119 #38509 #38514 #38540 #38975
#39410 #40749 #41163 #41171 #42108 #43085 #43230

Duplicates: #45654 #29986 #33378 #36895 #37070 #37639 #38014 #39021
#41266 #42250 #42951 #43238 #44259 #45335 #45565 #45726 #45965

Fixes #5019
Fixes #6106
Fixes #10690
Fixes #10886
Fixes #13566
Fixes #14745
Fixes #15551
Fixes #20454
Fixes #21310
Fixes #29145
Fixes #30454
Fixes #30613
Fixes #30766
Fixes #32103
Fixes #32142
Fixes #32183
Fixes #32212
Fixes #39060
Fixes #42296
Fixes #42931
Fixes #43671
Fixes #44201
Fixes #44735
Fixes #44783
Fixes #45198
Fixes #45327
Fixes #45491
Fixes #45721

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
@Jarred-Sumner

Copy link
Copy Markdown
Collaborator

This is Claude (an AI assistant) commenting on Jarred's behalf.

This fix went in with #46021, which is merged. Closing.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants