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
4 changes: 1 addition & 3 deletions src/runtime/shell/Builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -799,9 +799,7 @@ impl Builtin {

/// Sets the owning Cmd's state to
/// `WaitingWriteErr` and writes to the *Cmd's* `io.stderr` (not the
/// builtin's, which may already have been redirected). Hoisted here
/// because `init_redirections` and `Cmd::transition_to_exec` (the
/// "command not found" / spawn-error paths) are the only callers.
/// builtin's, which may already have been redirected).
pub(crate) fn cmd_write_failing_error(
interp: &Interpreter,
cmd: NodeId,
Expand Down
22 changes: 22 additions & 0 deletions src/runtime/shell/states/Cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ pub struct Cmd {
pub(crate) redirection_fd: Option<*mut CowFd>,
pub(crate) exec: Exec,
pub(crate) exit_code: Option<ExitCode>,
/// The wait for the subprocess failed, so it has no exit status. `Done`
/// reports this on stderr and the command exits with 1.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) wait_error: Option<bun_sys::Error>,
}

#[derive(Default, strum::IntoStaticStr)]
Expand Down Expand Up @@ -216,6 +219,7 @@ impl Cmd {
redirection_fd: None,
exec: Exec::None,
exit_code: None,
wait_error: None,
}))
}

Expand Down Expand Up @@ -293,6 +297,24 @@ impl Cmd {
}
CmdState::WaitingWriteErr => return Yield::suspended(),
CmdState::Done => {
if let Some(err) = interp.as_cmd_mut(this).wait_error.take() {
let argv0 = interp
.as_cmd(this)
.args
.first()
.map(|a| &a[..a.len().saturating_sub(1)])
.unwrap_or(b"<unknown>")
.to_vec();
return Builtin::cmd_write_failing_error(
interp,
this,
format_args!(
"bun: failed to wait for {}: {}\n",
bstr::BStr::new(&argv0),
err.to_shell_system_error().message,
),
);
}
let exit = interp.as_cmd(this).exit_code.unwrap_or(0);
let parent = interp.as_cmd(this).base.parent;
return interp.child_done(parent, this, exit);
Expand Down
5 changes: 4 additions & 1 deletion src/runtime/shell/subproc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -942,7 +942,7 @@ impl ShellSubprocess {
}

if matches!(status, Status::Err(_)) {
// TODO: handle error
break 'brk Some(1);
}

if matches!(status, Status::Signaled(_)) {
Comment thread
robobun marked this conversation as resolved.
Resolved
Expand All @@ -961,6 +961,9 @@ impl ShellSubprocess {
// before the Yield runs.
let cmd = unsafe { handle.cmd_mut() };
cmd.base.interrupted |= interrupted;
if let Status::Err(err) = status {
cmd.wait_error = Some(err.clone());
}
let y = cmd.on_exit(code.into());
// May free `*this`.
y.run(&handle.interp);
Expand Down
101 changes: 83 additions & 18 deletions test/js/bun/shell/shell-hang.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { dlopen } from "bun:ffi";
import { describe, expect, test } from "bun:test";
import { bunRun } from "harness";
import { bunEnv, bunExe, bunRun, isLinux, isWindows, libcPathForDlopen } from "harness";
import path from "path";

// Pass by not hanging
Expand All @@ -17,24 +18,88 @@ const pass = [
];

describe("fail", () => {
test.concurrent.each(fail)(
"%s",
async fixture => {
const { exitCode } = await bunRun(path.join(import.meta.dir, fixture));
expect(exitCode).not.toBe(0);
},
700,
);
test.concurrent.each(fail)("%s", async fixture => {
const { exitCode } = await bunRun(path.join(import.meta.dir, fixture));
expect(exitCode).not.toBe(0);
});
});

describe("pass", () => {
test.concurrent.each(pass)(
"%s",
async fixture => {
const { stderr, exitCode } = await bunRun(path.join(import.meta.dir, fixture));
if (exitCode !== 0) console.error(stderr);
expect(exitCode).toBe(0);
},
700,
);
test.concurrent.each(pass)("%s", async fixture => {
const { stderr, exitCode } = await bunRun(path.join(import.meta.dir, fixture));
if (exitCode !== 0) console.error(stderr);
expect(exitCode).toBe(0);
});
});

// Without pidfd_open (a seccomp profile can block it) bun on Linux waits for
// children on a second thread. That thread reaps the command before the test's
// waitpid() can, so the wait cannot be made to fail there.
function hasPidfdOpen() {
const libc = dlopen(libcPathForDlopen(), {
syscall: { args: ["i64", "i32", "u32"], returns: "i64" },
close: { args: ["i32"], returns: "i32" },
});
const SYS_pidfd_open = 434;
const pidfd = Number(libc.symbols.syscall(SYS_pidfd_open, process.pid, 0));
if (pidfd >= 0) libc.symbols.close(pidfd);
libc.close();
return pidfd >= 0;
}
const canForceFailedWait = !isWindows && (!isLinux || hasPidfdOpen());

// Other code in the process (here a blocking waitpid(-1) through bun:ffi) reaps
// the command first. bun's own wait then fails with ECHILD, and the exit status
// is gone.
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
//
// Not concurrent: if this case times out, its child never exits, and the runner
// kills the child of a timed-out test only when the test is not concurrent.
test.skipIf(!canForceFailedWait)("a command whose wait fails still completes", async () => {
const script = /* js */ `
import { $ } from "bun";
import { dlopen, ptr } from "bun:ffi";

const { waitpid } = dlopen(${JSON.stringify(libcPathForDlopen())}, {
waitpid: { args: ["i32", "ptr", "i32"], returns: "i32" },
}).symbols;

const results = {};
for (const quiet of [true, false]) {
// then() starts the command, so its process exists when waitpid() blocks.
const pending = $\`sh -c "echo out; echo err >&2; exit 3"\`.nothrow().quiet(quiet).then(r => r);
const status = new Int32Array(1);
const reaped = waitpid(-1, ptr(status), 0) > 0;
Comment thread
robobun marked this conversation as resolved.
Resolved
const { exitCode, stdout, stderr } = await pending;
results[quiet ? "quiet" : "loud"] = {
reaped,
reapedExitCode: (status[0] >> 8) & 0xff,
exitCode,
stdout: stdout.toString(),
stderr: stderr.toString(),
};
}
console.log(JSON.stringify(results));
`;

// This flag forces the second-thread wait that the script has to avoid.
const { BUN_FEATURE_FLAG_FORCE_WAITER_THREAD: _, ...env } = bunEnv;
await using proc = Bun.spawn({
cmd: [bunExe(), "-e", script],
env,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

const waitFailed = {
reaped: true,
reapedExitCode: 3,
exitCode: 1,
stdout: "out\n",
stderr: `err\nbun: failed to wait for ${Bun.which("sh")}: No child processes\n`,
};
// Only the loud run also writes through to the real stdout and stderr.
expect(stderr).toBe(waitFailed.stderr);
expect(stdout).toBe("out\n" + JSON.stringify({ quiet: waitFailed, loud: waitFailed }) + "\n");
expect(exitCode).toBe(0);
});
Loading