Skip to content
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/js/builtins/shell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
14 changes: 7 additions & 7 deletions src/runtime/shell/Builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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];

Expand All @@ -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 };
}
Expand All @@ -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() {
Expand All @@ -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(),
Expand All @@ -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() => {
Expand Down
1 change: 0 additions & 1 deletion src/runtime/shell/IOReader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand Down
11 changes: 4 additions & 7 deletions src/runtime/shell/Yield.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}

Expand All @@ -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! {
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/shell/builtin/cat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ impl Cat {
});
reader.start()
}
Branch::WaitingErr => Yield::failed(),
Branch::WaitingErr => Yield::suspended(),
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/runtime/shell/builtin/cp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/shell/builtin/ls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ impl Ls {
}
Yield::suspended()
}
Tag::WaitingWriteErr => Yield::failed(),
Tag::WaitingWriteErr => Yield::suspended(),
Tag::Done => Builtin::done(interp, cmd, 0),
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/shell/builtin/mkdir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/shell/builtin/mv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
}
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/shell/builtin/touch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
104 changes: 97 additions & 7 deletions src/runtime/shell/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::reject_with_pending_exception`].
Comment thread
robobun marked this conversation as resolved.
Resolved
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)]
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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));
}
}
}
Expand Down Expand Up @@ -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`.
Expand Down Expand Up @@ -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],
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
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(
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion src/runtime/shell/states/Binary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
30 changes: 28 additions & 2 deletions src/runtime/shell/states/Cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -552,7 +564,7 @@ impl Cmd {
Err(_) => {
drop(spawn_args);
drop(arena);
return Yield::failed();
return Yield::Failed(this);
}
}

Expand Down Expand Up @@ -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 = {
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/shell/states/CondExpr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
Loading
Loading