Skip to content
Closed
9 changes: 3 additions & 6 deletions src/js/builtins/shell.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export function createBunShellTemplateFunction(createShellInterpreter_, createParsedShellScript_) {
const createShellInterpreter = createShellInterpreter_ as (
resolve: (code: number, stdout: Buffer, stderr: Buffer) => void,
reject: (code: number, stdout: Buffer, stderr: Buffer) => void,
reject: (err: unknown) => void,
args: $ZigGeneratedClasses.ParsedShellScript,
) => $ZigGeneratedClasses.ShellInterpreter;
const createParsedShellScript = createParsedShellScript_ as (
Expand Down Expand Up @@ -108,7 +108,7 @@ export function createBunShellTemplateFunction(createShellInterpreter_, createPa
#hasRun: boolean = false;
#throws: boolean = true;
#resolve: (code: number, stdout: Buffer, stderr: Buffer) => void;
#reject: (code: number, stdout: Buffer, stderr: Buffer) => void;
#reject: (err: unknown) => void;

constructor(args: $ZigGeneratedClasses.ParsedShellScript, throws: boolean) {
// Create the error immediately so it captures the stacktrace at the point
Expand All @@ -131,10 +131,7 @@ export function createBunShellTemplateFunction(createShellInterpreter_, createPa
res(out);
}
};
reject = (code, stdout, stderr) => {
potentialError!.initialize(new ShellOutput(stdout, stderr, code), code);
rej(potentialError);
};
reject = err => rej(err);
});

this.#throws = throws;
Expand Down
9 changes: 8 additions & 1 deletion src/runtime/shell/Yield.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,14 @@
written,
err,
} => crate::shell::io_writer::on_io_writer_chunk(interp, child, written, err),
Yield::Suspended | Yield::Failed | Yield::Done => {
Yield::Failed => {
// Reject the ShellPromise and stop: do not drain pipelines,
// or downstream commands would spawn after the promise is
// already settled (hang/UAF) or throw into a cleared reject.
interp.reject_pending_exception();
return;
}

Check failure on line 148 in src/runtime/shell/Yield.rs

View check run for this annotation

Claude / Claude Code Review

Yield::Failed early-return leaks unwrapped pipeline pipe fds

The early `return` on `Yield::Failed` (04feaa7) abandons `pipeline_stack` without closing pipe ends that `Pipeline::next_starting` allocated upfront but never wrapped — for the PR's own "first in pipeline" case, `pipes[0][0]` is never handed to an `IOReader`, and since `Fd` is `Copy` (no `Drop`), it survives GC of the interpreter as a permanent kernel-fd leak. Pre-04feaa7, `drain_pipelines` would have wrapped it; the `dupe_for_subshell` error path at Pipeline.rs:236-246 has explicit `closefd()`
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
Yield::Suspended | Yield::Done => {
if let Some(y) = Self::drain_pipelines(interp, &mut pipeline_stack) {
y
} else {
Expand Down
46 changes: 43 additions & 3 deletions src/runtime/shell/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1256,6 +1256,46 @@
Ok(())
}

/// `Yield::Failed`: reject the ShellPromise with the pending exception and
/// release the keepalive. `has_pending_activity` is decremented only when
/// no spawned subprocess still holds a raw backref into us.
pub fn reject_pending_exception(&self) {
use crate::jsc::JSValue;
use crate::jsc::generated::JSShellInterpreter;
use crate::shell::states::cmd::Exec;

let Some(global) = self.global_this_ref() else {
return;
};
let Some(exc) = global.try_take_exception() else {
return;
};
let err = exc.to_error().unwrap_or(exc);
self.keep_alive.with_mut(|k| k.disable());
Comment thread
robobun marked this conversation as resolved.
Resolved
let has_live_subproc = self.nodes.get().iter().any(|n| {
matches!(n, Node::Cmd(c) if matches!(&c.exec, Exec::Subproc(s) if !s.child.is_null()))
});
if !has_live_subproc {
Self::decr_pending_activity_flag(&self.has_pending_activity);
}
Comment thread
robobun marked this conversation as resolved.
Resolved
let this_jsvalue = self.this_jsvalue.get();
let reject = (this_jsvalue != JSValue::ZERO)
.then(|| JSShellInterpreter::reject_get_cached(this_jsvalue))
.flatten()
.filter(|r| r.is_callable());
let Some(reject) = reject else {
global.report_active_exception_as_unhandled(global.throw_value(err));
return;
};
JSShellInterpreter::resolve_set_cached(this_jsvalue, global, JSValue::UNDEFINED);
JSShellInterpreter::reject_set_cached(this_jsvalue, global, JSValue::UNDEFINED);

Check failure on line 1291 in src/runtime/shell/interpreter.rs

View check run for this annotation

Claude / Claude Code Review

reject_pending_exception has no idempotency guard against cross-.run() re-entry

`reject_pending_exception()` has no "already rejected" guard, so a second `Yield::Failed` reached from a *separate* `.run()` invocation (not via `drain_pipelines`) still re-enters it: `IOWriter::on_error` / `broken_pipe_for_writers` loop over every pending child and call `run_yield()` → fresh `y.run(&interp)` per child (IOWriter.rs:826-834, 879-891, 932-945), and each `Cmd::on_io_writer_chunk` with an error does `interp.throw + Yield::failed()` — so two Cmds in `WaitingWriteErr` on the same stde
Comment thread
robobun marked this conversation as resolved.
Resolved
let loop_ = self.event_loop;
let _entered = loop_.entered();
if let Err(e) = reject.call(global, JSValue::UNDEFINED, &[err]) {
global.report_active_exception_as_unhandled(e);
}
}

pub fn finish(&self, exit_code: ExitCode) -> Yield {
use crate::jsc::JSValue;
use crate::jsc::generated::JSShellInterpreter;
Expand Down Expand Up @@ -1338,6 +1378,7 @@
);

if let Err(e) = self.setup_io_before_run() {
self.keep_alive.with_mut(|k| k.disable());
self.deref_root_shell_and_io_if_needed(true);
let shellerr = ShellErr::new_sys(&e);
return Err(throw_shell_err(
Expand All @@ -1354,9 +1395,8 @@
let root = Script::init(self, shell, ast, NodeId::INTERPRETER, io);
self.started.store(true, Ordering::SeqCst);
Script::start(self, root).run(self);
if global_this.has_exception() {
return Err(crate::jsc::JsError::Thrown);
}
// `Yield::run` rejects the promise and releases keepalive on
// `Yield::Failed`, so no post-run exception check is needed here.

Ok(crate::jsc::JSValue::UNDEFINED)
}
Expand Down
2 changes: 0 additions & 2 deletions src/runtime/shell/states/Cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -776,8 +776,6 @@ impl Cmd {
STDERR_NO as i32,
)?;
}
} else if crate::webcore::ReadableStream::from_js(jsval, global)?.is_some() {
panic!("TODO SHELL READABLE STREAM");
} else if let Some(req) = jsval.as_::<crate::webcore::Response>() {
// SAFETY: `as_` returns a live JSC-owned `*mut Response`.
let req = unsafe { &mut *req };
Expand Down
40 changes: 40 additions & 0 deletions test/js/bun/shell/bunshell.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1552,6 +1552,46 @@ describe("deno_task", () => {
TestBuilder.command`BUN_DEBUG_QUIET_LOGS=1 ${BUN} -e ${code} > /dev/null`
.quiet()
.runAsTest("bunception redirect /dev/null");

describe("ReadableStream as redirect target throws instead of panicking", () => {
test.concurrent.each([
["stdin to subprocess", `$\`\${process.execPath} -e 0 < \${stream}\``],
["stdin to subprocess (Response.body)", `$\`\${process.execPath} -e 0 < \${new Response("x").body}\``],
["stdout from subprocess", `$\`\${process.execPath} -e 0 > \${stream}\``],
["stderr from subprocess", `$\`\${process.execPath} -e 0 2> \${stream}\``],
["in pipeline", `$\`\${process.execPath} -e 0 | \${process.execPath} -e 0 < \${stream}\``],
["first in pipeline", `$\`\${process.execPath} -e 0 < \${stream} | \${process.execPath} -e 0\``],
[
"both sides of pipeline",
`$\`\${process.execPath} -e 0 < \${stream} | \${process.execPath} -e 0 < \${stream}\``,
],
["after && (async re-entry)", `$\`\${process.execPath} -e 0 && \${process.execPath} -e 0 < \${stream}\``],
])("%s", async (_, shellExpr) => {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const script = /* ts */ `
import { $ } from "bun";
const stream = new ReadableStream({ start(c) { c.close(); } });
try {
await ${shellExpr}.quiet();
console.log("no throw");
} catch (e) {
console.log("caught:", e.message);
}
Bun.gc(true);
`;
await using proc = Bun.spawn({
cmd: [bunExe(), "-e", script],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, , exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect({ stdout: stdout.trim(), exitCode, signalCode: proc.signalCode }).toEqual({
stdout: "caught: Unknown JS value used in shell: [object ReadableStream]",
exitCode: 0,
signalCode: null,
});
});
});
});

describe("pwd", async () => {
Expand Down
Loading