Skip to content
6 changes: 3 additions & 3 deletions src/runtime/api/cron.rs
Original file line number Diff line number Diff line change
Expand Up @@ -833,9 +833,9 @@ pub(crate) fn cron_register(global: &JSGlobalObject, frame: &CallFrame) -> JsRes
}
}

let bun_exe = match bun_core::self_exe_path() {
Ok(p) => p,
Err(_) => {
let bun_exe = match crate::node::process::exec_path_zstr() {
Some(p) => p,
None => {
return Err(global.throw(format_args!("Failed to get bun executable path")));
}
};
Expand Down
34 changes: 34 additions & 0 deletions src/runtime/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,38 @@ pub(crate) static Bun__Node__RedirectWarnings: std::sync::OnceLock<Box<[u8]>> =
pub(crate) static Bun__Node__DisabledWarnings: std::sync::OnceLock<Vec<Box<[u8]>>> =
std::sync::OnceLock::new();

#[allow(non_upper_case_globals)]
/// Overrides `process.execPath` / `process.argv[0]` / `npm_execpath`. Set
/// once, at bunx dispatch on Windows, when the process is `bunx.exe`, whose
/// path children cannot be spawned from (it dispatches to bunx CLI mode).
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) static Bun__Node__ExecPathOverride: std::sync::OnceLock<bun_core::ZBox> =
std::sync::OnceLock::new();

/// When the process is `bunx.exe`, record the sibling `bun.exe` as the
/// executable path before anything captures it (`npm_execpath` in the run
/// env, `process.execPath` in the in-process fast path). A child spawned
/// from `bunx.exe` re-enters bunx CLI mode (#40298). POSIX needs no
/// override: `bunx` is a symlink and `self_exe_path` resolves through it.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[cfg(windows)]
fn detect_bunx_exec_path_override() {
let Ok(self_exe) = bun::self_exe_path() else {
return;
};
let bytes = self_exe.as_bytes();
if !strings::eql_case_insensitive_ascii_check_length(bun_paths::basename(bytes), b"bunx.exe") {
return;
}
let Some(dir) = bun_paths::dirname(bytes) else {
return;
};
let mut sibling = Vec::with_capacity(dir.len() + b"\\bun.exe".len());
sibling.extend_from_slice(dir);
sibling.extend_from_slice(b"\\bun.exe");
if bun_sys::exists(&sibling) {
let _ = Bun__Node__ExecPathOverride.set(bun_core::ZBox::from_vec(sibling));
}
}

/// Backing storage for [`cli_arena`]. Written exactly once in [`Cli::start`]
/// during single-threaded process startup (before `Command::start`, hence
/// before any `cli_arena()` / `cli_dupe` caller), then read freely — same
Expand Down Expand Up @@ -1528,6 +1560,8 @@ pub mod command {
#[cold]
#[inline(never)]
fn exec_bunx(log: &mut bun_ast::Log) -> CmdResult {
#[cfg(windows)]
detect_bunx_exec_path_override();
let ctx = init(Tag::BunxCommand, log)?;
let start_idx = if IS_BUNX_EXE.load(core::sync::atomic::Ordering::Relaxed) {
0
Expand Down
47 changes: 45 additions & 2 deletions src/runtime/cli/run_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -728,10 +728,10 @@ Full documentation is available at <magenta>https://bun.com/docs/cli/run<r>

if env_loader.get(b"npm_execpath").is_none() {
// we don't care if this fails
if let Ok(self_exe_path) = bun_core::self_exe_path() {
if let Some(exec_path) = crate::node::process::exec_path_bytes() {
env_loader
.map
.put_default(b"npm_execpath", self_exe_path.as_bytes())
.put_default(b"npm_execpath", exec_path)
.expect("unreachable");
}
}
Expand Down Expand Up @@ -3998,6 +3998,48 @@ impl BunXFastPath {
bun_core::scoped_log!(BUNX_FAST_PATH_LOG, "did not start via shim");
}

/// Give the in-process launch the identity a POSIX bunx child gets by
/// exec'ing through the temp `node` shim: argv in the
/// `bun <BUN_OPTIONS> <script> <args>` shape (the `process.execArgv`
/// re-parse must not see bunx CLI flags) and argv[0] at the override
/// `cli::detect_bunx_exec_path_override` recorded (a fork of `bunx.exe`
/// re-enters bunx CLI mode, #40298).
Comment thread
robobun marked this conversation as resolved.
Resolved
fn assume_runtime_identity(script_path: &[u8], passthrough: &[Box<[u8]>]) {
fn leak_zstr(bytes: &[u8]) -> &'static ZStr {
let mut v = Vec::with_capacity(bytes.len() + 1);
v.extend_from_slice(bytes);
v.push(0);
ZStr::from_slice_with_nul(v.leak())
}

let argv0: &'static ZStr = match cli::Bun__Node__ExecPathOverride.get() {
Some(path) => path.as_zstr(),
None => match core::self_exe_path().ok() {
Some(z) => z,
None => core::argv().get(0).unwrap_or(core::zstr!("bun")),
},
};

let bun_options_argc = core::bun_options_argc();
let mut new_argv: Vec<&'static ZStr> =
Vec::with_capacity(2 + bun_options_argc + passthrough.len());
new_argv.push(argv0);
// BUN_OPTIONS tokens sit at argv[1..]; keep them so `process.execArgv`
// reports them, as the POSIX child does after its own env re-splice.
Comment thread
robobun marked this conversation as resolved.
Resolved
for i in 1..=bun_options_argc {
if let Some(z) = core::argv().get(i) {
new_argv.push(z);
}
}
new_argv.push(leak_zstr(script_path));
for arg in passthrough {
new_argv.push(leak_zstr(arg));
}
// SAFETY: single-threaded CLI dispatch, before the VM boots; no
// concurrent `argv()` readers exist yet.
unsafe { core::set_argv(core::intern_argv(new_argv)) };
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

fn direct_launch_callback(wpath: &mut [u16], ctx: bun_options_types::context::Context<'_>) {
// SAFETY: process-lifetime static, single-threaded CLI dispatch.
// `try_launch` (still on the call stack) holds live `&mut [u16]`
Expand All @@ -4014,6 +4056,7 @@ impl BunXFastPath {
::core::slice::from_raw_parts_mut(raw.cast::<u8>(), bun_paths::PATH_MAX_WIDE * 2)
};
let utf8 = strings::convert_utf16_to_utf8_in_buffer(out_buf, wpath);
Self::assume_runtime_identity(utf8, &ctx.passthrough);
if let Err(err) = RunCommand::boot(ctx, utf8.to_vec().into_boxed_slice(), None) {
// SAFETY: `ctx.log` was set in `create_context_data`.
let _ = unsafe { &mut *ctx.log }.print(std::ptr::from_mut(Output::error_writer()));
Expand Down
23 changes: 18 additions & 5 deletions src/runtime/node/node_process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,27 @@ extern "C" fn create_argv0(global_object: &JSGlobalObject) -> JSValue {
EncodedSlice::from_bytes(argv0).to_js(global_object)
}

/// `process.execPath` as a NUL-terminated `ZStr`: the CLI-set override
/// (Windows bunx in-process launch) or the resolved executable path.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn exec_path_zstr() -> Option<&'static bun_core::ZStr> {
if let Some(path) = crate::cli::Bun__Node__ExecPathOverride.get() {
return Some(path.as_zstr());
}
bun_core::self_exe_path().ok()
}

/// [`exec_path_zstr`] as bytes.
pub(crate) fn exec_path_bytes() -> Option<&'static [u8]> {
exec_path_zstr().map(|z| z.as_bytes())
}

#[unsafe(export_name = "Bun__Process__getExecPath")]
extern "C" fn get_exec_path(global_object: &JSGlobalObject) -> JSValue {
let Ok(out) = bun_core::self_exe_path() else {
let Some(out) = exec_path_bytes() else {
// if for any reason we are unable to get the executable path, we just return argv[0]
return create_argv0(global_object);
};
EncodedSlice::from_bytes(out.as_bytes()).to_js(global_object)
EncodedSlice::from_bytes(out).to_js(global_object)
}

/// A worker's `argv`/`execArgv` strings live in its parent-thread
Expand Down Expand Up @@ -359,9 +373,8 @@ mod _impl {
// Even if they didn't type "bun", we still want to add it as argv[0]
args_list.push(BunString::static_("bun"));
} else {
let exe_path = bun_core::self_exe_path().ok();
args_list.push(match exe_path {
Some(str_) => BunString::borrow_utf8(str_.as_bytes()),
args_list.push(match super::exec_path_bytes() {
Some(bytes) => BunString::borrow_utf8(bytes),
None => BunString::static_("bun"),
});
}
Expand Down
4 changes: 2 additions & 2 deletions src/runtime/shell/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1587,8 +1587,8 @@ impl Interpreter {
match event_loop {
EventLoopHandle::Js { .. } => {
if int == 0 {
if let Ok(p) = bun_core::self_exe_path() {
out.extend_from_slice(p.as_bytes());
if let Some(p) = crate::node::process::exec_path_bytes() {
out.extend_from_slice(p);
}
return;
}
Expand Down
4 changes: 1 addition & 3 deletions src/runtime/shell/states/Cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -478,9 +478,7 @@ impl Cmd {
match bun_which::which(&mut *path_buf, spawn_args.path, spawn_args.cwd, &first_arg) {
Some(z) => Some(z.as_bytes().to_vec()),
None if &first_arg[..] == b"bun" || &first_arg[..] == b"bun-debug" => {
bun_core::self_exe_path()
.ok()
.map(|z| z.as_bytes().to_vec())
crate::node::process::exec_path_bytes().map(<[u8]>::to_vec)
}
None => None,
}
Expand Down
68 changes: 66 additions & 2 deletions test/cli/install/bunx.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { spawn } from "bun";
import { afterAll, beforeAll, beforeEach, describe, expect, it, setDefaultTimeout } from "bun:test";
import { mkdir, rm, writeFile } from "fs/promises";
import { bunEnv, bunExe, isWindows, readdirSorted, tmpdirSync } from "harness";
import { chmodSync, copyFileSync, readdirSync, symlinkSync } from "node:fs";
import { bunEnv, bunExe, isWindows, readdirSorted, tempDir, tmpdirSync } from "harness";
import { chmodSync, copyFileSync, mkdirSync, readdirSync, realpathSync, symlinkSync } from "node:fs";
import { tmpdir } from "os";
import { delimiter, join, resolve } from "path";
import { dummyAfterAll, dummyBeforeAll, dummyBeforeEach, dummyRegistry, getPort, setHandler } from "./dummy.registry";
Expand Down Expand Up @@ -511,6 +511,70 @@ it.concurrent("should handle postinstall scripts correctly with symlinked bunx",
expect(exited).toBe(0);
});

// #40298: on Windows, `bunx --bun <pkg>` runs a node-shebang bin script in the
// same process instead of spawning a child. The process kept bunx's identity:
// process.execPath pointed at bunx.exe (so a fork()ed child re-entered bunx
// CLI mode) and process.execArgv carried the bunx CLI flags.
it.concurrent.skipIf(!isWindows)("bunx --bun in-process launch can fork children (#40298)", async () => {
using dir = tempDir("bunx-bun-fork", {
"package.json": JSON.stringify({ name: "repro", dependencies: { showexec: "file:./showexec" } }),
"showexec/package.json": JSON.stringify({ name: "showexec", version: "1.0.0", bin: { showexec: "cli.js" } }),
"showexec/cli.js": `#!/usr/bin/env node
console.log(JSON.stringify({ argv0: process.argv[0], execPath: process.execPath, execArgv: process.execArgv, npmExecpath: process.env.npm_execpath }));
const { fork } = require("node:child_process");
const cp = fork(require("node:path").join(__dirname, "child.js"));
cp.on("exit", code => console.log("child exit", code));
`,
"showexec/child.js": `console.log("CHILD OK");`,
});
// The defect only reproduces when the executable is named bunx.exe, so run
// a copy of the test build under that name, with a bun.exe sibling.
const exeDir = join(String(dir), "exes");
mkdirSync(exeDir);
copyFileSync(bunExe(), join(exeDir, "bun.exe"));
copyFileSync(bunExe(), join(exeDir, "bunx.exe"));

await using install = spawn({
cmd: [bunExe(), "install"],
cwd: String(dir),
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [installOut, installErr, installExit] = await Promise.all([
install.stdout.text(),
install.stderr.text(),
install.exited,
]);
expect(installErr).not.toContain("error:");
expect(installExit).toBe(0);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// An inherited npm_execpath (the test runner sets one) would win over the
// bunx-set default, so strip it.
const bunxEnv = { ...bunEnv, BUN_OPTIONS: "--smol" };
delete bunxEnv.npm_execpath;
await using proc = spawn({
cmd: [join(exeDir, "bunx.exe"), "--bun", "--no-install", "showexec"],
cwd: String(dir),
env: bunxEnv,
stdout: "pipe",
stderr: "pipe",
});
const [out, err, exited] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

const state = JSON.parse(out.slice(0, out.indexOf("\n")));
const bunExePath = realpathSync(join(exeDir, "bun.exe")).toLowerCase();
expect(realpathSync(state.execPath).toLowerCase()).toBe(bunExePath);
expect(realpathSync(state.argv0).toLowerCase()).toBe(bunExePath);
expect(realpathSync(state.npmExecpath).toLowerCase()).toBe(bunExePath);
// BUN_OPTIONS flags stay in execArgv; the bunx CLI flags must not.
expect(state.execArgv).toEqual(["--smol"]);
expect(out).toContain("CHILD OK");
expect(out).toContain("child exit 0");
expect(err).not.toContain("error:");
expect(exited).toBe(0);
});

// Pinned to 20: its engines are "^20.19.0 || ^22.12.0 || >=24.0.0", so the node-24
// requirement this test exercises holds no matter what Node.js version Bun reports.
// @latest tracks Angular's engines upward and breaks whenever they outrun us.
Expand Down
Loading