Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
12 changes: 12 additions & 0 deletions src/runtime/cli/run_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,18 @@ Full documentation is available at <magenta>https://bun.com/docs/cli/run<r>
}
};

if let Some(sig) = crate::shell::forward_signals::ended_script(code) {
if !silent {
pretty_errorln!(
"<r><red>error<r><d>:<r> script <b>\"{}\"<r> was terminated by signal {}<r>",
bstr::BStr::new(name),
bun_sys::SignalCode(sig as u8).fmt(Output::enable_ansi_colors_stderr()),
);
Output::flush();
}
Global::raise_ignoring_panic_handler(sig);
}

if code > 0 {
if code != 2 && !silent {
pretty_errorln!(
Expand Down
130 changes: 130 additions & 0 deletions src/runtime/shell/forward_signals.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
//! SIGTERM / SIGHUP sent to the pid of a bun-shell script runner (`bun run
//! --shell=bun`, `bun exec`, `bun x.sh`): recorded here, forwarded to the live
//! subprocesses by the interpreter between ticks, which then waits for them and
//! starts no further command. SIGINT is `bun_spawn::ctrl_c`'s (the terminal
//! signals the whole process group, so there is nothing to forward).
Comment on lines +1 to +5

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code


use core::sync::atomic::{AtomicPtr, AtomicU8, Ordering};

use bun_core::SignalCode;

/// A signal that arrived and is not forwarded yet. 0 while none.
static PENDING: AtomicU8 = AtomicU8::new(0);
/// The first signal that arrived. 0 while none. Decides the exit status.
static RECEIVED: AtomicU8 = AtomicU8::new(0);
/// Set by [`install`], cleared by [`uninstall`]. The uws loop is thread-lifetime.
static LOOP: AtomicPtr<bun_uws::Loop> = AtomicPtr::new(core::ptr::null_mut());

#[cfg(unix)]
const SIGNALS: [i32; 2] = [libc::SIGTERM, libc::SIGHUP];

/// Bit `i`: `SIGNALS[i]` is hooked. A signal inherited as `SIG_IGN` (`nohup`) is not.
#[cfg(unix)]
static HOOKED: AtomicU8 = AtomicU8::new(0);
/// Dispositions replaced by [`install`] and restored by [`uninstall`].
#[cfg(unix)]
static PREVIOUS: bun_core::RacyCell<core::mem::MaybeUninit<[libc::sigaction; 2]>> =
bun_core::RacyCell::new(core::mem::MaybeUninit::uninit());

#[cfg(unix)]
extern "C" fn handler(sig: core::ffi::c_int) {
if bun_spawn::ctrl_c::Child::alive() == 0 {
Comment thread
robobun marked this conversation as resolved.
Resolved
// Nothing to forward to (a builtin runs, or nothing): die from `sig`
// now. A builtin may never yield to the loop (`yes > /dev/null`).
// SAFETY: SIG_DFL is a valid disposition; `sig` is blocked while the
// handler runs, so unblock it for the raise to be fatal here. `raise`
// only returns for PID 1 of a pid namespace (signal discarded).
unsafe {
let mut action: libc::sigaction = bun_core::ffi::zeroed();
action.sa_sigaction = libc::SIG_DFL;
libc::sigaction(sig, &raw const action, core::ptr::null_mut());
let mut set: libc::sigset_t = bun_core::ffi::zeroed();
libc::sigemptyset(&raw mut set);
libc::sigaddset(&raw mut set, sig);
libc::pthread_sigmask(libc::SIG_UNBLOCK, &raw const set, core::ptr::null_mut());
libc::raise(sig);
libc::_exit(128 + sig);
}
}
// The wakeup write may set errno; the interrupted code must not see that.
let errno_ptr = bun_core::ffi::errno_ptr();
// SAFETY: thread-local errno slot, valid for the calling thread.
let saved = unsafe { *errno_ptr };
let sig = sig as u8;
let _ = RECEIVED.compare_exchange(0, sig, Ordering::AcqRel, Ordering::Acquire);
PENDING.store(sig, Ordering::Release);
let loop_ = LOOP.load(Ordering::Acquire);
if !loop_.is_null() {
// SAFETY: the loop is thread-lifetime and `us_wakeup_loop` is the
// thread-safe entry point (an eventfd write, no lock).
unsafe { bun_uws::us_wakeup_loop(loop_) };
}
// SAFETY: same slot.
unsafe { *errno_ptr = saved };
}

/// `loop_` is the uws loop to wake. No `SA_RESETHAND`: a repeated signal is forwarded again.
pub(crate) fn install(loop_: *mut bun_uws::Loop) {
PENDING.store(0, Ordering::Release);
RECEIVED.store(0, Ordering::Release);
LOOP.store(loop_, Ordering::Release);
#[cfg(unix)]
// SAFETY: zeroed sigaction + a handler fn is a valid disposition;
// `sigemptyset` and `sigaction` are FFI calls over valid pointers.
// `PREVIOUS` is written on this thread only, while no hook is active.
unsafe {
let mut action: libc::sigaction = bun_core::ffi::zeroed();
action.sa_sigaction = handler as *const () as usize;
libc::sigemptyset(&raw mut action.sa_mask);
action.sa_flags = libc::SA_RESTART;
let previous = (*PREVIOUS.get()).as_mut_ptr().cast::<libc::sigaction>();
let mut hooked: u8 = 0;
for (i, sig) in SIGNALS.into_iter().enumerate() {
let slot = previous.add(i);
libc::sigaction(sig, core::ptr::null(), slot);
if (*slot).sa_sigaction != libc::SIG_IGN {
libc::sigaction(sig, &raw const action, core::ptr::null_mut());
hooked |= 1 << i;
}
}
HOOKED.store(hooked, Ordering::Release);
}
}

/// Puts back the disposition each hooked signal had before [`install`].
pub(crate) fn uninstall() {
LOOP.store(core::ptr::null_mut(), Ordering::Release);
#[cfg(unix)]
{
let hooked = HOOKED.swap(0, Ordering::AcqRel);
// SAFETY: `install` filled `PREVIOUS[i]` for every bit set in `hooked`.
unsafe {
let previous = (*PREVIOUS.get()).as_ptr().cast::<libc::sigaction>();
for (i, sig) in SIGNALS.into_iter().enumerate() {
if hooked & (1 << i) != 0 {
libc::sigaction(sig, previous.add(i), core::ptr::null_mut());
}
}
}
}
}

/// The signal that arrived since the last call, if any.
pub(crate) fn take_pending() -> Option<SignalCode> {
SignalCode::from_raw(PENDING.swap(0, Ordering::AcqRel))
}

/// The first signal that arrived during the run, if any.
pub(crate) fn received() -> Option<SignalCode> {
SignalCode::from_raw(RECEIVED.load(Ordering::Acquire))
}

/// The signal the script was ended by: one arrived and was forwarded, and the
/// script's exit code is the one a shell reports for a command that signal
/// killed. A command that handled the signal and exited on its own terms
/// keeps its exit code.
Comment on lines +122 to +125

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

pub(crate) fn ended_script(exit_code: crate::shell::interpreter::ExitCode) -> Option<SignalCode> {
let sig = received()?;
let signal_exit_code = bun_sys::SignalCode(sig as u8).to_exit_code()?;
(exit_code == u16::from(signal_exit_code)).then_some(sig)
}
44 changes: 42 additions & 2 deletions src/runtime/shell/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ use crate::shell::states::pipeline::Pipeline;
use crate::shell::states::script::Script;
use crate::shell::states::stmt::Stmt;
use crate::shell::states::subshell::Subshell;
use crate::shell::subproc::ShellSubprocess;
use crate::shell::yield_::Yield;
use crate::shell::{ShellErr, ast};

Expand Down Expand Up @@ -732,6 +733,8 @@ impl Interpreter {

// ── run ────────────────────────────────────────────────────────────
interp.exit_code.set(Some(1));
// Armed before `run()`: it spawns the first command before it returns.
crate::shell::forward_signals::install(mini.loop_ptr());
if let Err(e) = interp.run() {
let name = e.name();
interp.deinit_from_exec();
Expand All @@ -751,8 +754,15 @@ impl Interpreter {
// SAFETY: `interp` lives in this stack frame for the whole tick
// loop; `flags` is `Cell<InterpreterFlags>` (interior-mutable), so
// the read is sound even while tasks `tick` drains mutate it.
unsafe { (*interp_ptr).flags.get().done() }
// `forward_signal` runs between ticks, so no task holds a borrow of
// the node arena.
Comment on lines +757 to +758

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

let interp = unsafe { &*interp_ptr };
if let Some(sig) = crate::shell::forward_signals::take_pending() {
interp.forward_signal(sig);
}
interp.flags.get().done()
});
crate::shell::forward_signals::uninstall();

let code = interp.exit_code.get().expect("exit_code set by finish()");
interp.deinit_from_exec();
Expand Down Expand Up @@ -925,10 +935,40 @@ impl Interpreter {
}
}

/// Send `sig` to every subprocess that is still running (see
/// `forward_signals`). Every command the script runs, pipeline members and
/// command substitutions included, is a `Cmd` node in the arena. Call
/// between ticks only: no callback holds a borrow of a subprocess then.
Comment on lines +938 to +941

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

pub(crate) fn forward_signal(&self, sig: bun_core::SignalCode) {
let Some(sig) = sig.platform_number() else {
return;
};
for node in self.nodes.get() {
let Node::Cmd(cmd) = node else { continue };
let crate::shell::states::cmd::Exec::Subproc(sub) = &cmd.exec else {
continue;
};
if sub.child.is_null() {
continue;
}
// SAFETY: `child` is the live `heap::alloc` subprocess owned by
// this `Cmd` until `Cmd::deinit` frees it (it is also the
// `Process`'s exit-callback context). Between ticks no callback
// holds a borrow of it.
let child: &mut ShellSubprocess = unsafe { &mut *sub.child };
if child.process.is_some() {
let _ = child.try_kill(sig);
}
}
}

/// For sequencing states' `child_done`: an interrupted pipeline member stops
/// where it is instead of running its next command.
/// where it is instead of running its next command. After a termination
/// signal (see `forward_signals`) every sequence stops, so the script ends
/// with the commands that received it.
Comment on lines +966 to +968

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

pub(crate) fn interrupted(&self, id: NodeId) -> bool {
self.node(id).base().is_some_and(|b| b.interrupted)
|| crate::shell::forward_signals::received().is_some()
}

/// Some ancestor is a member of a multi-command pipeline.
Expand Down
2 changes: 2 additions & 0 deletions src/runtime/shell/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ pub mod util;

#[path = "Builtin.rs"]
pub mod builtin;
#[path = "forward_signals.rs"]
pub(crate) mod forward_signals;
#[path = "interpreter.rs"]
pub mod interpreter;
#[path = "IO.rs"]
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 @@ -78,9 +78,10 @@ impl Binary {
) -> Yield {
interp.deinit_node(child);
{
let interrupted = 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() && !interrupted {
me.left = Some(exit_code);
} else {
me.right = Some(exit_code);
Expand Down
124 changes: 124 additions & 0 deletions test/cli/run/run-shell.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,127 @@ test.skipIf(isWindows)(
expect(exitCode).toBe(0);
},
);

// A signal sent to the runner's pid alone (kill, docker stop, systemd), not to
// the process group. proc.kill() is TerminateProcess on Windows and reaches no
// handler, so this is POSIX only. Sequential: each case starts two debug
// builds of bun, and several at once overrun the per-test budget under ASAN.
describe.skipIf(isWindows)("signal to the bun shell runner", () => {
// Prints its pid, then waits. With a signal name as its argument it handles
// that signal and exits 7. SIGUSR1 ends it with 0.
const fixture = `
const sig = process.argv[2];
if (sig) process.on(sig, () => { console.log("got " + sig); process.exit(7); });
process.on("SIGUSR1", () => process.exit(0));
console.log("ready " + process.pid);
setTimeout(() => {}, 30_000);
`;

function project(prefix: string, script: string) {
return tempDir(prefix, {
"child.js": fixture,
"package.json": JSON.stringify({ name: "p", scripts: { wait: script } }),
});
}

async function runAndSignal(cmd: string[], cwd: string, signal: "SIGTERM" | "SIGHUP", endChild = false) {
await using proc = Bun.spawn({
cmd,
cwd,
env: { ...bunEnv, NO_COLOR: "1" },
stdout: "pipe",
stderr: "pipe",
});
const ready = Promise.withResolvers<number>();
let stdout = "";
const stdoutDone = (async () => {
for await (const chunk of proc.stdout) {
stdout += new TextDecoder().decode(chunk);
const m = stdout.match(/ready (\d+)/);
if (m) ready.resolve(Number(m[1]));
}
ready.reject(new Error(`stdout ended before the child was ready:\n${stdout}`));
})();
const childPid = await ready.promise;
proc.kill(signal);
if (endChild) process.kill(childPid, "SIGUSR1");
const exitCode = await proc.exited;
// The runner waited for the child, so the child is gone once the runner is.
// An orphan still holds the stdio pipes open, so check (and end it) before
// reading them to the end.
let childAlive = true;
try {
process.kill(childPid, 0);
process.kill(childPid, "SIGKILL");
} catch {
childAlive = false;
}
const [, stderr] = await Promise.all([stdoutDone, proc.stderr.text()]);
return { stdout, stderr, exitCode, signalCode: proc.signalCode, childAlive };
}

test("bun run --shell=bun forwards SIGTERM to the command and dies from it", async () => {
using dir = project("run-shell-sigterm", `${bunExe()} child.js`);
const r = await runAndSignal([bunExe(), "run", "--shell=bun", "wait"], String(dir), "SIGTERM");
expect(r.childAlive).toBe(false);
expect(r.stderr).toContain('script "wait" was terminated by signal SIGTERM');
expect(r.signalCode).toBe("SIGTERM");
});

test("bun exec forwards SIGHUP to the command and exits 129", async () => {
using dir = project("run-shell-exec-sighup", "");
const r = await runAndSignal([bunExe(), "exec", `${bunExe()} child.js`], String(dir), "SIGHUP");
expect(r.childAlive).toBe(false);
expect(r.exitCode).toBe(129);
});

test("a command that handles the forwarded SIGTERM keeps its own exit code", async () => {
using dir = project("run-shell-sigterm-handled", `${bunExe()} child.js SIGTERM`);
const r = await runAndSignal([bunExe(), "run", "--shell=bun", "wait"], String(dir), "SIGTERM");
expect(r.childAlive).toBe(false);
expect(r.stdout).toContain("got SIGTERM");
expect(r.stderr).toContain('script "wait" exited with code 7');
expect(r.exitCode).toBe(7);
});

test("the script stops at the command that received the signal", async () => {
using dir = project("run-shell-sigterm-sequence", `${bunExe()} child.js; echo after`);
const r = await runAndSignal([bunExe(), "run", "--shell=bun", "wait"], String(dir), "SIGTERM");
expect(r.childAlive).toBe(false);
expect(r.stdout).not.toContain("after");
expect(r.signalCode).toBe("SIGTERM");
});

test("a script with no subprocess to forward to dies from the signal at once", async () => {
await using proc = Bun.spawn({
cmd: [bunExe(), "exec", "echo ready; yes > /dev/null"],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const reader = proc.stdout.getReader();
let stdout = "";
while (!stdout.includes("ready")) {
const { value, done } = await reader.read();
if (done) break;
stdout += new TextDecoder().decode(value);
}
expect(stdout).toContain("ready");
proc.kill("SIGTERM");
await proc.exited;
expect(proc.signalCode).toBe("SIGTERM");
});

test("a SIGTERM the runner inherited as ignored stays ignored", async () => {
using dir = project("run-shell-sigterm-ignored", `${bunExe()} child.js`);
const r = await runAndSignal(
["sh", "-c", 'trap "" TERM; exec "$0" run --shell=bun wait', bunExe()],
String(dir),
"SIGTERM",
true,
);
expect(r.childAlive).toBe(false);
expect(r.stderr).toBe(`$ ${bunExe()} child.js\n`);
expect(r.exitCode).toBe(0);
});
});
Loading