diff --git a/src/js_parser_jsc/Macro.rs b/src/js_parser_jsc/Macro.rs index d4b574bf8fab..a70f49ddf278 100644 --- a/src/js_parser_jsc/Macro.rs +++ b/src/js_parser_jsc/Macro.rs @@ -193,6 +193,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); @@ -208,7 +220,16 @@ 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 earlier; returning `caller` would leave an unbound call in the output. + 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 @@ -457,7 +478,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) }?; @@ -466,13 +487,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` is the live per-thread VM. + unsafe { (*vm).run_error_handler(result, None) }; + return Err(crate::Error::MacroLoadError); } - return Err(crate::Error::MacroLoadError); + // 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(_) => {} } Ok(Macro { @@ -544,6 +573,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> { @@ -563,11 +594,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, + // 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); + return Err(MacroError::MacroFailed); + } + Err(e) => return Err(e.into()), + }; let mut runner = Run { caller, @@ -578,15 +615,32 @@ 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)`) - runner.run(result) + match runner.run(result) { + // 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().run_error_handler(err, None); + Err(MacroError::MacroFailed) + } + other => other, + } } 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() { @@ -629,10 +683,10 @@ impl<'a> Run<'a> { use ConsoleObject::formatter::Tag as T; match tag { 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) }; - return Ok(self.caller); + unsafe { (*self.macro_.vm()).run_error_handler(value, None) }; + return Err(MacroError::MacroFailed); } T::Undefined => { if self.is_top_level { @@ -666,9 +720,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); } } @@ -703,6 +755,30 @@ impl<'a> Run<'a> { let mut iter = JSArrayIterator::init(value, self.global)?; + // 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_range_error_fmt_with_notes( + Some(self.source), + 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{}", + 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 `?`) @@ -841,10 +917,26 @@ 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)))?; + // 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(()) => {} + // 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: the wait would never end. + 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; @@ -863,11 +955,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/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 3a4ce3566e28..d8d5b89b38e6 100644 --- a/src/jsc/JSValue.rs +++ b/src/jsc/JSValue.rs @@ -2615,6 +2615,25 @@ impl JSValue { index => Some(index as u32), } } + /// `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" { + 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/SavedSourceMap.rs b/src/jsc/SavedSourceMap.rs index 7edf2e3ad7d0..a45372ac3a22 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::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::ignore_object(Arc::as_ptr(&result).cast()); self.unlock(); return SourceMap::ParseUrl { map: Some(result), diff --git a/src/jsc/VM.rs b/src/jsc/VM.rs index ce53cdaeb33c..72fb4c0101fb 100644 --- a/src/jsc/VM.rs +++ b/src/jsc/VM.rs @@ -40,6 +40,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! { @@ -124,6 +125,12 @@ impl VM { JSC__VM__executionForbidden(self) } + /// 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) + } + // 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 52461eaf0526..df05741a80c0 100644 --- a/src/jsc/VirtualMachine.rs +++ b/src/jsc/VirtualMachine.rs @@ -1785,20 +1785,29 @@ impl VirtualMachine { } } - pub fn is_event_loop_alive_excluding_immediates(&self) -> bool { + /// 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(); - 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 { @@ -2048,7 +2057,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) { @@ -2078,11 +2087,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 { @@ -3316,6 +3325,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] @@ -5804,18 +5822,19 @@ impl VirtualMachine { } } - /// Loads and evaluates a macro entry module, waiting for its promise. + /// 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(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 30a84bf05b33..c530db267d18 100644 --- a/src/jsc/bindings/BunProcess.cpp +++ b/src/jsc/bindings/BunProcess.cpp @@ -889,11 +889,22 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionUptime, (JSC::JSGlobalObject * lexicalG return JSC::JSValue::encode(JSC::jsNumber(result)); } +// 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; +} + 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); @@ -1863,6 +1874,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. @@ -3746,6 +3763,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.reallyExit() cannot be called from a macro"_s); + return {}; + } uint8_t exitCode = 0; JSValue arg0 = callFrame->argument(0); if (arg0.isAnyInt()) { @@ -4797,6 +4818,16 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionReallyKill, (JSC::JSGlobalObject * glob #else int ownPid = uv_os_getpid(); #endif +#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 && 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. diff --git a/src/jsc/bindings/JSCTaskScheduler.cpp b/src/jsc/bindings/JSCTaskScheduler.cpp index de2d83fb0661..7703d05731f9 100644 --- a/src/jsc/bindings/JSCTaskScheduler.cpp +++ b/src/jsc/bindings/JSCTaskScheduler.cpp @@ -190,4 +190,23 @@ extern "C" void Bun__deleteDeferredWorkTask(Bun::JSCDeferredWorkTask* job) delete job; } +// 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* clientData = WebCore::clientData(*vm); + BunLoopKind loopKind = Bun__VM__currentLoopKind(clientData->bunVM); + auto& scheduler = clientData->deferredWorkTimer; + Locker holder { scheduler.m_lock }; + for (auto& ticket : scheduler.m_pendingTicketsKeepingEventLoopAlive) { + if (ticket.value.loopKind == loopKind) + return true; + } + for (auto& ticket : scheduler.m_pendingTicketsOther) { + if (ticket.value.loopKind == loopKind) + return true; + } + return false; +} + } diff --git a/src/jsc/bindings/bindings.cpp b/src/jsc/bindings/bindings.cpp index ebfbfbbe123f..bdafe9de2bba 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" @@ -7154,6 +7156,65 @@ extern "C" uint64_t Bun__JSArray__nextPresentIndex( } } +// 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, + 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()); + // 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) { + 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 a44ba7575b59..3f45f15cfa89 100644 --- a/src/jsc/event_loop.rs +++ b/src/jsc/event_loop.rs @@ -202,6 +202,16 @@ 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 ([`VirtualMachine::has_pending_work`]): a program would have exited here. + #[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*: @@ -1157,6 +1167,39 @@ impl EventLoop { Ok(()) } + /// [`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 stopped(self) { + return Err(Unsettled::Stopped(Stopped)); + } + self.tick(); + if promise.status() != PromiseStatus::Pending { + break; + } + // 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); + } + 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 88d2e59bb252..6236c2a438bb 100644 --- a/src/jsc/lib.rs +++ b/src/jsc/lib.rs @@ -1241,7 +1241,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 965008868621..15470371ff8b 100644 --- a/test/bundler/transpiler/macro-test.test.ts +++ b/test/bundler/transpiler/macro-test.test.ts @@ -453,6 +453,314 @@ 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]").replaceAll("\\", "/"), + 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.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({ + 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}\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 () => { + 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];", + ); + }); + + // 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 () => { + 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];`); + }); + + // 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), + }); + }); + + // 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 // macro VM created there has to take the CLI's transform options, or the macro module never sees // `--define`.