Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 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
12 changes: 5 additions & 7 deletions src/runtime/shell/Yield.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,9 @@ 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`). The script is over:
/// the promise is rejected and the tree winds down through `child_done`.
Comment thread
robobun marked this conversation as resolved.
Resolved
Failed(NodeId),
Done,
}

Expand All @@ -51,10 +52,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 +128,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
110 changes: 103 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,11 @@ impl Interpreter {
}
}

/// For sequencing states' `child_done`: an interrupted pipeline member stops
/// where it is instead of running its next command.
/// For sequencing states' `child_done`: an interrupted pipeline member, or
/// any node once the script failed (`fail`), stops where it is instead of
/// running its next command.
Comment thread
robobun marked this conversation as resolved.
Resolved
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 +1030,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 +1274,12 @@ 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` rejected the promise. Every member has exited, so the
// interpreter can let go of the event loop and be collected.
Comment thread
robobun marked this conversation as resolved.
Resolved
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 +1345,89 @@ impl Interpreter {
Yield::done()
}

/// The script failed with a JS error (`Yield::Failed`). The sequencing
/// states stop where they are (see `interrupted`), a pipeline frees the
/// members it did not start, and `finish` settles nothing.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[inline]
pub(crate) fn failed(&self) -> bool {
self.flags.get().failed()
}

/// `Yield::Failed(id)`: node `id` threw a JS exception and holds nothing
/// in flight. Reject the promise, stop every subprocess, and report `id`
/// to its parent as finished. The tree then winds down through the
/// normal `child_done` path, so every member that still runs reaches
/// `finish` before the interpreter lets go of the event loop.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn fail(&self, id: NodeId) -> Yield {
self.reject_with_pending_exception();
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);
self.child_done(parent, id, 1)
}

/// Take the pending JS exception and reject the `ShellPromise` with it.
fn reject_with_pending_exception(&self) {
use crate::jsc::JSValue;
use crate::jsc::generated::JSShellInterpreter;

// Mini event loop: `Interpreter::throw` prints and exits instead.
let Some(global_this) = self.global_this_ref() else {
return;
};
log!(
"Interpreter(0x{:x}) reject with pending exception",
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.
let Some(error) = error else { return };
Some(error)
};

// A second pipeline member failed: the promise is already rejected.
if self.failed() {
return;
}
self.update_flags(|f| f.set_failed(true));

let this_jsvalue = self.this_jsvalue.get();
if let Some(error) = error
&& this_jsvalue != JSValue::ZERO
{
if let Some(reject) = JSShellInterpreter::reject_get_cached(this_jsvalue) {
let _entered = self.event_loop.entered();
global_this.bun_vm().event_loop_mut().run_callback(
reject,
global_this,
JSValue::UNDEFINED,
&[error],
);
}
JSShellInterpreter::resolve_set_cached(this_jsvalue, global_this, JSValue::UNDEFINED);
JSShellInterpreter::reject_set_cached(this_jsvalue, global_this, JSValue::UNDEFINED);
}
}

/// 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 +1537,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
33 changes: 31 additions & 2 deletions src/runtime/shell/states/Cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,19 @@ 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 while an expansion of this command was in
// flight: do not expand the rest or spawn the command.
Comment thread
robobun marked this conversation as resolved.
Resolved
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 +313,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 +565,7 @@ impl Cmd {
Err(_) => {
drop(spawn_args);
drop(arena);
return Yield::failed();
return Yield::Failed(this);
}
}

Expand Down Expand Up @@ -879,6 +892,22 @@ impl Cmd {
Self::deinit(interp, this);
}

/// The script failed (`Interpreter::fail`): stop a subprocess that still
/// runs. Its exit then reaches `on_exit` and finishes the Cmd through
/// the normal path, so its pipe ends close once nothing can call back.
Comment thread
robobun marked this conversation as resolved.
Resolved
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
Loading
Loading