From ca01a71e498b2bd069b347efae11a0e10030c6e6 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 28 Aug 2026 10:53:46 +0000 Subject: [PATCH 1/8] macros: fail the build on process.exit, Error returns, sparse arrays, and promises that never settle A macro produces a value for one call site. Each way it could instead take down the process that runs the build, leave bad output, or stall the build is now a located build error: - process.exit(), process.reallyExit() and process.abort() threw nothing and exited the process, including the program that called Bun.build(). In macro mode they throw a TypeError. - A returned Error was printed and the call was left in the output with its import removed: an unbound reference at runtime. It fails the expansion like a throw does. - A thrown exception surfaced as the engine's Exception cell and was reported as "cannot coerce Exception (JSType(0)) to Bun's AST". It is reported with its message and stack, and a throw while the return value is converted (a getter) is reported the same way. - A sparse array ([,,1] with length = 1e9, a[2**32 - 2] = 1, an arguments object with its length overwritten) was expanded index by index into undefined elements until the process ran out of memory. An array is accepted only when JSC backs its length with storage; otherwise the error names the length and the element count. - A promise that can never settle (new Promise(() => {}), a macro module whose top-level await never resolves) spun the parse forever at 100% CPU. The wait now gives up when nothing keeps the event loop alive, the condition under which a program would have exited with the promise unsettled. JSC's deferred work tickets count as pending so an Atomics.waitAsync timeout still resolves. Co-authored-by: Dylan Conway --- src/js_parser_jsc/Macro.rs | 106 +++++++++++-- src/js_parser_jsc/error.rs | 4 + src/jsc/JSValue.rs | 23 +++ src/jsc/VM.rs | 9 ++ src/jsc/VirtualMachine.rs | 54 +++++-- src/jsc/bindings/BunProcess.cpp | 22 +++ src/jsc/bindings/JSCTaskScheduler.cpp | 10 ++ src/jsc/bindings/bindings.cpp | 67 ++++++++ src/jsc/event_loop.rs | 42 +++++ src/jsc/lib.rs | 3 +- test/bundler/transpiler/macro-test.test.ts | 174 +++++++++++++++++++++ 11 files changed, 481 insertions(+), 33 deletions(-) diff --git a/src/js_parser_jsc/Macro.rs b/src/js_parser_jsc/Macro.rs index 049a6171541e..76ad9c892c13 100644 --- a/src/js_parser_jsc/Macro.rs +++ b/src/js_parser_jsc/Macro.rs @@ -188,6 +188,18 @@ impl MacroContext { hash, ) { Ok(m) => m, + Err(crate::Error::MacroLoadStalled) => { + *macro_entry.value_ptr = Macro::disabled_sentinel(); + log.add_range_error_fmt( + Some(source), + import_range, + format_args!( + "macro \"{}\" never finished loading: its top-level await is pending and nothing is keeping the event loop alive", + bstr::BStr::new(import_record_path) + ), + ); + return Err(crate::Error::MacroFailed); + } Err(e) => { *macro_entry.value_ptr = Macro::disabled_sentinel(); return Err(e); @@ -462,13 +474,21 @@ impl Macro { let unwrapped = unsafe { (*loaded_result).unwrap(&*(*vm).jsc_vm, jsc::PromiseUnwrapMode::LeaveUnhandled) }; - if let jsc::PromiseResult::Rejected(result) = unwrapped { - // SAFETY: `vm.global` is the live per-thread global; `loaded_result` - // is a live promise cell. - unsafe { - (*vm).unhandled_rejection(&*(*vm).global, result, (*loaded_result).to_js()); + match unwrapped { + jsc::PromiseResult::Rejected(result) => { + // SAFETY: `vm.global` is the live per-thread global; `loaded_result` + // is a live promise cell. + unsafe { + (*vm).unhandled_rejection(&*(*vm).global, result, (*loaded_result).to_js()); + } + return Err(crate::Error::MacroLoadError); } - return Err(crate::Error::MacroLoadError); + // The wait gave up: nothing keeps the loop alive for the module's + // top-level await (or the VM was stopped). A `Macro` returned here + // would have its first call find no registered function and leave + // the call in the output as an unbound reference. + jsc::PromiseResult::Pending => return Err(crate::Error::MacroLoadStalled), + jsc::PromiseResult::Fulfilled(_) => {} } Ok(Macro { @@ -559,11 +579,17 @@ impl<'a> Run<'a> { }; let global = vm.global(); - let result = vm.run_with_api_lock(|| { - macro_callback - .call(global, JSValue::ZERO, args) - .unwrap_or_else(|_| global.try_take_exception().unwrap_or_default()) - }); + let result = match vm.run_with_api_lock(|| macro_callback.call(global, JSValue::ZERO, args)) + { + Ok(result) => result, + // The macro threw: report it (with its stack) and fail this expansion. + Err(JsError::Thrown) => { + let err = global.take_exception(JsError::Thrown); + vm.as_mut().uncaught_exception(global, err, false); + return Err(MacroError::MacroFailed); + } + Err(e) => return Err(e.into()), + }; let mut runner = Run { caller, @@ -578,7 +604,17 @@ impl<'a> Run<'a> { // `runner.visited` dropped at scope exit (was `defer runner.visited.deinit(allocator)`) - runner.run(result) + match runner.run(result) { + // Converting the macro's return value threw (a getter, an iterator, a toString): report it the + // way a throw from the macro function itself is reported above, rather than leaving it pending + // under the parser. + Err(MacroError::Js(JsError::Thrown)) => { + let err = global.take_exception(JsError::Thrown); + vm.as_mut().uncaught_exception(global, err, false); + Err(MacroError::MacroFailed) + } + other => other, + } } pub(crate) fn run(&mut self, value: JSValue) -> Result { @@ -625,10 +661,13 @@ impl<'a> Run<'a> { use ConsoleObject::formatter::Tag as T; match tag { T::Error => { + // Report it the way a throw is reported, then fail the + // expansion. Returning `self.caller` here would leave the call + // in the output with its import gone: an unbound reference. // SAFETY: `vm()` is the per-thread VM; uniquely accessed here. let _ = unsafe { (*self.macro_.vm()).uncaught_exception(self.global, value, false) }; - return Ok(self.caller); + return Err(MacroError::MacroFailed); } T::Undefined => { if self.is_top_level { @@ -699,6 +738,24 @@ impl<'a> Run<'a> { let mut iter = JSArrayIterator::init(value, self.global)?; + // Every index up to `length` becomes an element of the literal, + // holes as `undefined`. Only a length the JS heap actually backs + // keeps that proportional: `[,,1]` with `length = 1e9` would + // otherwise become a billion `undefined`s. + if let Err(stored) = value.indexed_storage_covers(iter.len) { + self.log.add_error_fmt( + Some(self.source), + self.caller.loc, + format_args!( + "cannot coerce a sparse array to Bun's AST: its length is {} but it holds {} element{}. Please return a dense array", + iter.len, + stored, + if stored == 1 { "" } else { "s" }, + ), + ); + return Err(MacroError::MacroFailed); + } + // Process all array items let mut array = ExprNodeList::init_capacity(iter.len as usize); // (errdefer free deleted — drops on `?`) @@ -837,10 +894,25 @@ impl<'a> Run<'a> { let _ = self.macro_.vm(); let vm = VirtualMachine::get(); - // The VM stopped before the macro's promise settled: throw its termination and unwind. - vm.as_mut() - .wait_for_promise(promise) - .map_err(|stopped| MacroError::Js(stopped.throw(self.global)))?; + match vm.as_mut().wait_for_promise_until_idle(promise) { + Ok(()) => {} + // The VM stopped before the macro's promise settled: throw its termination and unwind. + Err(jsc::Unsettled::Stopped(stopped)) => { + return Err(MacroError::Js(stopped.throw(self.global))); + } + // Node's exit-13 condition, applied to the macro: nothing + // keeps the loop alive, so waiting on it would be a hang. + Err(jsc::Unsettled::Idle) => { + self.log.add_error_fmt( + Some(self.source), + self.caller.loc, + format_args!( + "macro returned a promise that never settles: no timer, I/O, or task is keeping the event loop alive" + ), + ); + return Err(MacroError::MacroFailed); + } + } let promise_result = promise.result(vm.jsc_vm()); let rejected = promise.status() == jsc::js_promise::Status::Rejected; diff --git a/src/js_parser_jsc/error.rs b/src/js_parser_jsc/error.rs index 9e95c384424e..d37a8775b322 100644 --- a/src/js_parser_jsc/error.rs +++ b/src/js_parser_jsc/error.rs @@ -6,6 +6,9 @@ pub enum Error { MacroNotFound, #[error("MacroLoadError")] MacroLoadError, + /// The macro module's top-level await has nothing left that could settle it. + #[error("MacroLoadStalled")] + MacroLoadStalled, #[error("MacroFailed")] MacroFailed, #[error("JSError")] @@ -31,6 +34,7 @@ impl Error { Self::ModuleNotFound => "ModuleNotFound", Self::MacroNotFound => "MacroNotFound", Self::MacroLoadError => "MacroLoadError", + Self::MacroLoadStalled => "MacroLoadStalled", Self::MacroFailed => "MacroFailed", Self::JSError => "JSError", Self::Alloc(_) => "OutOfMemory", diff --git a/src/jsc/JSValue.rs b/src/jsc/JSValue.rs index 7065857dd720..87922950926b 100644 --- a/src/jsc/JSValue.rs +++ b/src/jsc/JSValue.rs @@ -2557,6 +2557,29 @@ impl JSValue { index => Some(index as u32), } } + /// `Ok(())` when `self` (an object) holds storage for `length` indexed + /// slots, so iterating them yields at most as much as the JS heap already + /// holds: a dense array, holes included, or an arguments object of that + /// many arguments. `Err(stored)` when `length` runs past its storage, which + /// is a sparse array (`[,,1]` with `length = 1e9`, `a[2**32 - 2] = 1`) or an + /// array-like whose `length` property was written past its elements; + /// `stored` is the number of elements it does hold. + pub fn indexed_storage_covers(self, length: u32) -> Result<(), u32> { + debug_assert!(self.is_object()); + unsafe extern "C" { + safe fn Bun__JSObject__indexedStorageCovers( + this: JSValue, + length: u32, + out_stored_count: &mut u32, + ) -> bool; + } + let mut stored: u32 = 0; + if Bun__JSObject__indexedStorageCovers(self, length, &mut stored) { + Ok(()) + } else { + Err(stored) + } + } /// `JSValue.getNameProperty` — the value's `.name` (function/class /// name). Empty for empty/`undefined`/`null`. pub fn get_name_property(self, global: &JSGlobalObject) -> JsResult { diff --git a/src/jsc/VM.rs b/src/jsc/VM.rs index 092d29a0f87a..9d887a2c7d7d 100644 --- a/src/jsc/VM.rs +++ b/src/jsc/VM.rs @@ -37,6 +37,7 @@ unsafe extern "C" { safe fn JSC__VM__releaseWeakRefs(vm: &VM); safe fn JSC__VM__drainMicrotasks(vm: &VM); safe fn JSC__VM__blockBytesAllocated(vm: &VM) -> usize; + safe fn Bun__JSCTaskScheduler__hasPendingWork(vm: &VM) -> bool; } bun_opaque::opaque_ffi! { @@ -102,6 +103,14 @@ impl VM { JSC__VM__executionForbidden(self) } + /// JSC still holds deferred work it will post to this VM's loop later: an + /// `Atomics.waitAsync` timeout, a `FinalizationRegistry` callback, a wasm + /// compile. Only some of those keep the loop alive, so a promise waiting + /// on one can still settle with nothing else pending. + pub fn has_pending_deferred_work(&self) -> bool { + Bun__JSCTaskScheduler__hasPendingWork(self) + } + // These four functions fire VM traps. To understand what that means, see VMTraps.h for a giant explainer. // These may be called concurrently from another thread. diff --git a/src/jsc/VirtualMachine.rs b/src/jsc/VirtualMachine.rs index 6771425a2efb..b46a19cb885f 100644 --- a/src/jsc/VirtualMachine.rs +++ b/src/jsc/VirtualMachine.rs @@ -1295,20 +1295,33 @@ impl VirtualMachine { } } - pub fn is_event_loop_alive_excluding_immediates(&self) -> bool { + /// Something keeps the current loop alive: an active platform handle (a + /// socket, a ref'd timer, a keep-alive ref), a task in flight or queued, a + /// posting from another thread, or deferred work JSC holds for this VM. The + /// same question as [`Self::is_event_loop_alive`] minus whether the program + /// already failed, plus JSC's tickets that do not hold the loop open (an + /// `Atomics.waitAsync` timeout): what a wait on a pending promise asks + /// before it concludes that nothing will settle it. + pub fn has_pending_work(&self) -> bool { let el = self.event_loop_shared(); - let active = self - .platform_loop_opt() - .map(|h| h.is_active()) - .unwrap_or(false); - self.unhandled_error_counter == 0 - && ((active as usize) - + self.active_tasks - + el.tasks.readable_length() - + el.yield_tasks.len() - + (el.has_concurrent_tasks() as usize) - + (el.has_pending_refs() as usize) - > 0) + self.has_pending_work_excluding_immediates() + || !el.immediate_tasks.is_empty() + || !el.next_immediate_tasks.is_empty() + || self.jsc_vm().has_pending_deferred_work() + } + + fn has_pending_work_excluding_immediates(&self) -> bool { + let el = self.event_loop_shared(); + self.platform_loop_opt().is_some_and(|h| h.is_active()) + || self.active_tasks > 0 + || el.tasks.readable_length() > 0 + || !el.yield_tasks.is_empty() + || el.has_concurrent_tasks() + || el.has_pending_refs() + } + + pub fn is_event_loop_alive_excluding_immediates(&self) -> bool { + self.unhandled_error_counter == 0 && self.has_pending_work_excluding_immediates() } pub fn is_event_loop_alive(&self) -> bool { @@ -2776,6 +2789,15 @@ impl VirtualMachine { self.event_loop_mut().wait_for_promise(promise) } + /// Forwarder for [`crate::event_loop::EventLoop::wait_for_promise_until_idle`]. + #[inline] + pub fn wait_for_promise_until_idle( + &mut self, + promise: jsc::AnyPromise, + ) -> Result<(), jsc::Unsettled> { + self.event_loop_mut().wait_for_promise_until_idle(promise) + } + /// `eventLoop().autoTick()` — dispatched through the runtime hook /// (needs `Timer::All` for the poll timeout). #[inline] @@ -5202,7 +5224,9 @@ impl VirtualMachine { } } - /// Loads and evaluates a macro entry module, waiting for its promise. + /// Loads and evaluates a macro entry module, waiting for its promise. The + /// promise is still pending on return when the module's top-level `await` + /// can never settle (nothing left on the loop) or the VM was stopped. #[inline] pub(crate) fn _load_macro_entry_point( &mut self, @@ -5212,7 +5236,7 @@ impl VirtualMachine { let promise = jsc::JSModuleLoader::load_and_evaluate_module_ptr(self.global, Some(&path_str))? .as_ptr(); - let _ = self.wait_for_promise(jsc::AnyPromise::Internal(promise)); + let _ = self.wait_for_promise_until_idle(jsc::AnyPromise::Internal(promise)); Some(promise) } diff --git a/src/jsc/bindings/BunProcess.cpp b/src/jsc/bindings/BunProcess.cpp index 6af7db3ec00f..f8744effcf2e 100644 --- a/src/jsc/bindings/BunProcess.cpp +++ b/src/jsc/bindings/BunProcess.cpp @@ -857,11 +857,23 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionUptime, (JSC::JSGlobalObject * lexicalG return JSC::JSValue::encode(JSC::jsNumber(result)); } +// A macro runs in the VM of whichever thread is transpiling: a bundler worker, +// or the program's own main thread mid-`require()`. Exiting from inside one +// would take down the build, or the program that is only importing the file. +static bool isRunningMacro(Zig::GlobalObject* globalObject) +{ + return Bun__VM__currentLoopKind(globalObject->bunVM()) == BunLoopKind::Macro; +} + JSC_DEFINE_HOST_FUNCTION(Process_functionExit, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame)) { auto& vm = JSC::getVM(globalObject); auto throwScope = DECLARE_THROW_SCOPE(vm); auto* zigGlobal = defaultGlobalObject(globalObject); + if (isRunningMacro(zigGlobal)) [[unlikely]] { + throwTypeError(globalObject, throwScope, "process.exit() cannot be called from a macro"_s); + return {}; + } auto process = zigGlobal->processObject(); auto code = callFrame->argument(0); @@ -1823,6 +1835,12 @@ static void restoreDefaultSignalDisposition(int signalNumber) JSC_DEFINE_HOST_FUNCTION(Process_functionAbort, (JSGlobalObject * globalObject, CallFrame*)) { + if (isRunningMacro(defaultGlobalObject(globalObject))) [[unlikely]] { + auto& vm = JSC::getVM(globalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + throwTypeError(globalObject, throwScope, "process.abort() cannot be called from a macro"_s); + return {}; + } #if OS(WINDOWS) // Raising SIGABRT is handled in the CRT in windows, calling _exit() with ambiguous code "3" by default. // This adjustment to the abort behavior gives a more sane exit code on abort, by calling _exit directly with code 134. @@ -3698,6 +3716,10 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionReallyExit, (JSGlobalObject * globalObj { auto& vm = JSC::getVM(globalObject); auto throwScope = DECLARE_THROW_SCOPE(vm); + if (isRunningMacro(defaultGlobalObject(globalObject))) [[unlikely]] { + throwTypeError(globalObject, throwScope, "process.exit() cannot be called from a macro"_s); + return {}; + } uint8_t exitCode = 0; JSValue arg0 = callFrame->argument(0); if (arg0.isAnyInt()) { diff --git a/src/jsc/bindings/JSCTaskScheduler.cpp b/src/jsc/bindings/JSCTaskScheduler.cpp index a81da91f3d71..a6922d74797d 100644 --- a/src/jsc/bindings/JSCTaskScheduler.cpp +++ b/src/jsc/bindings/JSCTaskScheduler.cpp @@ -157,4 +157,14 @@ extern "C" void Bun__deleteDeferredWorkTask(Bun::JSCDeferredWorkTask* job) delete job; } +// JSC still holds a ticket whose completion it will post to this VM later, +// whether or not that ticket keeps the event loop alive (an Atomics.waitAsync +// timeout does not). A wait that gives up on an idle loop asks this first. +extern "C" bool Bun__JSCTaskScheduler__hasPendingWork(JSC::VM* vm) +{ + auto& scheduler = WebCore::clientData(*vm)->deferredWorkTimer; + Locker holder { scheduler.m_lock }; + return !scheduler.m_pendingTicketsKeepingEventLoopAlive.isEmpty() || !scheduler.m_pendingTicketsOther.isEmpty(); +} + } diff --git a/src/jsc/bindings/bindings.cpp b/src/jsc/bindings/bindings.cpp index 79428e514843..939e2b17c13e 100644 --- a/src/jsc/bindings/bindings.cpp +++ b/src/jsc/bindings/bindings.cpp @@ -38,6 +38,8 @@ #include "JavaScriptCore/BytecodeIndex.h" #include "JavaScriptCore/CodeBlock.h" #include "JavaScriptCore/Completion.h" +#include "JavaScriptCore/DirectArguments.h" +#include "JavaScriptCore/ScopedArguments.h" #include "JavaScriptCore/ErrorInstance.h" #include "JavaScriptCore/ExceptionHelpers.h" #include "JavaScriptCore/ExceptionScope.h" @@ -7246,6 +7248,71 @@ extern "C" uint64_t Bun__JSArray__nextPresentIndex( } } +// Whether `value` holds storage for `length` indexed slots. A dense array's +// butterfly backs every slot of its length (holes included), so whatever is +// built from its elements is proportional to the JS heap it already occupies. +// A sparse array is not: `[,,1]` with `length = 1e9` keeps one element in a +// vector of three and `a[2**32 - 2] = 1` keeps one in the sparse map, yet +// iterating `length` indices yields a billion `undefined`s. Arguments objects +// keep their elements off the butterfly and their `length` property can be +// written past them. When the storage falls short, `*outStoredCount` is the +// number of elements it does hold. +extern "C" bool Bun__JSObject__indexedStorageCovers( + JSC::EncodedJSValue encodedValue, + uint32_t length, + uint32_t* outStoredCount) +{ + JSC::JSValue value = JSC::JSValue::decode(encodedValue); + if (!value.isObject()) + return false; + JSC::JSObject* object = value.getObject(); + + switch (object->type()) { + case JSC::DirectArgumentsType: + *outStoredCount = uncheckedDowncast(object)->internalLength(); + return length <= *outStoredCount; + case JSC::ScopedArgumentsType: + *outStoredCount = uncheckedDowncast(object)->internalLength(); + return length <= *outStoredCount; + default: + break; + } + + switch (object->indexingType() & JSC::IndexingShapeMask) { + case JSC::UndecidedShape: + case JSC::Int32Shape: + case JSC::DoubleShape: + case JSC::ContiguousShape: + *outStoredCount = object->butterfly()->publicLength(); + return length <= *outStoredCount; + + case JSC::ArrayStorageShape: + case JSC::SlowPutArrayStorageShape: { + JSC::ArrayStorage* storage = object->butterfly()->arrayStorage(); + unsigned usedVectorLength = std::min(storage->length(), storage->vectorLength()); + // The vector backs its slots whether or not they are filled; only + // what lies past it (or lives in the map) is unbacked. + uint64_t backed = usedVectorLength; + uint64_t stored = 0; + for (unsigned i = 0; i < usedVectorLength; ++i) { + if (storage->m_vector[i]) + stored++; + } + if (JSC::SparseArrayValueMap* map = storage->m_sparseMap.get()) { + backed += map->size(); + stored += map->size(); + } + *outStoredCount = static_cast(std::min(stored, std::numeric_limits::max())); + return length <= backed; + } + + default: + // No indexed storage at all. + *outStoredCount = 0; + return length == 0; + } +} + extern "C" void JSC__ArrayBuffer__ref(JSC::ArrayBuffer* self) { self->ref(); } extern "C" void JSC__ArrayBuffer__deref(JSC::ArrayBuffer* self) { self->deref(); } extern "C" void JSC__ArrayBuffer__asBunArrayBuffer(JSC::ArrayBuffer* self, Bun__ArrayBuffer* out) diff --git a/src/jsc/event_loop.rs b/src/jsc/event_loop.rs index bbb01de0335c..791fbe9127bb 100644 --- a/src/jsc/event_loop.rs +++ b/src/jsc/event_loop.rs @@ -202,6 +202,17 @@ impl Stopped { } } +/// Why [`EventLoop::wait_for_promise_until_idle`] returned with its promise still pending. +#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)] +pub enum Unsettled { + #[error(transparent)] + Stopped(Stopped), + /// Nothing keeps the loop alive any more ([`VirtualMachine::has_pending_work`]): + /// the condition under which a program would have exited with it unsettled. + #[error("Idle")] + Idle, +} + // ────────────────────────────────────────────────────────────────────────── // §Dispatch hot-path — `tick_queue_with_count` is the per-tick dispatch over // `Task { tag, ptr }`. Per PORTING.md, the *high tier owns the match loop*: @@ -1120,6 +1131,37 @@ impl EventLoop { Ok(()) } + /// [`Self::wait_for_promise`], but gives up once nothing keeps the loop + /// alive ([`VirtualMachine::has_pending_work`]): where a program would have + /// exited with `promise` unsettled, this returns `Idle` with it pending. A + /// wait that has to finish (a macro, whose caller holds the parse) uses this + /// so such a promise is an error rather than a hang. + pub fn wait_for_promise_until_idle( + &mut self, + promise: jsc::AnyPromise, + ) -> Result<(), Unsettled> { + let jsc_vm = self.vm_ref().jsc_vm(); + while promise.status() == PromiseStatus::Pending { + if jsc_vm.execution_forbidden() + || !self.vm_ref().script_allowed() + || self.global_ref().has_pending_termination_exception() + { + return Err(Unsettled::Stopped(Stopped)); + } + self.tick(); + if promise.status() != PromiseStatus::Pending { + break; + } + // After the drain, so a reaction queued by the last task (or a + // handle it opened) counts. + if !self.vm_ref().has_pending_work() { + return Err(Unsettled::Idle); + } + self.auto_tick(); + } + Ok(()) + } + pub fn wakeup(&self) { if let Some(loop_) = self.uws_loop { // SAFETY: uws_loop is a valid live uws::Loop handle diff --git a/src/jsc/lib.rs b/src/jsc/lib.rs index 03faa8dec0e7..7cb57f4ecf84 100644 --- a/src/jsc/lib.rs +++ b/src/jsc/lib.rs @@ -1237,7 +1237,8 @@ pub mod job; pub use self::event_loop::{ AnyEventLoop, AnyTaskWithExtraContext, ConcurrentCppTask, ConcurrentTask, CppTask, DeferredTaskQueue, EventLoopHandle, EventLoopTask, GarbageCollectionController, ManagedTask, - MiniEventLoop, PosixSignalHandle, PosixSignalTask, Stopped, Task, WorkPool, WorkPoolTask, + MiniEventLoop, PosixSignalHandle, PosixSignalTask, Stopped, Task, Unsettled, WorkPool, + WorkPoolTask, }; pub use self::job::{Completion, Job, JobContext, JsPtr, JsThread, Protected}; #[cfg(unix)] diff --git a/test/bundler/transpiler/macro-test.test.ts b/test/bundler/transpiler/macro-test.test.ts index 9bfd7c294a2d..ad45446e91fc 100644 --- a/test/bundler/transpiler/macro-test.test.ts +++ b/test/bundler/transpiler/macro-test.test.ts @@ -381,6 +381,180 @@ describe("event loop routing around macros", () => { }); }); +// A macro produces a value for the file being bundled, nothing else: it cannot take the process down, +// every failure is a located build error, and what it returns has to fit in the output. +describe("a hostile macro", () => { + async function build(files: Record) { + using dir = tempDir("macro-hostile", { + ...files, + "index.ts": `import { m } from "./m.ts" with { type: "macro" };\nexport const v = m();\n`, + }); + await using proc = Bun.spawn({ + cmd: [bunExe(), "build", "index.ts"], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + // Each of these hung or exited the process before its fix. Bounded so a regression fails instead. + timeout: 20_000, + killSignal: "SIGKILL", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { + // Debug builds print "[macro] call " to stdout before the output. + stdout: stdout + .split("\n") + .filter(line => !line.startsWith("[macro]")) + .join("\n"), + stderr: stderr.replaceAll(String(dir), "[dir]"), + exitCode, + signalCode: proc.signalCode, + }; + } + + test.concurrent.each([ + ["process.exit()", `process.exit(42)`, "process.exit() cannot be called from a macro"], + ["process.reallyExit()", `process.reallyExit(42)`, "process.exit() cannot be called from a macro"], + ["process.abort()", `process.abort()`, "process.abort() cannot be called from a macro"], + ])("%s inside a macro fails the build instead of the process", async (_name, call, message) => { + const { stderr, exitCode, signalCode } = await build({ "m.ts": `export function m() { ${call}; }` }); + expect({ exitCode, signalCode, stderr }).toEqual({ + exitCode: 1, + signalCode: null, + stderr: expect.stringContaining(message), + }); + expect(stderr).toContain("error: macro threw exception"); + }); + + // Bun.build() runs macros on its bundler threads; the program that called it must outlive them. + test.concurrent("process.exit() inside a macro does not exit the Bun.build() caller", async () => { + using dir = tempDir("macro-hostile-api", { + "m.ts": `export function m() { process.exit(42); }`, + "user.ts": `import { m } from "./m.ts" with { type: "macro" };\nexport const v = m();\n`, + "build.ts": [ + `const result = await Bun.build({ entrypoints: ["./user.ts"], throw: false });`, + `console.log(JSON.stringify({ success: result.success, logs: result.logs.map(log => log.message) }));`, + ].join("\n"), + }); + await using proc = Bun.spawn({ + cmd: [bunExe(), "run", "build.ts"], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect({ lastLine: stdout.trim().split("\n").pop(), stderr, exitCode }).toEqual({ + lastLine: JSON.stringify({ success: false, logs: ["macro threw exception"] }), + stderr: expect.stringContaining("process.exit() cannot be called from a macro"), + exitCode: 0, + }); + }); + + // Before: the error was printed and the call was left in the output, with its import gone. + test.concurrent("returning an Error fails the build instead of leaving the call in the output", async () => { + const { stdout, stderr, exitCode } = await build({ + "m.ts": `export function m() { return new Error("returned, not thrown"); }`, + }); + expect({ exitCode, stdout, stderr }).toEqual({ + exitCode: 1, + stdout: "", + stderr: expect.stringContaining("error: returned, not thrown"), + }); + expect(stderr).toContain("error: macro threw exception"); + }); + + // Every index up to `length` becomes an element of the literal. JSC only backs a dense array's length + // with storage; a sparse one (length set past its elements, or an index in the sparse map) would + // inflate without bound: `[,,1]` with `length = 1e9` is a billion `undefined`s. + test.concurrent.each([ + [ + "length set past its elements", + `const a = [, , 1]; a.length = 200000; return a;`, + "its length is 200000 but it holds 1 element", + ], + [ + "an element in the sparse map", + `const a = []; a[150000] = 1; return a;`, + "its length is 150001 but it holds 1 element", + ], + [ + "an arguments object whose length was overwritten", + `return (function () { "use strict"; arguments.length = 200000; return arguments; })(4, 5);`, + "its length is 200000 but it holds 2 elements", + ], + ])("a sparse array (%s) is refused with a located error", async (_name, body, message) => { + const { stderr, exitCode } = await build({ "m.ts": `export function m() { ${body} }` }); + expect({ exitCode, stderr }).toEqual({ + exitCode: 1, + stderr: expect.stringContaining( + `error: cannot coerce a sparse array to Bun's AST: ${message}. Please return a dense array`, + ), + }); + expect(stderr).toContain("at [dir]/index.ts:2:18"); + }); + + test.concurrent("dense arrays with holes, arguments objects, and doubles are still inlined", async () => { + const { stdout, stderr, exitCode } = await build({ + "m.ts": [ + `export function m() {`, + ` return [[1, , 3], new Array(3), (function () { return arguments; })(4, 5), [1.5, , 2.5], new Array(200000).fill(7).length];`, + `}`, + ].join("\n"), + }); + expect({ stderr, exitCode }).toEqual({ stderr: "", exitCode: 0 }); + expect(stdout.replace(/\s+/g, "")).toContain( + "varv=[[1,undefined,3],[undefined,undefined,undefined],[4,5],[1.5,undefined,2.5],200000];", + ); + }); + + // Before: the parse spun on the promise forever (100% CPU). A program in the same state, a pending await + // with nothing keeping the event loop alive, would have exited; the macro fails the same way. + test.concurrent("a returned promise that can never settle is a located error", async () => { + const { stderr, exitCode, signalCode } = await build({ + "m.ts": `export function m() { return new Promise(() => {}); }`, + }); + expect({ exitCode, signalCode, stderr }).toEqual({ + exitCode: 1, + signalCode: null, + stderr: expect.stringContaining( + "error: macro returned a promise that never settles: no timer, I/O, or task is keeping the event loop alive", + ), + }); + expect(stderr).toContain("at [dir]/index.ts:2:18"); + }); + + test.concurrent("a macro module whose top-level await can never settle is a located error", async () => { + const { stderr, exitCode, signalCode } = await build({ + "m.ts": `await new Promise(() => {});\nexport function m() { return 1; }`, + }); + expect({ exitCode, signalCode, stderr }).toEqual({ + exitCode: 1, + signalCode: null, + stderr: expect.stringContaining( + `error: macro "./m.ts" never finished loading: its top-level await is pending and nothing is keeping the event loop alive`, + ), + }); + expect(stderr).toContain("at [dir]/index.ts:1:19"); + }); + + // Promises that do settle keep working, including ones nothing on the loop holds open for: JSC posts + // an Atomics.waitAsync timeout itself, and it does not keep the event loop alive. + test.concurrent("a returned promise that will settle is awaited", async () => { + const { stdout, stderr, exitCode } = await build({ + "m.ts": [ + `export async function m() {`, + ` const { value } = Atomics.waitAsync(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);`, + ` await new Promise(resolve => setTimeout(resolve, 10));`, + ` return [await value, await Bun.file(import.meta.path).text().then(text => text.length > 0)];`, + `}`, + ].join("\n"), + }); + expect({ stderr, exitCode }).toEqual({ stderr: "", exitCode: 0 }); + expect(stdout.replace(/\s+/g, "")).toContain(`varv=["timed-out",true];`); + }); +}); + describe("--no-macros", () => { const files = { "macro.ts": ` From ec34aa4d6fccd6a4cb0d7ecd5d6b9d0a90f9854a Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 28 Aug 2026 11:14:53 +0000 Subject: [PATCH 2/8] macros: keep LeakSanitizer off the source map table, compare paths with forward slashes in the test An error printed from inside a macro is remapped through SavedSourceMap, whose table owns the ParsedSourceMap through a tagged pointer LeakSanitizer cannot follow. The ASAN lane reported that entry as a leak at exit and aborted the build with code 134. Tell LSan the table owns it. On Windows the error location is printed with backslashes; the test normalizes them before comparing. Co-authored-by: Dylan Conway --- src/bun_core/lib.rs | 10 ++++++++++ src/jsc/SavedSourceMap.rs | 4 ++++ test/bundler/transpiler/macro-test.test.ts | 2 +- 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/bun_core/lib.rs b/src/bun_core/lib.rs index c5b8d48c6220..6b1127794283 100644 --- a/src/bun_core/lib.rs +++ b/src/bun_core/lib.rs @@ -2841,6 +2841,7 @@ pub mod asan { safe fn __asan_describe_address(ptr: *const c_void); safe fn __lsan_register_root_region(ptr: *const c_void, size: usize); safe fn __lsan_unregister_root_region(ptr: *const c_void, size: usize); + safe fn __lsan_ignore_object(ptr: *const c_void); } #[inline] @@ -2886,6 +2887,15 @@ pub mod asan { #[cfg(not(bun_asan))] let _ = (ptr, size); } + /// The heap allocation containing `ptr` is owned through a reference LeakSanitizer cannot follow (e.g. a + /// tagged pointer); do not report it. Its owner is still responsible for freeing it. + #[inline] + pub fn lsan_ignore_object(ptr: *const c_void) { + #[cfg(bun_asan)] + __lsan_ignore_object(ptr); + #[cfg(not(bun_asan))] + let _ = ptr; + } } // ──────────────────────────────────────────────────────────────────────────── diff --git a/src/jsc/SavedSourceMap.rs b/src/jsc/SavedSourceMap.rs index 7edf2e3ad7d0..1feedf15e772 100644 --- a/src/jsc/SavedSourceMap.rs +++ b/src/jsc/SavedSourceMap.rs @@ -231,6 +231,8 @@ impl SavedSourceMap { pub(crate) fn put_value(&mut self, path: &[u8], value: Value) -> bun_js_printer::Result<()> { use bun_collections::zig_hash_map::MapEntry as Entry; + // The table owns `value`'s allocation through a tagged pointer, which LeakSanitizer cannot follow. + bun_core::asan::lsan_ignore_object(value.as_uintptr() as usize as *const c_void); self.lock(); // Note: reshaped for borrowck — explicit unlock paired manually. @@ -283,6 +285,8 @@ impl SavedSourceMap { // the returned `Arc`. let result = Arc::new(ParsedSourceMap::from_internal(ism)); *mapping = Value::init(Arc::into_raw(Arc::clone(&result))).ptr(); + // As in `put_value`: owned by the table through a tagged pointer. + bun_core::asan::lsan_ignore_object(Arc::as_ptr(&result).cast()); self.unlock(); return SourceMap::ParseUrl { map: Some(result), diff --git a/test/bundler/transpiler/macro-test.test.ts b/test/bundler/transpiler/macro-test.test.ts index ad45446e91fc..d78c96356e20 100644 --- a/test/bundler/transpiler/macro-test.test.ts +++ b/test/bundler/transpiler/macro-test.test.ts @@ -406,7 +406,7 @@ describe("a hostile macro", () => { .split("\n") .filter(line => !line.startsWith("[macro]")) .join("\n"), - stderr: stderr.replaceAll(String(dir), "[dir]"), + stderr: stderr.replaceAll(String(dir), "[dir]").replaceAll("\\", "/"), exitCode, signalCode: proc.signalCode, }; From ca9b16b53d0b90cb3b8132e5453abf5b50818e67 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 28 Aug 2026 11:26:25 +0000 Subject: [PATCH 3/8] macros: name process.reallyExit() in its error, move the dense-array hint to a note, keep a stop from reading as idle - process.reallyExit() inside a macro names itself in the TypeError. - The sparse array error drops "Please" and carries the remedy on a note line. - wait_for_promise_until_idle re-checks the stop conditions after the tick that may have requested them, so a stop is never reported as Idle. The macro module load hands the wait outcome to Macro::init: only Idle is the top-level-await diagnostic, a stop is a plain JSError. - Bun__JSCTaskScheduler__hasPendingWork counts only tickets tagged with the VM's current loop kind: a ticket the program registered on the regular loop cannot keep a macro's wait alive. - Shorter comments. --- src/bun_core/lib.rs | 3 +- src/js_parser_jsc/Macro.rs | 46 ++++++++++++---------- src/jsc/JSValue.rs | 10 ++--- src/jsc/VM.rs | 6 +-- src/jsc/VirtualMachine.rs | 27 ++++++------- src/jsc/bindings/BunProcess.cpp | 7 ++-- src/jsc/bindings/JSCTaskScheduler.cpp | 19 ++++++--- src/jsc/bindings/bindings.cpp | 16 +++----- src/jsc/event_loop.rs | 27 +++++++------ test/bundler/transpiler/macro-test.test.ts | 7 ++-- 10 files changed, 81 insertions(+), 87 deletions(-) diff --git a/src/bun_core/lib.rs b/src/bun_core/lib.rs index 6b1127794283..a812f7532a6a 100644 --- a/src/bun_core/lib.rs +++ b/src/bun_core/lib.rs @@ -2887,8 +2887,7 @@ pub mod asan { #[cfg(not(bun_asan))] let _ = (ptr, size); } - /// The heap allocation containing `ptr` is owned through a reference LeakSanitizer cannot follow (e.g. a - /// tagged pointer); do not report it. Its owner is still responsible for freeing it. + /// Do not report the allocation containing `ptr`: its owner holds it through a reference LSAN cannot follow (a tagged pointer). #[inline] pub fn lsan_ignore_object(ptr: *const c_void) { #[cfg(bun_asan)] diff --git a/src/js_parser_jsc/Macro.rs b/src/js_parser_jsc/Macro.rs index 76ad9c892c13..27f17ae18d4c 100644 --- a/src/js_parser_jsc/Macro.rs +++ b/src/js_parser_jsc/Macro.rs @@ -465,7 +465,7 @@ impl Macro { } // SAFETY: `vm` is the per-thread VM; uniquely accessed here. - let loaded_result = unsafe { + let (loaded_result, waited) = unsafe { (*vm).load_macro_entry_point(input_specifier, function_name, specifier, hash) }?; @@ -483,11 +483,14 @@ impl Macro { } return Err(crate::Error::MacroLoadError); } - // The wait gave up: nothing keeps the loop alive for the module's - // top-level await (or the VM was stopped). A `Macro` returned here - // would have its first call find no registered function and leave - // the call in the output as an unbound reference. - jsc::PromiseResult::Pending => return Err(crate::Error::MacroLoadStalled), + // A `Macro` returned here would leave its first call in the output as an + // unbound reference. + jsc::PromiseResult::Pending => { + return Err(match waited { + Err(jsc::Unsettled::Idle) => crate::Error::MacroLoadStalled, + _ => crate::Error::JSError, + }); + } jsc::PromiseResult::Fulfilled(_) => {} } @@ -605,9 +608,7 @@ impl<'a> Run<'a> { // `runner.visited` dropped at scope exit (was `defer runner.visited.deinit(allocator)`) match runner.run(result) { - // Converting the macro's return value threw (a getter, an iterator, a toString): report it the - // way a throw from the macro function itself is reported above, rather than leaving it pending - // under the parser. + // A throw while converting the result (a getter) is reported like a throw from the macro. Err(MacroError::Js(JsError::Thrown)) => { let err = global.take_exception(JsError::Thrown); vm.as_mut().uncaught_exception(global, err, false); @@ -661,9 +662,7 @@ impl<'a> Run<'a> { use ConsoleObject::formatter::Tag as T; match tag { T::Error => { - // Report it the way a throw is reported, then fail the - // expansion. Returning `self.caller` here would leave the call - // in the output with its import gone: an unbound reference. + // Returning `self.caller` would leave the call in the output with its import gone. // SAFETY: `vm()` is the per-thread VM; uniquely accessed here. let _ = unsafe { (*self.macro_.vm()).uncaught_exception(self.global, value, false) }; @@ -738,16 +737,22 @@ impl<'a> Run<'a> { let mut iter = JSArrayIterator::init(value, self.global)?; - // Every index up to `length` becomes an element of the literal, - // holes as `undefined`. Only a length the JS heap actually backs - // keeps that proportional: `[,,1]` with `length = 1e9` would - // otherwise become a billion `undefined`s. + // Every index below `length` becomes an element (holes as `undefined`), so + // `[,,1]` with `length = 1e9` would be a billion `undefined`s. if let Err(stored) = value.indexed_storage_covers(iter.len) { - self.log.add_error_fmt( + self.log.add_range_error_fmt_with_notes( Some(self.source), - self.caller.loc, + Range { + loc: self.caller.loc, + ..Default::default() + }, + Box::new([bun_ast::range_data( + None, + Range::NONE, + b"return a dense array", + )]), format_args!( - "cannot coerce a sparse array to Bun's AST: its length is {} but it holds {} element{}. Please return a dense array", + "cannot coerce a sparse array to Bun's AST: its length is {} but it holds {} element{}", iter.len, stored, if stored == 1 { "" } else { "s" }, @@ -900,8 +905,7 @@ impl<'a> Run<'a> { Err(jsc::Unsettled::Stopped(stopped)) => { return Err(MacroError::Js(stopped.throw(self.global))); } - // Node's exit-13 condition, applied to the macro: nothing - // keeps the loop alive, so waiting on it would be a hang. + // Node's exit-13 condition: the wait would never end. Err(jsc::Unsettled::Idle) => { self.log.add_error_fmt( Some(self.source), diff --git a/src/jsc/JSValue.rs b/src/jsc/JSValue.rs index 87922950926b..cee6964a2c02 100644 --- a/src/jsc/JSValue.rs +++ b/src/jsc/JSValue.rs @@ -2557,13 +2557,9 @@ impl JSValue { index => Some(index as u32), } } - /// `Ok(())` when `self` (an object) holds storage for `length` indexed - /// slots, so iterating them yields at most as much as the JS heap already - /// holds: a dense array, holes included, or an arguments object of that - /// many arguments. `Err(stored)` when `length` runs past its storage, which - /// is a sparse array (`[,,1]` with `length = 1e9`, `a[2**32 - 2] = 1`) or an - /// array-like whose `length` property was written past its elements; - /// `stored` is the number of elements it does hold. + /// `Ok(())` when `self` (an object) backs `length` indexed slots with storage (a dense array, + /// holes included). `Err(stored)` when `length` runs past that storage (a sparse array, or a + /// `length` property written past the elements), with the number of elements it does hold. pub fn indexed_storage_covers(self, length: u32) -> Result<(), u32> { debug_assert!(self.is_object()); unsafe extern "C" { diff --git a/src/jsc/VM.rs b/src/jsc/VM.rs index 9d887a2c7d7d..d65007902cf8 100644 --- a/src/jsc/VM.rs +++ b/src/jsc/VM.rs @@ -103,10 +103,8 @@ impl VM { JSC__VM__executionForbidden(self) } - /// JSC still holds deferred work it will post to this VM's loop later: an - /// `Atomics.waitAsync` timeout, a `FinalizationRegistry` callback, a wasm - /// compile. Only some of those keep the loop alive, so a promise waiting - /// on one can still settle with nothing else pending. + /// JSC will still post deferred work to this VM (an `Atomics.waitAsync` timeout, a wasm + /// compile); not all of it keeps the loop alive. pub fn has_pending_deferred_work(&self) -> bool { Bun__JSCTaskScheduler__hasPendingWork(self) } diff --git a/src/jsc/VirtualMachine.rs b/src/jsc/VirtualMachine.rs index b46a19cb885f..8c499afacc79 100644 --- a/src/jsc/VirtualMachine.rs +++ b/src/jsc/VirtualMachine.rs @@ -1295,13 +1295,9 @@ impl VirtualMachine { } } - /// Something keeps the current loop alive: an active platform handle (a - /// socket, a ref'd timer, a keep-alive ref), a task in flight or queued, a - /// posting from another thread, or deferred work JSC holds for this VM. The - /// same question as [`Self::is_event_loop_alive`] minus whether the program - /// already failed, plus JSC's tickets that do not hold the loop open (an - /// `Atomics.waitAsync` timeout): what a wait on a pending promise asks - /// before it concludes that nothing will settle it. + /// Something can still run JS on the current loop: [`Self::is_event_loop_alive`] without + /// `unhandled_error_counter`, plus JSC's deferred work (an `Atomics.waitAsync` timeout does + /// not keep the loop alive). pub fn has_pending_work(&self) -> bool { let el = self.event_loop_shared(); self.has_pending_work_excluding_immediates() @@ -1561,7 +1557,7 @@ impl VirtualMachine { function_name: &[u8], specifier: &[u8], hash: i32, - ) -> crate::CrateResult<*mut JSInternalPromise> { + ) -> crate::CrateResult<(*mut JSInternalPromise, Result<(), jsc::Unsettled>)> { use bun_bundler::entry_points::{Fs, MacroEntryPoint}; use bun_collections::hash_map::Entry; let entry_point: *mut MacroEntryPoint = match self.macro_entry_points.entry(hash) { @@ -1591,11 +1587,11 @@ impl VirtualMachine { // SAFETY: `entry_point` was just inserted (heap-allocated) or fetched // from the cache; it lives for the VM lifetime. let path: &[u8] = unsafe { &*entry_point }.source.path.text; - let promise = self.run_with_api_lock(|| { + let loaded = self.run_with_api_lock(|| { // SAFETY: per-thread VM; the API lock guarantees JSC is held. VirtualMachine::get().as_mut()._load_macro_entry_point(path) }); - promise.ok_or(crate::CrateError::JSError) + loaded.ok_or(crate::CrateError::JSError) } pub fn is_watcher_enabled(&self) -> bool { @@ -5224,20 +5220,19 @@ impl VirtualMachine { } } - /// Loads and evaluates a macro entry module, waiting for its promise. The - /// promise is still pending on return when the module's top-level `await` - /// can never settle (nothing left on the loop) or the VM was stopped. + /// Loads and evaluates a macro entry module. The promise is still pending on return when the + /// wait gave up (`Idle`: its top-level `await` can never settle; `Stopped`: the VM stopped). #[inline] pub(crate) fn _load_macro_entry_point( &mut self, entry_path: &[u8], - ) -> Option<*mut JSInternalPromise> { + ) -> Option<(*mut JSInternalPromise, Result<(), jsc::Unsettled>)> { let path_str = bun_core::String::from_bytes(entry_path); let promise = jsc::JSModuleLoader::load_and_evaluate_module_ptr(self.global, Some(&path_str))? .as_ptr(); - let _ = self.wait_for_promise_until_idle(jsc::AnyPromise::Internal(promise)); - Some(promise) + let waited = self.wait_for_promise_until_idle(jsc::AnyPromise::Internal(promise)); + Some((promise, waited)) } /// Prints an error-like JS value to the console via the error handler. diff --git a/src/jsc/bindings/BunProcess.cpp b/src/jsc/bindings/BunProcess.cpp index f8744effcf2e..0b5302e79a8f 100644 --- a/src/jsc/bindings/BunProcess.cpp +++ b/src/jsc/bindings/BunProcess.cpp @@ -857,9 +857,8 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionUptime, (JSC::JSGlobalObject * lexicalG return JSC::JSValue::encode(JSC::jsNumber(result)); } -// A macro runs in the VM of whichever thread is transpiling: a bundler worker, -// or the program's own main thread mid-`require()`. Exiting from inside one -// would take down the build, or the program that is only importing the file. +// A macro runs in the transpiling thread's VM (a bundler worker, or the program +// itself mid-require()): exiting from one would exit the build or the program. static bool isRunningMacro(Zig::GlobalObject* globalObject) { return Bun__VM__currentLoopKind(globalObject->bunVM()) == BunLoopKind::Macro; @@ -3717,7 +3716,7 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionReallyExit, (JSGlobalObject * globalObj auto& vm = JSC::getVM(globalObject); auto throwScope = DECLARE_THROW_SCOPE(vm); if (isRunningMacro(defaultGlobalObject(globalObject))) [[unlikely]] { - throwTypeError(globalObject, throwScope, "process.exit() cannot be called from a macro"_s); + throwTypeError(globalObject, throwScope, "process.reallyExit() cannot be called from a macro"_s); return {}; } uint8_t exitCode = 0; diff --git a/src/jsc/bindings/JSCTaskScheduler.cpp b/src/jsc/bindings/JSCTaskScheduler.cpp index a6922d74797d..08f96ae01507 100644 --- a/src/jsc/bindings/JSCTaskScheduler.cpp +++ b/src/jsc/bindings/JSCTaskScheduler.cpp @@ -157,14 +157,23 @@ extern "C" void Bun__deleteDeferredWorkTask(Bun::JSCDeferredWorkTask* job) delete job; } -// JSC still holds a ticket whose completion it will post to this VM later, -// whether or not that ticket keeps the event loop alive (an Atomics.waitAsync -// timeout does not). A wait that gives up on an idle loop asks this first. +// A ticket JSC will still post to the VM's current loop, whether or not it keeps +// that loop alive (an Atomics.waitAsync timeout does not). extern "C" bool Bun__JSCTaskScheduler__hasPendingWork(JSC::VM* vm) { - auto& scheduler = WebCore::clientData(*vm)->deferredWorkTimer; + auto* clientData = WebCore::clientData(*vm); + BunLoopKind loopKind = Bun__VM__currentLoopKind(clientData->bunVM); + auto& scheduler = clientData->deferredWorkTimer; Locker holder { scheduler.m_lock }; - return !scheduler.m_pendingTicketsKeepingEventLoopAlive.isEmpty() || !scheduler.m_pendingTicketsOther.isEmpty(); + for (auto& ticket : scheduler.m_pendingTicketsKeepingEventLoopAlive) { + if (ticket.value == loopKind) + return true; + } + for (auto& ticket : scheduler.m_pendingTicketsOther) { + if (ticket.value == loopKind) + return true; + } + return false; } } diff --git a/src/jsc/bindings/bindings.cpp b/src/jsc/bindings/bindings.cpp index 939e2b17c13e..a500dcf24733 100644 --- a/src/jsc/bindings/bindings.cpp +++ b/src/jsc/bindings/bindings.cpp @@ -7248,15 +7248,10 @@ extern "C" uint64_t Bun__JSArray__nextPresentIndex( } } -// Whether `value` holds storage for `length` indexed slots. A dense array's -// butterfly backs every slot of its length (holes included), so whatever is -// built from its elements is proportional to the JS heap it already occupies. -// A sparse array is not: `[,,1]` with `length = 1e9` keeps one element in a -// vector of three and `a[2**32 - 2] = 1` keeps one in the sparse map, yet -// iterating `length` indices yields a billion `undefined`s. Arguments objects -// keep their elements off the butterfly and their `length` property can be -// written past them. When the storage falls short, `*outStoredCount` is the -// number of elements it does hold. +// Whether `value` backs `length` indexed slots with storage: a dense array does +// (holes included); `[,,1]` with `length = 1e9` or `a[2**32 - 2] = 1` does not. +// Arguments objects keep their elements off the butterfly, and their `length` +// property can be written past them. `*outStoredCount` is the element count. extern "C" bool Bun__JSObject__indexedStorageCovers( JSC::EncodedJSValue encodedValue, uint32_t length, @@ -7290,8 +7285,7 @@ extern "C" bool Bun__JSObject__indexedStorageCovers( case JSC::SlowPutArrayStorageShape: { JSC::ArrayStorage* storage = object->butterfly()->arrayStorage(); unsigned usedVectorLength = std::min(storage->length(), storage->vectorLength()); - // The vector backs its slots whether or not they are filled; only - // what lies past it (or lives in the map) is unbacked. + // Vector slots are backed whether or not they are filled. uint64_t backed = usedVectorLength; uint64_t stored = 0; for (unsigned i = 0; i < usedVectorLength; ++i) { diff --git a/src/jsc/event_loop.rs b/src/jsc/event_loop.rs index 791fbe9127bb..26a76cc8eb74 100644 --- a/src/jsc/event_loop.rs +++ b/src/jsc/event_loop.rs @@ -207,8 +207,7 @@ impl Stopped { pub enum Unsettled { #[error(transparent)] Stopped(Stopped), - /// Nothing keeps the loop alive any more ([`VirtualMachine::has_pending_work`]): - /// the condition under which a program would have exited with it unsettled. + /// Nothing keeps the loop alive ([`VirtualMachine::has_pending_work`]): a program would have exited here. #[error("Idle")] Idle, } @@ -1131,29 +1130,31 @@ impl EventLoop { Ok(()) } - /// [`Self::wait_for_promise`], but gives up once nothing keeps the loop - /// alive ([`VirtualMachine::has_pending_work`]): where a program would have - /// exited with `promise` unsettled, this returns `Idle` with it pending. A - /// wait that has to finish (a macro, whose caller holds the parse) uses this - /// so such a promise is an error rather than a hang. + /// [`Self::wait_for_promise`], but returns `Idle` with `promise` still pending once nothing + /// keeps the loop alive ([`VirtualMachine::has_pending_work`]), where a program would have exited. pub fn wait_for_promise_until_idle( &mut self, promise: jsc::AnyPromise, ) -> Result<(), Unsettled> { let jsc_vm = self.vm_ref().jsc_vm(); + let stopped = |this: &Self| { + jsc_vm.execution_forbidden() + || !this.vm_ref().script_allowed() + || this.global_ref().has_pending_termination_exception() + }; while promise.status() == PromiseStatus::Pending { - if jsc_vm.execution_forbidden() - || !self.vm_ref().script_allowed() - || self.global_ref().has_pending_termination_exception() - { + if stopped(self) { return Err(Unsettled::Stopped(Stopped)); } self.tick(); if promise.status() != PromiseStatus::Pending { break; } - // After the drain, so a reaction queued by the last task (or a - // handle it opened) counts. + // A task in that tick may have requested the stop; a stop is never idle. + if stopped(self) { + return Err(Unsettled::Stopped(Stopped)); + } + // After the drain, so what the last task queued or opened counts. if !self.vm_ref().has_pending_work() { return Err(Unsettled::Idle); } diff --git a/test/bundler/transpiler/macro-test.test.ts b/test/bundler/transpiler/macro-test.test.ts index d78c96356e20..234b8aa25c3e 100644 --- a/test/bundler/transpiler/macro-test.test.ts +++ b/test/bundler/transpiler/macro-test.test.ts @@ -414,7 +414,7 @@ describe("a hostile macro", () => { test.concurrent.each([ ["process.exit()", `process.exit(42)`, "process.exit() cannot be called from a macro"], - ["process.reallyExit()", `process.reallyExit(42)`, "process.exit() cannot be called from a macro"], + ["process.reallyExit()", `process.reallyExit(42)`, "process.reallyExit() cannot be called from a macro"], ["process.abort()", `process.abort()`, "process.abort() cannot be called from a macro"], ])("%s inside a macro fails the build instead of the process", async (_name, call, message) => { const { stderr, exitCode, signalCode } = await build({ "m.ts": `export function m() { ${call}; }` }); @@ -487,11 +487,10 @@ describe("a hostile macro", () => { const { stderr, exitCode } = await build({ "m.ts": `export function m() { ${body} }` }); expect({ exitCode, stderr }).toEqual({ exitCode: 1, - stderr: expect.stringContaining( - `error: cannot coerce a sparse array to Bun's AST: ${message}. Please return a dense array`, - ), + stderr: expect.stringContaining(`error: cannot coerce a sparse array to Bun's AST: ${message}\n`), }); expect(stderr).toContain("at [dir]/index.ts:2:18"); + expect(stderr).toContain("note: return a dense array"); }); test.concurrent("dense arrays with holes, arguments objects, and doubles are still inlined", async () => { From c45857e1469370826b86751b09022fe3df8e63e5 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 29 Aug 2026 01:47:57 +0000 Subject: [PATCH 4/8] macros: fail the build when a return value is nested too deeply for the stack Run::run and Run::coerce recurse once per nesting level of the returned value, on a 4 MB bundler pool thread. A value nested 10000 levels deep overflowed the stack and the build died with SIGSEGV and no message. The walk now carries the parser's StackCheck and stops with a located error once the headroom is gone. --- src/js_parser_jsc/Macro.rs | 11 +++++++++++ test/bundler/transpiler/macro-test.test.ts | 16 ++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/js_parser_jsc/Macro.rs b/src/js_parser_jsc/Macro.rs index 27f17ae18d4c..8253c7b8abb1 100644 --- a/src/js_parser_jsc/Macro.rs +++ b/src/js_parser_jsc/Macro.rs @@ -563,6 +563,8 @@ pub(crate) struct Run<'a> { pub(crate) source: &'a Source, pub(crate) visited: VisitMap, pub(crate) is_top_level: bool, + /// `run` recurses once per nesting level of the returned value, on a bundler pool thread's stack. + pub(crate) stack_check: bun_core::StackCheck, } impl<'a> Run<'a> { @@ -603,6 +605,7 @@ impl<'a> Run<'a> { source, visited: VisitMap::default(), is_top_level: false, + stack_check: bun_core::StackCheck::init(), }; // `runner.visited` dropped at scope exit (was `defer runner.visited.deinit(allocator)`) @@ -620,6 +623,14 @@ impl<'a> Run<'a> { pub(crate) fn run(&mut self, value: JSValue) -> Result { use ConsoleObject::formatter::Tag as T; + if !self.stack_check.is_safe_to_recurse() { + self.log.add_error_fmt( + Some(self.source), + self.caller.loc, + format_args!("macro return value is too deeply nested"), + ); + return Err(MacroError::MacroFailed); + } // `Tag::get` returns `TagResult { tag: TagPayload, .. }`; // collapse the payload to its discriminant via `.tag()`. match T::get(value, self.global)?.tag.tag() { diff --git a/test/bundler/transpiler/macro-test.test.ts b/test/bundler/transpiler/macro-test.test.ts index 234b8aa25c3e..033dd76730b6 100644 --- a/test/bundler/transpiler/macro-test.test.ts +++ b/test/bundler/transpiler/macro-test.test.ts @@ -507,6 +507,22 @@ describe("a hostile macro", () => { ); }); + // The value-to-AST walk recurses once per nesting level on a bundler pool thread's stack. Before: a + // stack overflow, SIGSEGV with nothing printed. + test.concurrent.each([ + ["objects", `v = { v }`], + ["arrays", `v = [v]`], + ])("a return value nested 100000 %s deep is a located error", async (_name, wrap) => { + const { stderr, exitCode, signalCode } = await build({ + "m.ts": `export function m() { let v: unknown = 1; for (let i = 0; i < 100000; i++) ${wrap}; return v; }`, + }); + expect({ exitCode, signalCode, stderr }).toEqual({ + exitCode: 1, + signalCode: null, + stderr: expect.stringContaining("error: macro return value is too deeply nested\n at [dir]/index.ts:2:18"), + }); + }); + // Before: the parse spun on the promise forever (100% CPU). A program in the same state, a pending await // with nothing keeping the event loop alive, would have exited; the macro fails the same way. test.concurrent("a returned promise that can never settle is a located error", async () => { From 8de818a41e76d9d32db10976746d31f258dc8c0f Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 23:02:09 +0000 Subject: [PATCH 5/8] macros: read the loop kind from PendingWork after the merge with main main (#42590) turned the value of JSCTaskScheduler's pending-ticket maps from a BunLoopKind into a PendingWork struct. The merge is textually clean, but Bun__JSCTaskScheduler__hasPendingWork compared the whole value with a loop kind and no longer compiled. Compare its loopKind field. Add a test for what that filter is for: a ticket the program registered on the regular loop does not keep a macro's wait alive. --- src/jsc/bindings/JSCTaskScheduler.cpp | 4 +-- test/bundler/transpiler/macro-test.test.ts | 37 ++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/jsc/bindings/JSCTaskScheduler.cpp b/src/jsc/bindings/JSCTaskScheduler.cpp index 1fcf2e582e2c..7703d05731f9 100644 --- a/src/jsc/bindings/JSCTaskScheduler.cpp +++ b/src/jsc/bindings/JSCTaskScheduler.cpp @@ -199,11 +199,11 @@ extern "C" bool Bun__JSCTaskScheduler__hasPendingWork(JSC::VM* vm) auto& scheduler = clientData->deferredWorkTimer; Locker holder { scheduler.m_lock }; for (auto& ticket : scheduler.m_pendingTicketsKeepingEventLoopAlive) { - if (ticket.value == loopKind) + if (ticket.value.loopKind == loopKind) return true; } for (auto& ticket : scheduler.m_pendingTicketsOther) { - if (ticket.value == loopKind) + if (ticket.value.loopKind == loopKind) return true; } return false; diff --git a/test/bundler/transpiler/macro-test.test.ts b/test/bundler/transpiler/macro-test.test.ts index 332a78fef5fb..0c087d017f37 100644 --- a/test/bundler/transpiler/macro-test.test.ts +++ b/test/bundler/transpiler/macro-test.test.ts @@ -640,6 +640,43 @@ describe("a hostile macro", () => { expect({ stderr, exitCode }).toEqual({ stderr: "", exitCode: 0 }); expect(stdout.replace(/\s+/g, "")).toContain(`varv=["timed-out",true];`); }); + + // require() runs the macro in the program's own VM. The program's Atomics.waitAsync ticket (no timeout, + // nobody notifies) belongs to the regular loop: it must not read as work the macro is still waiting for. + test.concurrent("a JSC ticket the program registered does not keep a macro's wait alive", async () => { + using dir = tempDir("macro-hostile-ticket", { + "m.ts": `export function never() { return new Promise(() => {}); }`, + "uses.ts": `import { never } from "./m.ts" with { type: "macro" };\nexport const v = never();\n`, + "index.ts": [ + `Atomics.waitAsync(new Int32Array(new SharedArrayBuffer(4)), 0, 0);`, + `try {`, + ` require("./uses.ts");`, + ` console.log("required");`, + `} catch (e) {`, + ` console.log("require failed: " + String(e.message).split("\\n")[0]);`, + `}`, + `process.exit(0);`, + ].join("\n"), + }); + await using proc = Bun.spawn({ + cmd: [bunExe(), "run", "index.ts"], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + timeout: 20_000, + killSignal: "SIGKILL", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + // stderr rides along so a failure shows what the child printed. + expect({ lastLine: stdout.trim().split("\n").pop(), exitCode, signalCode: proc.signalCode, stderr }).toEqual({ + lastLine: + "require failed: macro returned a promise that never settles: no timer, I/O, or task is keeping the event loop alive", + exitCode: 0, + signalCode: null, + stderr: expect.any(String), + }); + }); }); // A module that is not the entry point is transpiled on a worker thread, where no VM exists yet. The From e37bf9d89760412f8b0c99b41ef0834eed725d12 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 23:42:59 +0000 Subject: [PATCH 6/8] macros: report a macro's error without the program's fatal-error path, fail later uses of a macro that did not load, refuse process.kill on the current process A file loaded with require() runs its macros in the program's own VM. Every macro failure was reported through uncaught_exception or unhandled_rejection, which there is the fatal-error path: exit code 1 and an abandoned event loop, even when the program catches the failed require(). The error is now printed with run_error_handler, and the returned promise is marked handled before the wait so the rejection tracker does not report it a second time. This covers a throw, a returned Error, a BuildMessage or ResolveMessage, a rejected promise, and a macro module that throws while it loads. A macro whose load failed stayed in the table as a disabled entry, and every later call returned the caller unchanged: the call was left in the output with its import gone. A disabled entry now fails the expansion with a located error. process.kill() with a signal aimed at the current process throws in a macro, like process.exit() and process.abort(). A macro can still signal a child. --- src/js_parser_jsc/Macro.rs | 43 +++++++----- src/jsc/bindings/BunProcess.cpp | 8 ++- test/bundler/transpiler/macro-test.test.ts | 82 ++++++++++++++++++++++ 3 files changed, 113 insertions(+), 20 deletions(-) diff --git a/src/js_parser_jsc/Macro.rs b/src/js_parser_jsc/Macro.rs index 63705dc4d6cf..2ab32b2bae7b 100644 --- a/src/js_parser_jsc/Macro.rs +++ b/src/js_parser_jsc/Macro.rs @@ -220,7 +220,17 @@ impl MacroContext { let macro_vm = macro_entry.value_ptr.vm; let macro_: *const Macro = macro_entry.value_ptr; if macro_disabled { - return Ok(caller); + // Its load failed on an earlier call. Returning `caller` would leave this call in the + // output with its import gone. + log.add_error_fmt( + Some(source), + caller.loc, + format_args!( + "macro \"{}\" failed to load", + bstr::BStr::new(import_record_path) + ), + ); + return Err(crate::Error::MacroFailed); } // SAFETY: `Some` for every non-disabled Macro; see `Macro` struct comment. let vm = macro_vm @@ -480,11 +490,8 @@ impl Macro { }; match unwrapped { jsc::PromiseResult::Rejected(result) => { - // SAFETY: `vm.global` is the live per-thread global; `loaded_result` - // is a live promise cell. - unsafe { - (*vm).unhandled_rejection(&*(*vm).global, result, (*loaded_result).to_js()); - } + // SAFETY: `vm` is the live per-thread VM. + unsafe { (*vm).run_error_handler(result, None) }; return Err(crate::Error::MacroLoadError); } // A `Macro` returned here would leave its first call in the output as an @@ -591,10 +598,12 @@ impl<'a> Run<'a> { let result = match vm.run_with_api_lock(|| macro_callback.call(global, JSValue::ZERO, args)) { Ok(result) => result, - // The macro threw: report it (with its stack) and fail this expansion. + // The macro threw: print it (with its stack) and fail this expansion. Not + // `uncaught_exception`: on the program's own VM (a `require()`d file) that is the + // fatal-error path, and the program may catch the failed `require()` and go on. Err(JsError::Thrown) => { let err = global.take_exception(JsError::Thrown); - vm.as_mut().uncaught_exception(global, err, false); + vm.as_mut().run_error_handler(err, None); return Err(MacroError::MacroFailed); } Err(e) => return Err(e.into()), @@ -618,7 +627,7 @@ impl<'a> Run<'a> { // A throw while converting the result (a getter) is reported like a throw from the macro. Err(MacroError::Js(JsError::Thrown)) => { let err = global.take_exception(JsError::Thrown); - vm.as_mut().uncaught_exception(global, err, false); + vm.as_mut().run_error_handler(err, None); Err(MacroError::MacroFailed) } other => other, @@ -679,8 +688,7 @@ impl<'a> Run<'a> { T::Error => { // Returning `self.caller` would leave the call in the output with its import gone. // SAFETY: `vm()` is the per-thread VM; uniquely accessed here. - let _ = - unsafe { (*self.macro_.vm()).uncaught_exception(self.global, value, false) }; + unsafe { (*self.macro_.vm()).run_error_handler(value, None) }; return Err(MacroError::MacroFailed); } T::Undefined => { @@ -715,9 +723,7 @@ impl<'a> Run<'a> { || value.as_::().is_some() { // SAFETY: `vm()` is the per-thread VM; uniquely accessed here. - let _ = unsafe { - (*self.macro_.vm()).uncaught_exception(self.global, value, false) - }; + unsafe { (*self.macro_.vm()).run_error_handler(value, None) }; return Err(MacroError::MacroFailed); } } @@ -914,6 +920,9 @@ impl<'a> Run<'a> { let _ = self.macro_.vm(); let vm = VirtualMachine::get(); + // This wait is the promise's handler: a rejection is reported below, not by the + // VM's unhandled-rejection path (fatal to a program that `require()`d the file). + promise.set_handled(vm.jsc_vm()); match vm.as_mut().wait_for_promise_until_idle(promise) { Ok(()) => {} // The VM stopped before the macro's promise settled: throw its termination and unwind. @@ -950,11 +959,7 @@ impl<'a> Run<'a> { || promise_result .is_exception(std::ptr::from_ref::(self.global.vm()).cast_mut()) { - vm.as_mut().unhandled_rejection( - self.global, - promise_result, - promise.as_value(), - ); + vm.as_mut().run_error_handler(promise_result, None); return Err(MacroError::MacroFailed); } self.is_top_level = false; diff --git a/src/jsc/bindings/BunProcess.cpp b/src/jsc/bindings/BunProcess.cpp index aea92bfecce9..5f0e276f1535 100644 --- a/src/jsc/bindings/BunProcess.cpp +++ b/src/jsc/bindings/BunProcess.cpp @@ -4818,10 +4818,16 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionReallyKill, (JSC::JSGlobalObject * glob #else int ownPid = uv_os_getpid(); #endif + bool isSelfDirected = pid == 0 || pid == -1 || pid == ownPid || pid == -ownPid; + // A macro may signal a child it spawned, not the process that runs it. + if (signal > 0 && isSelfDirected && isRunningMacro(defaultGlobalObject(globalObject))) [[unlikely]] { + throwTypeError(globalObject, scope, "process.kill() cannot signal the current process from a macro"_s); + return {}; + } // Node's Kill binding runs RunAtExit for a self-directed unhandled signal, so flush profiles // first. `signalToContextIdsMap` is mutated only on the main thread; workers never set // profiler configs, so skipping the flush there avoids a rehash race. - if (signal > 0 && (pid == 0 || pid == -1 || pid == ownPid || pid == -ownPid) + if (signal > 0 && isSelfDirected && !(Bun__isMainThreadVM() && signalToContextIdsMap && signalToContextIdsMap->contains(signal))) { Bun__writeProfilesBeforeSelfKill(); } diff --git a/test/bundler/transpiler/macro-test.test.ts b/test/bundler/transpiler/macro-test.test.ts index 0c087d017f37..15470371ff8b 100644 --- a/test/bundler/transpiler/macro-test.test.ts +++ b/test/bundler/transpiler/macro-test.test.ts @@ -488,6 +488,11 @@ describe("a hostile macro", () => { ["process.exit()", `process.exit(42)`, "process.exit() cannot be called from a macro"], ["process.reallyExit()", `process.reallyExit(42)`, "process.reallyExit() cannot be called from a macro"], ["process.abort()", `process.abort()`, "process.abort() cannot be called from a macro"], + [ + "process.kill(process.pid)", + `process.kill(process.pid)`, + "process.kill() cannot signal the current process from a macro", + ], ])("%s inside a macro fails the build instead of the process", async (_name, call, message) => { const { stderr, exitCode, signalCode } = await build({ "m.ts": `export function m() { ${call}; }` }); expect({ exitCode, signalCode, stderr }).toEqual({ @@ -677,6 +682,83 @@ describe("a hostile macro", () => { stderr: expect.any(String), }); }); + + // require() runs the macro in the program's own VM. The macro's error is printed and the require() + // throws; it must not also go down the program's fatal-error path (exit code 1, event loop abandoned). + test.concurrent.each([ + ["throws", `export function m() { throw new Error("macro boom"); }`], + ["returns an Error", `export function m() { return new Error("macro boom"); }`], + ["returns a promise that rejects", `export async function m() { await 1; throw new Error("macro boom"); }`], + ["throws while its module loads", `throw new Error("macro boom");\nexport function m() {}`], + ])("a program that catches the require() of a file whose macro %s keeps running", async (_name, macro) => { + using dir = tempDir("macro-hostile-caught", { + "m.ts": macro, + "uses.ts": `import { m } from "./m.ts" with { type: "macro" };\nexport const v = m();\n`, + "index.ts": [ + `try {`, + ` require("./uses.ts");`, + ` console.log("required");`, + `} catch {`, + ` console.log("caught");`, + `}`, + `setTimeout(() => console.log("timer fired"), 1);`, + ].join("\n"), + }); + await using proc = Bun.spawn({ + cmd: [bunExe(), "run", "index.ts"], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + const lines = stdout + .trim() + .split("\n") + .filter(line => !line.startsWith("[macro]")); + expect({ lines, stderr, exitCode }).toEqual({ + lines: ["caught", "timer fired"], + stderr: expect.stringContaining("error: macro boom"), + exitCode: 0, + }); + }); + + // The runtime keeps one macro table for the VM's lifetime. Before: the second file kept its `m()` call + // with the import gone, loaded, and threw a ReferenceError when the line ran. + test.concurrent("a second file using a macro that failed to load fails too", async () => { + using dir = tempDir("macro-hostile-reload", { + "m.ts": `throw new Error("macro boom");\nexport function m() {}`, + "a.ts": `import { m } from "./m.ts" with { type: "macro" };\nexport const v = m();\n`, + "b.ts": `import { m } from "./m.ts" with { type: "macro" };\nexport const w = m();\n`, + "index.ts": [ + `for (const file of ["./a.ts", "./b.ts"]) {`, + ` try {`, + ` require(file);`, + ` console.log(file + " loaded");`, + ` } catch (e) {`, + ` console.log(file + ": " + String(e.message).split("\\n")[0]);`, + ` }`, + `}`, + ].join("\n"), + }); + await using proc = Bun.spawn({ + cmd: [bunExe(), "run", "index.ts"], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + const lines = stdout + .trim() + .split("\n") + .filter(line => !line.startsWith("[macro]")); + expect({ lines, stderr, exitCode }).toEqual({ + lines: [`./a.ts: "MacroLoadError" error in macro`, `./b.ts: macro "./m.ts" failed to load`], + stderr: expect.stringContaining("error: macro boom"), + exitCode: 0, + }); + }); }); // A module that is not the entry point is transpiled on a worker thread, where no VM exists yet. The From 1888e3111cd49567fe1a8142e1ff99e596ac5c33 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 23:44:09 +0000 Subject: [PATCH 7/8] macros: shorter comments --- src/js_parser_jsc/Macro.rs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/src/js_parser_jsc/Macro.rs b/src/js_parser_jsc/Macro.rs index 2ab32b2bae7b..a70f49ddf278 100644 --- a/src/js_parser_jsc/Macro.rs +++ b/src/js_parser_jsc/Macro.rs @@ -220,8 +220,7 @@ impl MacroContext { let macro_vm = macro_entry.value_ptr.vm; let macro_: *const Macro = macro_entry.value_ptr; if macro_disabled { - // Its load failed on an earlier call. Returning `caller` would leave this call in the - // output with its import gone. + // Its load failed earlier; returning `caller` would leave an unbound call in the output. log.add_error_fmt( Some(source), caller.loc, @@ -598,9 +597,7 @@ impl<'a> Run<'a> { let result = match vm.run_with_api_lock(|| macro_callback.call(global, JSValue::ZERO, args)) { Ok(result) => result, - // The macro threw: print it (with its stack) and fail this expansion. Not - // `uncaught_exception`: on the program's own VM (a `require()`d file) that is the - // fatal-error path, and the program may catch the failed `require()` and go on. + // Printed, not `uncaught_exception`: in a `require()`ing program's VM that path is fatal. Err(JsError::Thrown) => { let err = global.take_exception(JsError::Thrown); vm.as_mut().run_error_handler(err, None); @@ -920,8 +917,7 @@ impl<'a> Run<'a> { let _ = self.macro_.vm(); let vm = VirtualMachine::get(); - // This wait is the promise's handler: a rejection is reported below, not by the - // VM's unhandled-rejection path (fatal to a program that `require()`d the file). + // This wait handles the promise: the rejection tracker must not report it too. promise.set_handled(vm.jsc_vm()); match vm.as_mut().wait_for_promise_until_idle(promise) { Ok(()) => {} From ac9730f942fe677a4edf0774443efa4dd6ec29ec Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 19 Sep 2026 00:01:05 +0000 Subject: [PATCH 8/8] macros: refuse process.kill() aimed at the current process group too The guard matched -ownPid, which is the process group only when bun leads it. Use killReachesThisProcess(), which compares with getpgrp(). The profile flush keeps its own predicate. --- src/jsc/bindings/BunProcess.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/jsc/bindings/BunProcess.cpp b/src/jsc/bindings/BunProcess.cpp index 5f0e276f1535..c530db267d18 100644 --- a/src/jsc/bindings/BunProcess.cpp +++ b/src/jsc/bindings/BunProcess.cpp @@ -4818,16 +4818,20 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionReallyKill, (JSC::JSGlobalObject * glob #else int ownPid = uv_os_getpid(); #endif - bool isSelfDirected = pid == 0 || pid == -1 || pid == ownPid || pid == -ownPid; +#if !OS(WINDOWS) + bool reachesThisProcess = pid == -1 || killReachesThisProcess(pid, ownPid); +#else + bool reachesThisProcess = pid == 0 || pid == -1 || pid == ownPid || pid == -ownPid; +#endif // A macro may signal a child it spawned, not the process that runs it. - if (signal > 0 && isSelfDirected && isRunningMacro(defaultGlobalObject(globalObject))) [[unlikely]] { + if (signal > 0 && reachesThisProcess && isRunningMacro(defaultGlobalObject(globalObject))) [[unlikely]] { throwTypeError(globalObject, scope, "process.kill() cannot signal the current process from a macro"_s); return {}; } // Node's Kill binding runs RunAtExit for a self-directed unhandled signal, so flush profiles // first. `signalToContextIdsMap` is mutated only on the main thread; workers never set // profiler configs, so skipping the flush there avoids a rehash race. - if (signal > 0 && isSelfDirected + if (signal > 0 && (pid == 0 || pid == -1 || pid == ownPid || pid == -ownPid) && !(Bun__isMainThreadVM() && signalToContextIdsMap && signalToContextIdsMap->contains(signal))) { Bun__writeProfilesBeforeSelfKill(); }