diff --git a/src/js/builtins/shell.ts b/src/js/builtins/shell.ts index eb40883e52ed..f4780c796db5 100644 --- a/src/js/builtins/shell.ts +++ b/src/js/builtins/shell.ts @@ -131,7 +131,7 @@ export function createBunShellTemplateFunction(createShellInterpreter_, createPa res(out); } }; - // Only for a failure to build the output buffers; exit codes go through `resolve`. + // Only for a JS error raised by the interpreter itself; exit codes go through `resolve`. reject = error => { potentialError = undefined; rej(error); diff --git a/src/runtime/shell/Builtin.rs b/src/runtime/shell/Builtin.rs index 3504a9a802ea..44220d935e84 100644 --- a/src/runtime/shell/Builtin.rs +++ b/src/runtime/shell/Builtin.rs @@ -689,7 +689,7 @@ impl Builtin { .to_vec() .into_boxed_slice(), )); - return Some(Yield::failed()); + return Some(Yield::Failed(cmd)); }; let jsval = interp.jsobjs[idx]; @@ -705,19 +705,19 @@ impl Builtin { let me = Self::of_mut(interp, cmd); if redirect.stdin() { let Some(buf) = root() else { - return Some(Yield::failed()); + return Some(Yield::Failed(cmd)); }; me.stdin = BuiltinInput::ArrayBuf { buf, i: 0 }; } if redirect.stdout() { let Some(buf) = root() else { - return Some(Yield::failed()); + return Some(Yield::Failed(cmd)); }; me.stdout = BuiltinIO::ArrayBuf { buf, i: 0 }; } if redirect.stderr() { let Some(buf) = root() else { - return Some(Yield::failed()); + return Some(Yield::Failed(cmd)); }; me.stderr = BuiltinIO::ArrayBuf { buf, i: 0 }; } @@ -733,7 +733,7 @@ impl Builtin { let _ = global.throw(format_args!( "Cannot redirect stdout/stderr to an immutable blob. Expected a file" )); - return Some(Yield::failed()); + return Some(Yield::Failed(cmd)); } let original_blob = body.use_(); if !redirect.stdin() && !redirect.stdout() && !redirect.stderr() { @@ -759,7 +759,7 @@ impl Builtin { let _ = global.throw(format_args!( "Cannot redirect stdout/stderr to an immutable blob. Expected a file" )); - return Some(Yield::failed()); + return Some(Yield::Failed(cmd)); } let theblob = Arc::new(BuiltinBlob { blob: blob_ref.dupe(), @@ -777,7 +777,7 @@ impl Builtin { "Unknown JS value used in shell: {}", jsval.fmt_string(global) )); - return Some(Yield::failed()); + return Some(Yield::Failed(cmd)); } } None if redirect.duplicate_out() => { diff --git a/src/runtime/shell/IOReader.rs b/src/runtime/shell/IOReader.rs index 0484e6ed5c2b..110d85cab602 100644 --- a/src/runtime/shell/IOReader.rs +++ b/src/runtime/shell/IOReader.rs @@ -231,7 +231,6 @@ impl IOReader { s.is_reading = true; if let Err(e) = self.reader().start_with_current_pipe() { self.on_reader_error(&e); - return Yield::failed(); } Yield::suspended() } diff --git a/src/runtime/shell/Yield.rs b/src/runtime/shell/Yield.rs index 351032832410..50b2215143f0 100644 --- a/src/runtime/shell/Yield.rs +++ b/src/runtime/shell/Yield.rs @@ -37,8 +37,8 @@ pub enum Yield { /// Execution is waiting on async IO (epoll/kqueue/uv). The caller's task /// callback will resume by calling `.run()` again later. Suspended, - /// Threw a JS error. - Failed, + /// The node threw a JS exception; `Interpreter::fail` winds the script down. + Failed(NodeId), Done, } @@ -51,10 +51,6 @@ impl Yield { pub(crate) const fn done() -> Yield { Yield::Done } - #[inline] - pub(crate) const fn failed() -> Yield { - Yield::Failed - } } thread_local! { @@ -131,7 +127,8 @@ impl Yield { written, err, } => crate::shell::io_writer::on_io_writer_chunk(interp, child, written, err), - Yield::Suspended | Yield::Failed | Yield::Done => { + Yield::Failed(id) => interp.fail(id), + Yield::Suspended | Yield::Done => { if let Some(y) = Self::drain_pipelines(interp, &mut pipeline_stack) { y } else { diff --git a/src/runtime/shell/builtin/cat.rs b/src/runtime/shell/builtin/cat.rs index ef09d1f66a76..f1b338640653 100644 --- a/src/runtime/shell/builtin/cat.rs +++ b/src/runtime/shell/builtin/cat.rs @@ -232,7 +232,7 @@ impl Cat { }); reader.start() } - Branch::WaitingErr => Yield::failed(), + Branch::WaitingErr => Yield::suspended(), } } diff --git a/src/runtime/shell/builtin/cp.rs b/src/runtime/shell/builtin/cp.rs index f51257afdfcd..13ea496977f8 100644 --- a/src/runtime/shell/builtin/cp.rs +++ b/src/runtime/shell/builtin/cp.rs @@ -144,7 +144,7 @@ impl Cp { } #[cfg(windows)] State::Ebusy(_) => return Self::ignore_ebusy_error_if_possible(interp, cmd), - State::WaitingWriteErr => return Yield::failed(), + State::WaitingWriteErr => return Yield::suspended(), State::Done => return Builtin::done(interp, cmd, 0), }; match action { diff --git a/src/runtime/shell/builtin/ls.rs b/src/runtime/shell/builtin/ls.rs index 082c052687a8..887352e0bf7b 100644 --- a/src/runtime/shell/builtin/ls.rs +++ b/src/runtime/shell/builtin/ls.rs @@ -168,7 +168,7 @@ impl Ls { } Yield::suspended() } - Tag::WaitingWriteErr => Yield::failed(), + Tag::WaitingWriteErr => Yield::suspended(), Tag::Done => Builtin::done(interp, cmd, 0), } } diff --git a/src/runtime/shell/builtin/mkdir.rs b/src/runtime/shell/builtin/mkdir.rs index df2515693382..a444fe3e6637 100644 --- a/src/runtime/shell/builtin/mkdir.rs +++ b/src/runtime/shell/builtin/mkdir.rs @@ -107,7 +107,7 @@ impl Mkdir { NextAction::Schedule(exec.args_start) } } - State::WaitingWriteErr => return Yield::failed(), + State::WaitingWriteErr => return Yield::suspended(), State::Done => return Builtin::done(interp, cmd, 0), }; match action { diff --git a/src/runtime/shell/builtin/mv.rs b/src/runtime/shell/builtin/mv.rs index ef318c0037e0..bfbce264cbe8 100644 --- a/src/runtime/shell/builtin/mv.rs +++ b/src/runtime/shell/builtin/mv.rs @@ -271,7 +271,7 @@ impl Mv { // Shouldn't happen — driven by batchedMoveTaskDone. Yield::suspended() } - Tag::WaitingWriteErr => Yield::failed(), + Tag::WaitingWriteErr => Yield::suspended(), Tag::Done => Builtin::done(interp, cmd, 0), Tag::Err => Builtin::done(interp, cmd, 1), } diff --git a/src/runtime/shell/builtin/touch.rs b/src/runtime/shell/builtin/touch.rs index c4ef56c0ff31..8a5ef6b02c76 100644 --- a/src/runtime/shell/builtin/touch.rs +++ b/src/runtime/shell/builtin/touch.rs @@ -95,7 +95,7 @@ impl Touch { Action::Schedule(exec.args_start) } } - State::WaitingWriteErr => return Yield::failed(), + State::WaitingWriteErr => return Yield::suspended(), State::Done => return Builtin::done(interp, cmd, 0), }; match action { diff --git a/src/runtime/shell/interpreter.rs b/src/runtime/shell/interpreter.rs index 3cdf1eba50c1..a93ab5bd1b77 100644 --- a/src/runtime/shell/interpreter.rs +++ b/src/runtime/shell/interpreter.rs @@ -332,6 +332,13 @@ impl InterpreterFlags { pub(crate) fn set_quiet(&mut self, v: bool) { if v { self.0 |= 0b10 } else { self.0 &= !0b10 } } + /// Set by [`Interpreter::take_failure`]. + pub(crate) const fn failed(self) -> bool { + self.0 & 0b100 != 0 + } + pub(crate) fn set_failed(&mut self, v: bool) { + if v { self.0 |= 0b100 } else { self.0 &= !0b100 } + } } #[repr(u8)] @@ -925,10 +932,9 @@ impl Interpreter { } } - /// For sequencing states' `child_done`: an interrupted pipeline member stops - /// where it is instead of running its next command. + /// A sequencing state stops early: Ctrl+C cut the member short, or the script failed. pub(crate) fn interrupted(&self, id: NodeId) -> bool { - self.node(id).base().is_some_and(|b| b.interrupted) + self.failed() || self.node(id).base().is_some_and(|b| b.interrupted) } /// Some ancestor is a member of a multi-command pipeline. @@ -1022,11 +1028,11 @@ impl Interpreter { Ok(id) => id, Err(e) => { self.throw(ShellErr::new_sys(&e)); - // Callers fall through as if the subshell exited 0. + // No child exists, so `parent` is the node that failed. // Return `None` so callers leave `currently_executing` // unset (no `NodeId::NONE` sentinel needed in // `deinit_node`/`free_node` for this path). - return (None, Yield::failed()); + return (None, Yield::Failed(parent)); } } } @@ -1266,7 +1272,11 @@ impl Interpreter { self.exit_code.set(Some(exit_code)); let this_jsvalue = self.this_jsvalue.get(); if this_jsvalue != JSValue::ZERO { - if let Some(resolve) = JSShellInterpreter::resolve_get_cached(this_jsvalue) { + if self.failed() { + // `fail` already rejected the promise. + self.keep_alive.with_mut(|k| k.disable()); + self.deref_root_shell_and_io_if_needed(true); + } else if let Some(resolve) = JSShellInterpreter::resolve_get_cached(this_jsvalue) { let loop_ = self.event_loop; // `global_this` is `Some` on the `EventLoopHandle::Js` path // (set by `create_shell_interpreter`); see `global_this_ref`. @@ -1332,6 +1342,86 @@ impl Interpreter { Yield::done() } + /// A node threw a JS error (`fail`): the script winds down and `finish` settles nothing. + #[inline] + pub(crate) fn failed(&self) -> bool { + self.flags.get().failed() + } + + /// Node `id` threw and holds nothing in flight: kill the subprocesses, wind the tree down, then reject (the rejection runs JS, so it comes last). + pub(crate) fn fail(&self, id: NodeId) -> Yield { + let rejection = self.take_failure(); + if self.failed() { + let node_count = self.nodes.get().len(); + for i in 0..node_count { + let cmd = NodeId(i as u32); + if matches!(self.node(cmd).kind(), StateKind::Cmd) { + Cmd::kill_subprocess(self, cmd); + } + } + } + let parent = self + .node(id) + .base() + .map_or(NodeId::INTERPRETER, |b| b.parent); + let y = self.child_done(parent, id, 1); + if let Some((reject, error)) = rejection { + let global_this = self + .global_this_ref() + .expect("take_failure returned a rejection on the Js path"); + let _entered = self.event_loop.entered(); + global_this.bun_vm().event_loop_mut().run_callback( + reject, + global_this, + crate::jsc::JSValue::UNDEFINED, + &[error], + ); + } + y + } + + /// Take the pending exception and set `failed`; `Some` when the promise still has to be rejected. + fn take_failure(&self) -> Option<(crate::jsc::JSValue, crate::jsc::JSValue)> { + use crate::jsc::JSValue; + use crate::jsc::generated::JSShellInterpreter; + + // Mini event loop: `Interpreter::throw` prints and exits instead. + let global_this = self.global_this_ref()?; + log!( + "Interpreter(0x{:x}) take failure", + std::ptr::from_ref(self) as usize + ); + + // A pending termination (`worker.terminate()`) keeps unwinding and settles nothing. + let error = if global_this.has_pending_termination_exception() { + None + } else { + let error = global_this.try_take_exception().and_then(JSValue::to_error); + debug_assert!( + error.is_some(), + "Yield::Failed without a pending JS exception" + ); + // Nothing was thrown: the node finishes with exit code 1 and the script goes on. + Some(error?) + }; + + // A second pipeline member failed: the promise is already rejected. + if self.failed() { + return None; + } + self.update_flags(|f| f.set_failed(true)); + + let error = error?; + let this_jsvalue = self.this_jsvalue.get(); + if this_jsvalue == JSValue::ZERO { + return None; + } + let reject = JSShellInterpreter::reject_get_cached(this_jsvalue); + JSShellInterpreter::resolve_set_cached(this_jsvalue, global_this, JSValue::UNDEFINED); + JSShellInterpreter::reject_set_cached(this_jsvalue, global_this, JSValue::UNDEFINED); + Some((reject?, error)) + } + /// JS-host entrypoint — sets up root IO /// (unless quiet), spawns the root `Script` node, and starts ticking. pub(crate) fn run_from_js( @@ -1441,7 +1531,7 @@ impl Interpreter { match this.cleanup_state.get() { CleanupState::NeedsFullCleanup => { - // The script is still in flight (e.g. `worker.terminate()` + // The script never reached `finish` (e.g. `worker.terminate()` // mid-command) and `Node` has no `Drop` for its raw-pointer // resources: deinit every live `Cmd` (kills the child, frees // the `ShellSubprocess`, readers, redirection fd). Slots stay diff --git a/src/runtime/shell/states/Binary.rs b/src/runtime/shell/states/Binary.rs index 7a536ca667cd..29ebc2d39624 100644 --- a/src/runtime/shell/states/Binary.rs +++ b/src/runtime/shell/states/Binary.rs @@ -77,10 +77,11 @@ impl Binary { exit_code: ExitCode, ) -> Yield { interp.deinit_node(child); + let stop = interp.interrupted(this); { let me = interp.as_binary_mut(this); me.currently_executing = None; - if me.left.is_none() && !me.base.interrupted { + if me.left.is_none() && !stop { me.left = Some(exit_code); } else { me.right = Some(exit_code); diff --git a/src/runtime/shell/states/Cmd.rs b/src/runtime/shell/states/Cmd.rs index 893313e8f953..374c4731b8d7 100644 --- a/src/runtime/shell/states/Cmd.rs +++ b/src/runtime/shell/states/Cmd.rs @@ -235,6 +235,18 @@ impl Cmd { this, <&'static str>::from(&interp.as_cmd(this).state) ); + if interp.failed() + && !matches!( + interp.as_cmd(this).state, + CmdState::WaitingWriteErr | CmdState::Done + ) + { + // The script failed: expand nothing more and do not spawn. + let me = interp.as_cmd_mut(this); + me.exit_code = Some(1); + me.state = CmdState::Done; + continue; + } match interp.as_cmd(this).state { CmdState::Idle => { if !n.assigns.is_empty() { @@ -300,7 +312,7 @@ impl Cmd { ) -> Yield { if let Some(err) = e { interp.throw(crate::shell::ShellErr::from_system(err)); - return Yield::failed(); + return Yield::Failed(this); } debug_assert!(matches!( interp.as_cmd(this).state, @@ -552,7 +564,7 @@ impl Cmd { Err(_) => { drop(spawn_args); drop(arena); - return Yield::failed(); + return Yield::Failed(this); } } @@ -879,6 +891,20 @@ impl Cmd { Self::deinit(interp, this); } + /// The script failed: stop the subprocess. Its exit finishes the Cmd through `on_exit`. + pub(crate) fn kill_subprocess(interp: &Interpreter, this: NodeId) { + let Exec::Subproc(sub) = &interp.as_cmd(this).exec else { + return; + }; + if sub.child.is_null() { + return; + } + // SAFETY: `child` was set by `spawn_async` from a + // `heap::alloc(ShellSubprocess)` and stays valid until `deinit` + // reclaims the box. Single-threaded. + let _ = unsafe { (*sub.child).try_kill(bun_core::SignalCode::SIGKILL as i32) }; + } + pub(crate) fn deinit(interp: &Interpreter, this: NodeId) { log!("Cmd {} deinit", this); let exec = { diff --git a/src/runtime/shell/states/CondExpr.rs b/src/runtime/shell/states/CondExpr.rs index a2cb9913f7a8..67d98f160790 100644 --- a/src/runtime/shell/states/CondExpr.rs +++ b/src/runtime/shell/states/CondExpr.rs @@ -235,7 +235,7 @@ impl CondExpr { return Self::write_failing_error(interp, this, format_args!("{}\n", err)); } // Defensive fallback — finish via `writeFailingError` with exit 1. - debug_assert!(false, "Expansion child failed without an error"); + debug_assert!(interp.failed(), "Expansion child failed without an error"); let parent = interp.as_condexpr(this).base.parent; return interp.child_done(parent, this, 1); } diff --git a/src/runtime/shell/states/Expansion.rs b/src/runtime/shell/states/Expansion.rs index c3a181cd3302..9798fc045cd5 100644 --- a/src/runtime/shell/states/Expansion.rs +++ b/src/runtime/shell/states/Expansion.rs @@ -215,7 +215,7 @@ impl Expansion { Err(e) => { drop(io); interp.throw(ShellErr::new_sys(&e)); - return Yield::failed(); + return Yield::Failed(this); } }; let script = Script::init(interp, duped, script_ast, this, io); @@ -600,6 +600,17 @@ impl Expansion { // Child is a Script (command substitution). Its captured stdout lives // in the duped `ShellExecEnv` it owns; read it before deinit. debug_assert!(matches!(interp.node(child).kind(), StateKind::Script)); + if interp.failed() { + // The script failed: the rest of the word is not expanded. + { + let me = interp.as_expansion_mut(this); + me.state = ExpansionState::Done; + me.child_script = None; + } + interp.deinit_node(child); + let parent = interp.as_expansion(this).base.parent; + return interp.child_done(parent, this, 1); + } // SAFETY: single trampoline frame; the child script's env (and its // parent buffer in the `Borrowed` case) has no other live borrow. let stdout = unsafe { diff --git a/src/runtime/shell/states/Pipeline.rs b/src/runtime/shell/states/Pipeline.rs index 8e15a78e31dd..143286399a2e 100644 --- a/src/runtime/shell/states/Pipeline.rs +++ b/src/runtime/shell/states/Pipeline.rs @@ -96,6 +96,14 @@ impl Pipeline { /// Starts ONE child per call; `drain_pipelines` (Yield.rs) re-enters /// `Pipeline::next` for the next one once the current child suspends. fn next_starting(interp: &Interpreter, this: NodeId, idx: u32) -> Yield { + if interp.failed() { + // A nested pipeline's member failed while this one was still starting. + if interp.as_pipeline(this).cmds.is_none() { + return Self::finish(interp, this, 1); + } + Self::release_unstarted(interp, this); + return Self::finish_if_all_exited(interp, this); + } if interp.as_pipeline(this).cmds.is_none() { debug_assert_eq!(idx, 0); if let Some(y) = Self::setup_commands(interp, this) { @@ -331,44 +339,81 @@ impl Pipeline { exit_code ); // Find the child in `cmds` and replace with its result. - let (all_done, n) = { - let me = interp.as_pipeline_mut(this); - me.exited_count += 1; - let n = me.cmds.as_ref().map(|c| c.len() as u32).unwrap_or(0); - if let Some(cmds) = &mut me.cmds { - for slot in cmds.iter_mut() { - if matches!(slot, CmdOrResult::Cmd(id) if *id == child) { - *slot = CmdOrResult::Result(exit_code); - break; - } - } - } - (me.exited_count >= n && n > 0, n) - }; + Self::record_result(interp, this, child, exit_code); // We duped a ShellExecEnv per child in `next_starting`. Cmd/If/CondExpr // do NOT free `base.shell` in their own `deinit`, so free it here. // Subshell frees its own; Assigns is skipped. Self::deinit_child_duped_env(interp, child); interp.deinit_node(child); - if all_done { - // Exit code = last command's exit code (bash semantics). - // For a single-runnable pipeline `last_exit_code` stays 0: only - // inspect `cmds[len-1]` when `len >= 2`. - let exit = { - let me = interp.as_pipeline(this); - match me.cmds.as_ref() { - Some(c) if c.len() >= 2 => match c.last() { - Some(CmdOrResult::Result(e)) => *e, - _ => 0, - }, - _ => 0, + if interp.failed() { + Self::release_unstarted(interp, this); + } + Self::finish_if_all_exited(interp, this) + } + + /// `Done` once every member reported, else keep waiting for the rest. + fn finish_if_all_exited(interp: &Interpreter, this: NodeId) -> Yield { + let me = interp.as_pipeline(this); + let Some(cmds) = me.cmds.as_deref() else { + return Yield::suspended(); + }; + if cmds.is_empty() || (me.exited_count as usize) < cmds.len() { + return Yield::suspended(); + } + // Exit code = last command's exit code (bash semantics). + // For a single-runnable pipeline `last_exit_code` stays 0: only + // inspect `cmds[len-1]` when `len >= 2`. + let exit = if cmds.len() >= 2 { + match cmds.last() { + Some(CmdOrResult::Result(e)) => *e, + _ => 0, + } + } else { + 0 + }; + interp.as_pipeline_mut(this).state = PipelineState::Done { exit_code: exit }; + Yield::Next(this) + } + + fn record_result(interp: &Interpreter, this: NodeId, child: NodeId, exit_code: ExitCode) { + let me = interp.as_pipeline_mut(this); + me.exited_count += 1; + if let Some(cmds) = &mut me.cmds { + for slot in cmds.iter_mut() { + if matches!(slot, CmdOrResult::Cmd(id) if *id == child) { + *slot = CmdOrResult::Result(exit_code); + break; } - }; - interp.as_pipeline_mut(this).state = PipelineState::Done { exit_code: exit }; - return Yield::Next(this); + } + } + } + + /// The script failed: free the members that never started so their pipe ends close. + fn release_unstarted(interp: &Interpreter, this: NodeId) { + let PipelineState::StartingCmds { idx } = interp.as_pipeline(this).state else { + return; + }; + let unstarted: Vec = interp + .as_pipeline(this) + .cmds + .as_deref() + .map(|cmds| { + cmds.iter() + .skip(idx as usize) + .filter_map(|slot| match slot { + CmdOrResult::Cmd(id) => Some(*id), + CmdOrResult::Result(_) => None, + }) + .collect() + }) + .unwrap_or_default(); + for child in unstarted { + log!("Pipeline {} release unstarted child {}", this, child); + Self::record_result(interp, this, child, 1); + Self::deinit_child_duped_env(interp, child); + interp.deinit_node(child); } - let _ = n; - Yield::suspended() + interp.as_pipeline_mut(this).state = PipelineState::Pending; } /// Free the per-child env duped in `next_starting` for child kinds that diff --git a/src/runtime/shell/subproc.rs b/src/runtime/shell/subproc.rs index a7a6afd18b58..96a931236618 100644 --- a/src/runtime/shell/subproc.rs +++ b/src/runtime/shell/subproc.rs @@ -1688,7 +1688,7 @@ impl PipeReader { fn run_yield_with(interp: *mut crate::shell::interpreter::Interpreter, y: Yield) { if interp.is_null() { debug_assert!( - matches!(y, Yield::Done | Yield::Suspended | Yield::Failed), + matches!(y, Yield::Done | Yield::Suspended), "PipeReader async callback fired without interp backref" ); return; diff --git a/test/js/bun/shell/shell-worker-terminate-leak.test.ts b/test/js/bun/shell/shell-worker-terminate-leak.test.ts index 3e7f274078bc..834015b1cf95 100644 --- a/test/js/bun/shell/shell-worker-terminate-leak.test.ts +++ b/test/js/bun/shell/shell-worker-terminate-leak.test.ts @@ -165,6 +165,24 @@ test.skipIf(!isASAN || isWindows)( LEAK_TEST_TIMEOUT, ); +test.skipIf(!isASAN || isWindows)( + "worker.terminate() while a failed Bun.$ pipeline winds down does not leak or crash", + async () => { + // The second member throws a JS error as soon as it starts. The shell + // kills the first member and rejects the promise before the child's exit + // reaches the event loop, so the terminate races the wind-down: the + // finalizer either finds the pipeline still in flight or already finished. + await runTerminateScenario(` + const running = Bun.$\`sh -c "exec sleep 100" | sh -c "true" > \${new Response("r")}\`.nothrow(); + running.then( + () => postMessage("resolved"), + () => postMessage("ok"), + ); + `); + }, + LEAK_TEST_TIMEOUT, +); + test.skipIf(!isLinux)( "worker.terminate() kills a live Bun.$ subprocess", async () => { diff --git a/test/js/bun/shell/yield.test.ts b/test/js/bun/shell/yield.test.ts index 1a47205ff514..5ec31b1ededc 100644 --- a/test/js/bun/shell/yield.test.ts +++ b/test/js/bun/shell/yield.test.ts @@ -1,5 +1,7 @@ +import { $ } from "bun"; import { describe, expect, test } from "bun:test"; -import { bunEnv, bunExe, isLinux } from "harness"; +import { bunEnv, bunExe, isLinux, tempDir } from "harness"; +import { join } from "node:path"; import { createTestBuilder } from "./test_builder"; const TestBuilder = createTestBuilder(import.meta.path); @@ -101,4 +103,274 @@ describe("yield", async () => { exitCode: 0, }); }); + + // A state can throw a JS error (here: a `${value}` redirect target the command + // cannot use, or a failed write of a "command not found" message). When the + // command is not the first thing the script runs, the trampoline is driven + // by an event-loop callback (a process exit, a thread-pool task, a pipe + // write), not by the `.run()` host call. The promise must still reject with + // the error, nothing may stay pending on the VM, a GC afterwards must be + // safe, and the process must exit on its own. + describe("a state that throws a JS error rejects the shell promise", () => { + function child(body: string) { + return [ + bunExe(), + "-e", + ` + import { $ } from "bun"; + import { heapStats } from "bun:jsc"; + import { readdirSync } from "node:fs"; + const settle = p => p.then(r => "resolved " + r.exitCode, e => "rejected " + e.constructor.name + ": " + e.message); + const bun = process.execPath; + ${body} + `, + "--debug-crash-handler-use-trace-string", + ]; + } + + async function expectRejection(shell: string, rejection: string) { + await using proc = Bun.spawn({ + cmd: child(` + const out = [await settle(${shell})]; + Bun.gc(true); + // The VM is still usable: no exception was left pending on it. + out.push(await settle($\`echo ok\`.quiet())); + Bun.gc(true); + console.log(JSON.stringify(out)); + `), + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + + expect({ result: stdout.trim(), stderr, exitCode }).toEqual({ + result: JSON.stringify([rejection, "resolved 0"]), + stderr: "", + exitCode: 0, + }); + } + + const external = "rejected TypeError: Blobs are immutable, and cannot be used for stdout/stderr"; + const builtin = "rejected Error: Cannot redirect stdout/stderr to an immutable blob. Expected a file"; + + test.concurrent("external command after another command", async () => { + await expectRejection("$`${bun} --version; ${bun} --version > ${new Response('r')}`.quiet().nothrow()", external); + }); + + test.concurrent("builtin after another command", async () => { + await expectRejection("$`${bun} --version; echo hi > ${new Blob(['x'])}`.quiet().nothrow()", builtin); + }); + + test.concurrent("builtin after a builtin that ran on the thread pool", async () => { + await expectRejection("$`ls .; echo hi > ${new Blob(['x'])}`.quiet().nothrow()", builtin); + }); + + test.concurrent("in an && chain after another command", async () => { + await expectRejection("$`${bun} --version && echo hi > ${new Blob(['x'])} && echo no`.quiet()", builtin); + }); + + test.concurrent("last member of a pipeline", async () => { + await expectRejection( + "$`${bun} --version | ${bun} --version > ${new Response('r')}`.quiet().nothrow()", + external, + ); + }); + + // This one always rejected (the error comes straight out of `.run()`), but + // the interpreter was never finished and kept the event loop alive forever. + test.concurrent("first command, and the process still exits", async () => { + await expectRejection("$`echo hi > ${new Blob(['x'])}; echo no`.quiet().nothrow()", builtin); + }); + + // No misuse of the API here: the shell's own stderr is full, so the write + // of "bun: command not found" fails, and that failure is thrown. + test.concurrent.if(isLinux)("a failed write of the command-not-found message", async () => { + await using proc = Bun.spawn({ + cmd: child(` + const out = [await settle($\`\${bun} --version > /dev/null; command-that-does-not-exist-xyz\`)]; + Bun.gc(true); + out.push(await settle($\`echo ok\`.quiet())); + console.log(JSON.stringify(out)); + `), + env: bunEnv, + stdout: "pipe", + stderr: Bun.file("/dev/full"), + }); + + const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); + + expect({ result: stdout.trim(), exitCode }).toEqual({ + result: JSON.stringify(["rejected Error: No space left on device", "resolved 0"]), + exitCode: 0, + }); + }); + + // Once every member of a failed script has exited, the interpreter must + // become collectable, not stay pinned until the process exits. + test.concurrent("failed scripts are collected", async () => { + await using proc = Bun.spawn({ + cmd: child(` + let rejected = 0; + for (let i = 0; i < 10; i++) { + await $\`ls .; echo hi > \${new Blob(["x"])}\`.quiet().then(() => {}, () => rejected++); + await $\`\${bun} --version | echo hi > \${new Blob(["x"])}\`.quiet().then(() => {}, () => rejected++); + } + let live; + for (let i = 0; i < 10; i++) { + Bun.gc(true); + live = heapStats().objectTypeCounts.ShellInterpreter ?? 0; + if (live <= 3) break; + await new Promise(resolve => setImmediate(resolve)); + } + console.log(JSON.stringify({ rejected, collected: live <= 3 ? true : live })); + `), + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + + expect({ result: stdout.trim(), stderr, exitCode }).toEqual({ + result: JSON.stringify({ rejected: 20, collected: true }), + stderr: "", + exitCode: 0, + }); + }); + + // When the member that throws is part of a pipeline, the members that + // already run must stop and the members after it must never start. Until + // that happened, a producer that wrote more than the pipe buffer blocked + // on a pipe end nobody closed, and the process never exited. + describe("the other members of the pipeline stop", () => { + // 1 MiB: more than the pipe buffer, so the write blocks until the read end closes. + const producer = "${bun} -e ${'process.stdout.write(Buffer.alloc(1 << 20, \"a\"))'}"; + const sleeper = "${bun} -e ${'setTimeout(() => {}, 100_000)'}"; + const bad = "${bun} --version > ${new Response('r')}"; + + test.concurrent("a producer that writes more than the pipe buffer", async () => { + await expectRejection(`$\`${producer} | ${bad}\`.quiet().nothrow()`, external); + }); + + test.concurrent("a member that never touches the pipe is killed", async () => { + await expectRejection(`$\`${sleeper} | ${bad}\`.quiet().nothrow()`, external); + }); + + test.concurrent("the members after the failed one never start", async () => { + await expectRejection(`$\`${producer} | ${bad} | ${sleeper} | \${bun} --version\`.quiet().nothrow()`, external); + }); + + test.concurrent("the failed member is the first one", async () => { + await expectRejection(`$\`${bad} | ${sleeper}\`.quiet().nothrow()`, external); + }); + + // The glob runs on the thread pool. When it completes, the member must + // not spawn its command. + test.concurrent("a member whose glob expansion completes after the failure", async () => { + await expectRejection(`$\`${sleeper} * | ${bad}\`.quiet().nothrow()`, external); + }); + + test.concurrent("a member inside a subshell is killed", async () => { + await expectRejection(`$\`(${sleeper}; echo no) | ${bad}\`.quiet().nothrow()`, external); + }); + + test.concurrent("a command substitution in another member is stopped", async () => { + await expectRejection(`$\`echo $(${sleeper}) | ${bad}\`.quiet().nothrow()`, external); + }); + + // The thread-pool task of `ls` completes after the failure and writes + // to a pipe whose read end is closed by then. + test.concurrent("a builtin producer on the thread pool", async () => { + await expectRejection( + `$\`ls ${"${" + JSON.stringify(import.meta.dir) + "}"} | ${bad}\`.quiet().nothrow()`, + external, + ); + }); + + test.concurrent("nothing more of the script runs", async () => { + using dir = tempDir("shell-failed-pipeline", {}); + await using proc = Bun.spawn({ + cmd: child(` + const out = [await settle($\`(${sleeper}; touch a) | ${bad}; touch b\`.quiet().nothrow())]; + out.push(JSON.stringify(readdirSync("."))); + console.log(JSON.stringify(out)); + `), + 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({ result: stdout.trim(), stderr, exitCode }).toEqual({ + result: JSON.stringify([external, "[]"]), + stderr: "", + exitCode: 0, + }); + }); + + // A ShellPromise starts when `then` is called. `expect().rejects` does + // not call it, so await the promise here. + async function rejectionOf(promise: Promise): Promise { + try { + await promise; + } catch (e) { + return e; + } + throw new Error("the shell promise resolved"); + } + + // The member that does not touch the pipe writes its pid first, and the + // failing member waits for that file in a command substitution before it + // throws. So the sleeper is alive when the script fails, and the test + // can check that it is killed and reaped afterwards. + test.concurrent("the killed member is gone after the rejection", async () => { + using dir = tempDir("shell-failed-pipeline-pid", {}); + const bun = process.execPath; + const writePid = 'require("fs").writeFileSync("pid", String(process.pid)); setTimeout(() => {}, 100_000)'; + const waitForPid = + 'while (!require("fs").existsSync("pid")) Bun.sleepSync(5); process.stdout.write("--version")'; + expect( + await rejectionOf( + $`${bun} -e ${writePid} | ${bun} $(${bun} -e ${waitForPid}) > ${new Response("r")}` + .cwd(String(dir)) + .quiet(), + ), + ).toMatchObject({ message: "Blobs are immutable, and cannot be used for stdout/stderr" }); + const pid = Number(await Bun.file(join(String(dir), "pid")).text()); + expect(pid).toBeGreaterThan(0); + // The kill is sent before the promise rejects. The shell reaps the + // child when its exit reaches the event loop, so poll for that. + const alive = () => { + try { + process.kill(pid, 0); + return true; + } catch (e) { + expect(e).toMatchObject({ code: "ESRCH" }); + return false; + } + }; + for (let i = 0; i < 1000 && alive(); i++) await Bun.sleep(10); + expect(alive()).toBe(false); + }); + + test.concurrent("two members fail: the first error rejects, the shell stays usable", async () => { + expect(await rejectionOf($`echo a > ${new Blob(["x"])} | echo b > ${new Blob(["x"])}`.quiet())).toMatchObject({ + message: "Cannot redirect stdout/stderr to an immutable blob. Expected a file", + }); + expect((await $`echo ok`.quiet().text()).trim()).toBe("ok"); + }); + + test.concurrent("not quiet: the promise rejects and the shell stays usable", async () => { + const bun = process.execPath; + expect( + await rejectionOf($`${bun} -e ${"setTimeout(() => {}, 100_000)"} | ${bun} --version > ${new Response("r")}`), + ).toMatchObject({ message: "Blobs are immutable, and cannot be used for stdout/stderr" }); + expect((await $`echo ok`.text()).trim()).toBe("ok"); + }); + }); + }); });