From a317253a2adfea29924ef822feb8fd6e94ca4ac3 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 20 Sep 2026 21:16:24 +0000 Subject: [PATCH 1/5] install.sh: fall back to wget and to other zip extractors The install script now downloads with wget when curl is missing, and extracts the release zip with busybox, 7z, 7zz, 7za, bsdtar, or python3 when unzip is missing. bun upgrade probes the same extractors and sets the executable bit after extraction, because python3's zipfile module does not restore it. --- src/runtime/cli/install.sh | 50 +++++++++-- src/runtime/cli/upgrade_command.rs | 120 ++++++++++++++++++++++++--- test/cli/install/bun-upgrade.test.ts | 105 +++++++---------------- test/cli/install/fake-release.ts | 95 +++++++++++++++++++++ test/cli/install/install-sh.test.ts | 83 ++++++++++++++++++ 5 files changed, 359 insertions(+), 94 deletions(-) create mode 100644 test/cli/install/fake-release.ts create mode 100644 test/cli/install/install-sh.test.ts diff --git a/src/runtime/cli/install.sh b/src/runtime/cli/install.sh index b338bd03cdee..b5ba3613e4d9 100644 --- a/src/runtime/cli/install.sh +++ b/src/runtime/cli/install.sh @@ -53,8 +53,24 @@ success() { echo -e "${Green}$@ ${Color_Off}" } -command -v unzip >/dev/null || - error 'unzip is required to install bun' +if command -v curl >/dev/null; then + download_cmd=curl +elif command -v wget >/dev/null; then + download_cmd=wget +else + error 'curl or wget is required to install bun' +fi + +unzip_cmd='' +for cmd in unzip busybox 7z 7zz 7za bsdtar python3; do + if command -v "$cmd" >/dev/null; then + unzip_cmd=$cmd + break + fi +done + +[[ $unzip_cmd ]] || + error 'unzip is required to install bun (7z, busybox, bsdtar, python3 supported)' if [[ $# -gt 2 ]]; then error 'Too many arguments, only 2 are allowed. The first can be a specific tag of bun to install. (e.g. "bun-v0.1.4") The second can be a build variant of bun to install. (e.g. "debug-info")' @@ -146,11 +162,33 @@ if [[ ! -d $bin_dir ]]; then error "Failed to create install directory \"$bin_dir\"" fi -curl --fail --location --progress-bar --output "$exe.zip" "$bun_uri" || - error "Failed to download bun from \"$bun_uri\"" +case $download_cmd in +curl) + curl --fail --location --progress-bar --output "$exe.zip" "$bun_uri" + ;; +wget) + wget -q -O "$exe.zip" "$bun_uri" + ;; +esac || error "Failed to download bun from \"$bun_uri\"" -unzip -oqd "$bin_dir" "$exe.zip" || - error 'Failed to extract bun' +# python3's zipfile does not restore the file mode; the chmod below covers it. +case $unzip_cmd in +unzip) + unzip -oqd "$bin_dir" "$exe.zip" + ;; +busybox) + busybox unzip -oq "$exe.zip" -d "$bin_dir" + ;; +7z | 7zz | 7za) + "$unzip_cmd" x -y -o"$bin_dir" "$exe.zip" >/dev/null + ;; +bsdtar) + bsdtar -xf "$exe.zip" -C "$bin_dir" + ;; +python3) + python3 -m zipfile -e "$exe.zip" "$bin_dir" + ;; +esac || error 'Failed to extract bun' mv "$bin_dir/bun-$target/$exe_name" "$exe" || error 'Failed to move extracted bun to destination' diff --git a/src/runtime/cli/upgrade_command.rs b/src/runtime/cli/upgrade_command.rs index ac8bcf2d8c72..56e9a7eb0a11 100644 --- a/src/runtime/cli/upgrade_command.rs +++ b/src/runtime/cli/upgrade_command.rs @@ -63,6 +63,91 @@ fn argv_contains(target: &[u8]) -> bool { bun_core::argv().iter().any(|a| a == target) } +/// A program that can extract the release zip on POSIX. `before` and `after` +/// are the arguments placed around the archive path. The archive is extracted +/// into the current directory. +#[cfg(unix)] +struct UnzipProgram { + bin: &'static [u8], + before: &'static [&'static [u8]], + after: &'static [&'static [u8]], + /// Whether the program restores the Unix file mode stored in the zip. + restores_mode: bool, +} + +/// The extractors `bun upgrade` accepts, in probe order. +/// +/// We could just embed libz2, however we want to be sure that xattrs are +/// preserved. xattrs are used for codesigning and it'd be easy to mess that up. +#[cfg(unix)] +const UNZIP_PROGRAMS: &[UnzipProgram] = &[ + UnzipProgram { + bin: b"unzip", + before: &[b"-q", b"-o"], + after: &[], + restores_mode: true, + }, + UnzipProgram { + bin: b"busybox", + before: &[b"unzip", b"-q", b"-o"], + after: &[], + restores_mode: true, + }, + UnzipProgram { + bin: b"7z", + before: &[b"x", b"-y"], + after: &[], + restores_mode: true, + }, + UnzipProgram { + bin: b"7zz", + before: &[b"x", b"-y"], + after: &[], + restores_mode: true, + }, + UnzipProgram { + bin: b"7za", + before: &[b"x", b"-y"], + after: &[], + restores_mode: true, + }, + UnzipProgram { + bin: b"bsdtar", + before: &[b"-xf"], + after: &[], + restores_mode: true, + }, + UnzipProgram { + bin: b"python3", + before: &[b"-m", b"zipfile", b"-e"], + after: &[b"."], + restores_mode: false, + }, +]; + +/// Resolves the first entry of `UNZIP_PROGRAMS` found in `path` and returns it +/// with the argv that extracts `archive`. +#[cfg(unix)] +fn find_unzip_argv( + path: &[u8], + cwd: &[u8], + archive: &[u8], +) -> Option<(&'static UnzipProgram, Vec>)> { + let mut buf = bun_paths::path_buffer_pool::get(); + for program in UNZIP_PROGRAMS { + let Some(exe) = which(&mut buf, path, cwd, program.bin) else { + continue; + }; + let mut argv = Vec::with_capacity(program.before.len() + program.after.len() + 2); + argv.push(Box::<[u8]>::from(exe.as_bytes())); + argv.extend(program.before.iter().map(|a| Box::<[u8]>::from(*a))); + argv.push(Box::<[u8]>::from(archive)); + argv.extend(program.after.iter().map(|a| Box::<[u8]>::from(*a))); + return Some((program, argv)); + } + None +} + // ────────────────────────────────────────────────────────────────────────── pub struct Version { @@ -816,29 +901,20 @@ impl UpgradeCommand { #[cfg(unix)] { - let mut unzip_path_buf = bun_paths::path_buffer_pool::get(); - let Some(unzip_exe) = which( - &mut unzip_path_buf, + let Some((unzip_program, unzip_argv)) = find_unzip_argv( env_loader.map.get(b"PATH").unwrap_or(b""), filesystem.top_level_dir, - b"unzip", + tmpname.as_bytes(), ) else { let _ = sys::unlinkat(&save_dir, tmpname); bun_core::pretty_errorln!( - "error: Failed to locate \"unzip\" in PATH. bun upgrade needs \"unzip\" to work." + "error: Failed to locate \"unzip\" in PATH. bun upgrade needs \"unzip\" to work (7z, busybox, bsdtar, python3 supported)." ); Global::exit(1); }; - // We could just embed libz2 - // however, we want to be sure that xattrs are preserved - // xattrs are used for codesigning - // it'd be easy to mess that up - let unzip_argv: [&[u8]; 4] = - [unzip_exe.as_bytes(), b"-q", b"-o", tmpname.as_bytes()]; - let unzip_result = match spawn_sync::spawn(&spawn_sync::Options { - argv: build_argv(&unzip_argv), + argv: unzip_argv, envp: None, cwd: Box::<[u8]>::from(&tmpdir_path_buf[..tmpdir_path_len]), stdin: spawn_sync::SyncStdio::Inherit, @@ -883,6 +959,24 @@ impl UpgradeCommand { Global::exit(1); } } + + if !unzip_program.restores_mode { + // We already chdir'd to tmpdir, so the relative `exe` path works. + let exe_z: &ZStr = ZStr::from_static(if use_profile { + const_format::concatcp!(UpgradeCommand::PROFILE_EXE_SUBPATH, "\0") + .as_bytes() + } else { + const_format::concatcp!(UpgradeCommand::EXE_SUBPATH, "\0").as_bytes() + }); + if let Err(err) = sys::chmod(exe_z, 0o755) { + bun_core::pretty_errorln!( + "error: Failed to set permissions on {} due to {}.", + bstr::BStr::new(exe), + bstr::BStr::new(err.name()) + ); + Global::exit(1); + } + } } #[cfg(windows)] { diff --git a/test/cli/install/bun-upgrade.test.ts b/test/cli/install/bun-upgrade.test.ts index 6857b47e84b5..49332e2fd19d 100644 --- a/test/cli/install/bun-upgrade.test.ts +++ b/test/cli/install/bun-upgrade.test.ts @@ -5,6 +5,7 @@ import { bunExe, bunEnv as env, isMusl, isWindows, tempDir, tls, tmpdirSync } fr import { existsSync, statSync } from "node:fs"; import { copyFile, writeFile } from "node:fs/promises"; import { basename, join } from "path"; +import { makeZipStored, restrictedPathDir } from "./fake-release"; const { openTempDirWithoutSharingDelete, closeTempDirHandle } = upgrade_test_helpers; // Cover every platform/arch/abi/cpu combination so the asset list matches @@ -23,81 +24,6 @@ function allAssetNames(profile = false) { return names; } -// Build a minimal ZIP archive with a single stored (uncompressed) entry. -// `unzip -o` on POSIX restores the mode from the Unix external-attrs field; -// Expand-Archive on Windows ignores it. -function makeZipStored(entryName: string, data: Buffer, unixMode: number): Buffer { - const nameBytes = Buffer.from(entryName, "utf8"); - const crc = Bun.hash.crc32(data); - const size = data.length; - - const lfhLen = 30 + nameBytes.length; - const cdhLen = 46 + nameBytes.length; - const cdOffset = lfhLen + size; - - const buf = Buffer.alloc(lfhLen + size + cdhLen + 22); - let p = 0; - const u16 = (v: number) => { - buf.writeUInt16LE(v, p); - p += 2; - }; - const u32 = (v: number) => { - buf.writeUInt32LE(v >>> 0, p); - p += 4; - }; - const raw = (b: Buffer) => { - b.copy(buf, p); - p += b.length; - }; - - // Local file header - u32(0x04034b50); - u16(20); // version needed - u16(0); // flags - u16(0); // method: stored - u16(0); // mtime - u16(0); // mdate - u32(crc); - u32(size); - u32(size); - u16(nameBytes.length); - u16(0); - raw(nameBytes); - raw(data); - - // Central directory header - u32(0x02014b50); - u16((3 << 8) | 20); // made by: Unix, spec 2.0 - u16(20); - u16(0); - u16(0); - u16(0); - u16(0); - u32(crc); - u32(size); - u32(size); - u16(nameBytes.length); - u16(0); - u16(0); - u16(0); - u16(0); - u32((0o100000 | unixMode) << 16); - u32(0); // LFH offset - raw(nameBytes); - - // End of central directory - u32(0x06054b50); - u16(0); - u16(0); - u16(1); - u16(1); - u32(cdhLen); - u32(cdOffset); - u16(0); - - return buf; -} - // Write a release zip for the current target that, once unpacked, yields an // executable at the path `bun upgrade` verifies. On POSIX a shell script is // enough because `unzip` preserves the mode bits; on Windows the verify step @@ -297,6 +223,35 @@ it("completes against a locally-served release with the system temp dir held ope expect(exitCode).toBe(0); }); +// Minimal hosts often lack `unzip`. `bun upgrade` then falls back to other +// extractors; python3 is the one most often present. Its zipfile module does +// not restore the file mode, so the upgrade has to set it before verification. +const python3OnlyPath = isWindows ? null : restrictedPathDir(["python3"], ["python3"]); +it.skipIf(!python3OnlyPath)("extracts the release archive with python3 when unzip is not in PATH", async () => { + const version = "9.9.9"; + const cwd = tmpdirSync(); + const execPath = join(cwd, basename(bunExe())); + const zipPath = join(cwd, "release.zip"); + await Promise.all([copyFile(bunExe(), execPath), writeFakeReleaseZip(zipPath, version)]); + + using server = startReleaseServer({ tagName: `bun-v${version}`, zipPath }); + + await using proc = Bun.spawn({ + cmd: [execPath, "upgrade", "--stable"], + cwd, + stdout: null, + stdin: "pipe", + stderr: "pipe", + env: { ...server.env, PATH: python3OnlyPath! }, + }); + + const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]); + + expect(stderr).not.toContain("error:"); + expect(stderr).toContain("Upgraded."); + expect(exitCode).toBe(0); +}); + it("recreates the staging directory in the temp dir instead of reusing a pre-existing one", async () => { const tagName = "bun-v9.9.9"; // Simulate a directory that already exists at the predictable staging path diff --git a/test/cli/install/fake-release.ts b/test/cli/install/fake-release.ts new file mode 100644 index 000000000000..a8b20c6fa350 --- /dev/null +++ b/test/cli/install/fake-release.ts @@ -0,0 +1,95 @@ +import { tmpdirSync } from "harness"; +import { symlinkSync } from "node:fs"; +import { join } from "node:path"; + +// Build a minimal ZIP archive with a single stored (uncompressed) entry. +// `unzip -o` on POSIX restores the mode from the Unix external-attrs field; +// Expand-Archive on Windows ignores it. +export function makeZipStored(entryName: string, data: Buffer, unixMode: number): Buffer { + const nameBytes = Buffer.from(entryName, "utf8"); + const crc = Bun.hash.crc32(data); + const size = data.length; + + const lfhLen = 30 + nameBytes.length; + const cdhLen = 46 + nameBytes.length; + const cdOffset = lfhLen + size; + + const buf = Buffer.alloc(lfhLen + size + cdhLen + 22); + let p = 0; + const u16 = (v: number) => { + buf.writeUInt16LE(v, p); + p += 2; + }; + const u32 = (v: number) => { + buf.writeUInt32LE(v >>> 0, p); + p += 4; + }; + const raw = (b: Buffer) => { + b.copy(buf, p); + p += b.length; + }; + + // Local file header + u32(0x04034b50); + u16(20); // version needed + u16(0); // flags + u16(0); // method: stored + u16(0); // mtime + u16(0); // mdate + u32(crc); + u32(size); + u32(size); + u16(nameBytes.length); + u16(0); + raw(nameBytes); + raw(data); + + // Central directory header + u32(0x02014b50); + u16((3 << 8) | 20); // made by: Unix, spec 2.0 + u16(20); + u16(0); + u16(0); + u16(0); + u16(0); + u32(crc); + u32(size); + u32(size); + u16(nameBytes.length); + u16(0); + u16(0); + u16(0); + u16(0); + u32((0o100000 | unixMode) << 16); + u32(0); // LFH offset + raw(nameBytes); + + // End of central directory + u32(0x06054b50); + u16(0); + u16(0); + u16(1); + u16(1); + u32(cdhLen); + u32(cdOffset); + u16(0); + + return buf; +} + +// Build a PATH that holds only the named programs (those found on this host), +// so a test can run the installer or `bun upgrade` on a host that appears to +// lack `curl` or `unzip`. Returns the directory, or null when a required +// program is missing on this host. +export function restrictedPathDir(programs: string[], required: string[] = []): string | null { + const dir = tmpdirSync("bun-restricted-path"); + for (const name of programs) { + const found = Bun.which(name); + if (!found) { + if (required.includes(name)) return null; + continue; + } + symlinkSync(found, join(dir, name)); + } + return dir; +} diff --git a/test/cli/install/install-sh.test.ts b/test/cli/install/install-sh.test.ts new file mode 100644 index 000000000000..af8ae91dad8e --- /dev/null +++ b/test/cli/install/install-sh.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, test } from "bun:test"; +import { bunEnv, isWindows, tmpdirSync } from "harness"; +import { statSync } from "node:fs"; +import { join } from "node:path"; +import { makeZipStored, restrictedPathDir } from "./fake-release"; + +const installScript = join(import.meta.dir, "../../../src/runtime/cli/install.sh"); + +// Everything install.sh runs besides the download and extract programs. +const baseTools = ["bash", "uname", "mkdir", "mv", "chmod", "rm", "basename", "grep", "cat", "sysctl"]; + +// Serves any `bun-.zip` the installer asks for, with a shell script in +// place of the binary. The folder name inside the zip must match the target +// the installer computed, so it is taken from the request. +function startReleaseServer() { + return Bun.serve({ + port: 0, + fetch(req) { + const match = /\/(bun-[^/]+)\.zip$/.exec(new URL(req.url).pathname); + if (!match) return new Response("not found", { status: 404 }); + const script = Buffer.from("#!/bin/sh\necho fake-bun\n"); + return new Response(makeZipStored(`${match[1]}/bun`, script, 0o644), { + headers: { "Content-Type": "application/zip" }, + }); + }, + }); +} + +async function runInstaller(pathDir: string) { + using server = startReleaseServer(); + const home = tmpdirSync("bun-install-sh-home"); + const installDir = join(home, ".bun"); + await using proc = Bun.spawn({ + cmd: ["bash", installScript], + env: { + ...bunEnv, + PATH: pathDir, + HOME: home, + SHELL: "/bin/sh", + BUN_INSTALL: installDir, + GITHUB: `http://${server.hostname}:${server.port}`, + }, + cwd: home, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { stdout, stderr, exitCode, exe: join(installDir, "bin", "bun") }; +} + +describe.skipIf(isWindows).concurrent("install.sh", () => { + const wgetPath = restrictedPathDir([...baseTools, "wget", "unzip"], ["wget", "unzip"]); + test.skipIf(!wgetPath)("downloads with wget when curl is missing", async () => { + const { stdout, stderr, exitCode, exe } = await runInstaller(wgetPath!); + expect(stderr).not.toContain("error"); + expect(stdout).toContain("bun was installed successfully"); + expect(statSync(exe).mode & 0o111).not.toBe(0); + expect(exitCode).toBe(0); + }); + + const python3Path = restrictedPathDir([...baseTools, "curl", "python3"], ["curl", "python3"]); + test.skipIf(!python3Path)("extracts with python3 when unzip is missing", async () => { + const { stdout, stderr, exitCode, exe } = await runInstaller(python3Path!); + expect(stderr).not.toContain("error"); + expect(stdout).toContain("bun was installed successfully"); + expect(statSync(exe).mode & 0o111).not.toBe(0); + expect(exitCode).toBe(0); + }); + + const noDownloaderPath = restrictedPathDir([...baseTools, "unzip"], ["unzip"]); + test.skipIf(!noDownloaderPath)("reports when neither curl nor wget exists", async () => { + const { stderr, exitCode } = await runInstaller(noDownloaderPath!); + expect(stderr).toContain("curl or wget is required to install bun"); + expect(exitCode).toBe(1); + }); + + const noExtractorPath = restrictedPathDir([...baseTools, "curl"], ["curl"]); + test.skipIf(!noExtractorPath)("reports when no archive extractor exists", async () => { + const { stderr, exitCode } = await runInstaller(noExtractorPath!); + expect(stderr).toContain("unzip is required to install bun (7z, busybox, bsdtar, python3 supported)"); + expect(exitCode).toBe(1); + }); +}); From 9abdbd584d64d7e2c148a427dee97e9e307c6cdc Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 20 Sep 2026 22:17:55 +0000 Subject: [PATCH 2/5] Lint the extractor list shared by install.sh and bun upgrade Add a source lint that checks the probe order and the error text in install.sh against the UNZIP_PROGRAMS table. Update the install docs and the comment that explains why bun upgrade shells out. --- .github/workflows/source-lints.yml | 2 + docs/installation.mdx | 2 +- src/runtime/cli/upgrade_command.rs | 7 ++-- .../source-lints/install-extractors.test.ts | 42 +++++++++++++++++++ 4 files changed, 48 insertions(+), 5 deletions(-) create mode 100644 test/internal/source-lints/install-extractors.test.ts diff --git a/.github/workflows/source-lints.yml b/.github/workflows/source-lints.yml index 5af3365ed742..8d9accb73705 100644 --- a/.github/workflows/source-lints.yml +++ b/.github/workflows/source-lints.yml @@ -13,6 +13,7 @@ on: branches: [main] paths: - "src/**/*.rs" + - "src/runtime/cli/install.sh" - "src/**/*.h" - "src/**/*.cpp" - "src/**/*.classes.ts" @@ -37,6 +38,7 @@ on: pull_request: paths: - "src/**/*.rs" + - "src/runtime/cli/install.sh" - "src/**/*.h" - "src/**/*.cpp" - "src/**/*.classes.ts" diff --git a/docs/installation.mdx b/docs/installation.mdx index 44ca34e3ad69..3a909511bb26 100644 --- a/docs/installation.mdx +++ b/docs/installation.mdx @@ -21,7 +21,7 @@ Bun ships as a single, dependency-free executable. Install it with the install s - **Linux users:** You need the `unzip` package to install Bun (`sudo apt install unzip`). We recommend kernel version 5.6 or higher. Bun runs on kernels as old as 3.10 (RHEL 7) with graceful degradation of newer syscalls. Use `uname -r` to check your kernel version. + **Linux users:** The install script needs `curl` or `wget`, and `unzip` (`sudo apt install unzip`). If `unzip` is missing, it also accepts `busybox`, `7z`, `bsdtar`, or `python3`. We recommend kernel version 5.6 or higher. Bun runs on kernels as old as 3.10 (RHEL 7) with graceful degradation of newer syscalls. Use `uname -r` to check your kernel version. diff --git a/src/runtime/cli/upgrade_command.rs b/src/runtime/cli/upgrade_command.rs index 56e9a7eb0a11..b77febefc151 100644 --- a/src/runtime/cli/upgrade_command.rs +++ b/src/runtime/cli/upgrade_command.rs @@ -75,10 +75,9 @@ struct UnzipProgram { restores_mode: bool, } -/// The extractors `bun upgrade` accepts, in probe order. -/// -/// We could just embed libz2, however we want to be sure that xattrs are -/// preserved. xattrs are used for codesigning and it'd be easy to mess that up. +/// The extractors `bun upgrade` accepts, in probe order. The list must match +/// the `for cmd in ...` probe in `install.sh`. The vendored libarchive only has +/// its tar reader compiled in, so the zip is extracted by an external program. #[cfg(unix)] const UNZIP_PROGRAMS: &[UnzipProgram] = &[ UnzipProgram { diff --git a/test/internal/source-lints/install-extractors.test.ts b/test/internal/source-lints/install-extractors.test.ts new file mode 100644 index 000000000000..1afb7a5a85b1 --- /dev/null +++ b/test/internal/source-lints/install-extractors.test.ts @@ -0,0 +1,42 @@ +// src/runtime/cli/install.sh and `bun upgrade` (src/runtime/cli/upgrade_command.rs) +// each carry a list of programs that can extract the release zip. Nothing +// imports one from the other, so they have to say the same thing. +import { expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; + +const root = join(import.meta.dir, "../../.."); +const installSh = readFileSync(join(root, "src/runtime/cli/install.sh"), "utf8"); +const upgradeRs = readFileSync(join(root, "src/runtime/cli/upgrade_command.rs"), "utf8"); + +function shellExtractors(): string[] { + const probe = /^for cmd in (.+); do$/m.exec(installSh); + expect(probe).not.toBeNull(); + return probe![1].split(/\s+/); +} + +function rustExtractors(): string[] { + const table = /const UNZIP_PROGRAMS: &\[UnzipProgram\] = &\[([\s\S]*?)\n\];/.exec(upgradeRs); + expect(table).not.toBeNull(); + return [...table![1].matchAll(/bin: b"([^"]+)"/g)].map(match => match[1]); +} + +test("install.sh probes the extractors that bun upgrade probes, in the same order", () => { + expect(shellExtractors()).toEqual(rustExtractors()); +}); + +test("install.sh has a case arm for every extractor it probes", () => { + const extract = /^case \$unzip_cmd in\n([\s\S]*?)^esac/m.exec(installSh); + expect(extract).not.toBeNull(); + const arms = [...extract![1].matchAll(/^([^\s)]+(?: \| [^\s)]+)*)\)$/gm)].flatMap(match => match[1].split(" | ")); + expect(arms).toEqual(shellExtractors()); +}); + +test("install.sh and bun upgrade name the same supported extractors in their error", () => { + const suffix = /\(([^()]+) supported\)/; + const shell = suffix.exec(installSh); + const rust = suffix.exec(upgradeRs); + expect(shell).not.toBeNull(); + expect(rust).not.toBeNull(); + expect(shell![1]).toBe(rust![1]); +}); From 79a49491c13a077bc4857efb2490ebc10985ceaf Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 20 Sep 2026 22:24:05 +0000 Subject: [PATCH 3/5] Probe the busybox unzip applet and always set the executable bit bun upgrade and install.sh skip a busybox that lacks the unzip applet. bsdtar runs with --no-same-owner. bun upgrade sets the mode of the extracted binary through the staging directory handle and removes the staging directory when that fails. The tests cover every extractor that exists on the host and release their temp dirs. --- src/runtime/cli/install.sh | 11 ++-- src/runtime/cli/upgrade_command.rs | 89 +++++++++++++++------------- test/cli/install/bun-upgrade.test.ts | 77 +++++++++++++++--------- test/cli/install/fake-release.ts | 26 ++++++-- test/cli/install/install-sh.test.ts | 68 ++++++++++++++------- 5 files changed, 172 insertions(+), 99 deletions(-) diff --git a/src/runtime/cli/install.sh b/src/runtime/cli/install.sh index b5ba3613e4d9..1525fbe0815e 100644 --- a/src/runtime/cli/install.sh +++ b/src/runtime/cli/install.sh @@ -63,10 +63,13 @@ fi unzip_cmd='' for cmd in unzip busybox 7z 7zz 7za bsdtar python3; do - if command -v "$cmd" >/dev/null; then - unzip_cmd=$cmd - break + command -v "$cmd" >/dev/null || continue + # A busybox build can leave out the unzip applet. + if [[ $cmd = busybox ]] && ! busybox --list 2>/dev/null | grep -x unzip >/dev/null; then + continue fi + unzip_cmd=$cmd + break done [[ $unzip_cmd ]] || @@ -183,7 +186,7 @@ busybox) "$unzip_cmd" x -y -o"$bin_dir" "$exe.zip" >/dev/null ;; bsdtar) - bsdtar -xf "$exe.zip" -C "$bin_dir" + bsdtar --no-same-owner -xf "$exe.zip" -C "$bin_dir" ;; python3) python3 -m zipfile -e "$exe.zip" "$bin_dir" diff --git a/src/runtime/cli/upgrade_command.rs b/src/runtime/cli/upgrade_command.rs index b77febefc151..2230cfa6b5e3 100644 --- a/src/runtime/cli/upgrade_command.rs +++ b/src/runtime/cli/upgrade_command.rs @@ -63,86 +63,92 @@ fn argv_contains(target: &[u8]) -> bool { bun_core::argv().iter().any(|a| a == target) } -/// A program that can extract the release zip on POSIX. `before` and `after` -/// are the arguments placed around the archive path. The archive is extracted -/// into the current directory. +/// A program that can extract the release zip on POSIX into the current +/// directory. `before` and `after` are the arguments around the archive path. #[cfg(unix)] struct UnzipProgram { bin: &'static [u8], before: &'static [&'static [u8]], after: &'static [&'static [u8]], - /// Whether the program restores the Unix file mode stored in the zip. - restores_mode: bool, } -/// The extractors `bun upgrade` accepts, in probe order. The list must match -/// the `for cmd in ...` probe in `install.sh`. The vendored libarchive only has -/// its tar reader compiled in, so the zip is extracted by an external program. +/// Probe order. Must match the `for cmd in ...` loop in `install.sh`. +/// The vendored libarchive has no zip reader, so an external program extracts it. #[cfg(unix)] const UNZIP_PROGRAMS: &[UnzipProgram] = &[ UnzipProgram { bin: b"unzip", before: &[b"-q", b"-o"], after: &[], - restores_mode: true, }, UnzipProgram { bin: b"busybox", before: &[b"unzip", b"-q", b"-o"], after: &[], - restores_mode: true, }, UnzipProgram { bin: b"7z", before: &[b"x", b"-y"], after: &[], - restores_mode: true, }, UnzipProgram { bin: b"7zz", before: &[b"x", b"-y"], after: &[], - restores_mode: true, }, UnzipProgram { bin: b"7za", before: &[b"x", b"-y"], after: &[], - restores_mode: true, }, UnzipProgram { bin: b"bsdtar", - before: &[b"-xf"], + before: &[b"--no-same-owner", b"-xf"], after: &[], - restores_mode: true, }, UnzipProgram { bin: b"python3", before: &[b"-m", b"zipfile", b"-e"], after: &[b"."], - restores_mode: false, }, ]; -/// Resolves the first entry of `UNZIP_PROGRAMS` found in `path` and returns it -/// with the argv that extracts `archive`. +/// A busybox build can leave out the unzip applet. `busybox --list` prints one +/// applet name per line. #[cfg(unix)] -fn find_unzip_argv( - path: &[u8], - cwd: &[u8], - archive: &[u8], -) -> Option<(&'static UnzipProgram, Vec>)> { +fn busybox_has_unzip(busybox: &[u8]) -> bool { + let argv: [&[u8]; 2] = [busybox, b"--list"]; + let Ok(Ok(result)) = spawn_sync::spawn(&spawn_sync::Options { + argv: build_argv(&argv), + envp: None, + stdin: spawn_sync::SyncStdio::Ignore, + stdout: spawn_sync::SyncStdio::Buffer, + stderr: spawn_sync::SyncStdio::Ignore, + ..Default::default() + }) else { + return false; + }; + result.status.is_ok() + && strings::split(result.stdout.as_slice(), b"\n").any(|line| line == b"unzip") +} + +/// Returns the argv of the first entry of `UNZIP_PROGRAMS` found in `path`. +#[cfg(unix)] +fn find_unzip_argv(path: &[u8], cwd: &[u8], archive: &[u8]) -> Option>> { let mut buf = bun_paths::path_buffer_pool::get(); for program in UNZIP_PROGRAMS { let Some(exe) = which(&mut buf, path, cwd, program.bin) else { continue; }; + if program.bin == b"busybox" && !busybox_has_unzip(exe.as_bytes()) { + continue; + } let mut argv = Vec::with_capacity(program.before.len() + program.after.len() + 2); argv.push(Box::<[u8]>::from(exe.as_bytes())); argv.extend(program.before.iter().map(|a| Box::<[u8]>::from(*a))); argv.push(Box::<[u8]>::from(archive)); argv.extend(program.after.iter().map(|a| Box::<[u8]>::from(*a))); - return Some((program, argv)); + return Some(argv); } None } @@ -900,7 +906,7 @@ impl UpgradeCommand { #[cfg(unix)] { - let Some((unzip_program, unzip_argv)) = find_unzip_argv( + let Some(unzip_argv) = find_unzip_argv( env_loader.map.get(b"PATH").unwrap_or(b""), filesystem.top_level_dir, tmpname.as_bytes(), @@ -959,22 +965,23 @@ impl UpgradeCommand { } } - if !unzip_program.restores_mode { - // We already chdir'd to tmpdir, so the relative `exe` path works. - let exe_z: &ZStr = ZStr::from_static(if use_profile { - const_format::concatcp!(UpgradeCommand::PROFILE_EXE_SUBPATH, "\0") - .as_bytes() - } else { - const_format::concatcp!(UpgradeCommand::EXE_SUBPATH, "\0").as_bytes() - }); - if let Err(err) = sys::chmod(exe_z, 0o755) { - bun_core::pretty_errorln!( - "error: Failed to set permissions on {} due to {}.", - bstr::BStr::new(exe), - bstr::BStr::new(err.name()) - ); - Global::exit(1); - } + // `python3 -m zipfile` does not restore the file mode, and + // some busybox builds do not either. + let exe_z: &ZStr = ZStr::from_static(if use_profile { + const_format::concatcp!(UpgradeCommand::PROFILE_EXE_SUBPATH, "\0") + .as_bytes() + } else { + const_format::concatcp!(UpgradeCommand::EXE_SUBPATH, "\0").as_bytes() + }); + if let Err(err) = sys::fchmodat(&save_dir, exe_z, 0o755, 0) { + let _ = sys::unlinkat(&save_dir, tmpname); + let _ = save_dir_.delete_tree(&version_name); + bun_core::pretty_errorln!( + "error: Failed to set permissions on {} due to {}.", + bstr::BStr::new(exe), + bstr::BStr::new(err.name()) + ); + Global::exit(1); } } #[cfg(windows)] diff --git a/test/cli/install/bun-upgrade.test.ts b/test/cli/install/bun-upgrade.test.ts index 49332e2fd19d..70a615eafb8b 100644 --- a/test/cli/install/bun-upgrade.test.ts +++ b/test/cli/install/bun-upgrade.test.ts @@ -1,6 +1,6 @@ import { spawn } from "bun"; import { upgrade_test_helpers } from "bun:internal-for-testing"; -import { describe, expect, it } from "bun:test"; +import { afterAll, describe, expect, it } from "bun:test"; import { bunExe, bunEnv as env, isMusl, isWindows, tempDir, tls, tmpdirSync } from "harness"; import { existsSync, statSync } from "node:fs"; import { copyFile, writeFile } from "node:fs/promises"; @@ -223,33 +223,56 @@ it("completes against a locally-served release with the system temp dir held ope expect(exitCode).toBe(0); }); -// Minimal hosts often lack `unzip`. `bun upgrade` then falls back to other -// extractors; python3 is the one most often present. Its zipfile module does -// not restore the file mode, so the upgrade has to set it before verification. -const python3OnlyPath = isWindows ? null : restrictedPathDir(["python3"], ["python3"]); -it.skipIf(!python3OnlyPath)("extracts the release archive with python3 when unzip is not in PATH", async () => { - const version = "9.9.9"; - const cwd = tmpdirSync(); - const execPath = join(cwd, basename(bunExe())); - const zipPath = join(cwd, "release.zip"); - await Promise.all([copyFile(bunExe(), execPath), writeFakeReleaseZip(zipPath, version)]); - - using server = startReleaseServer({ tagName: `bun-v${version}`, zipPath }); - - await using proc = Bun.spawn({ - cmd: [execPath, "upgrade", "--stable"], - cwd, - stdout: null, - stdin: "pipe", - stderr: "pipe", - env: { ...server.env, PATH: python3OnlyPath! }, - }); - - const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]); +// Minimal hosts often lack `unzip`. `bun upgrade` then falls back to the other +// extractors in its table. The PATH holds one extractor at a time, so each +// table row runs wherever that program exists on the host. The busybox and +// python3 probes rule out a busybox without the unzip applet and a python3 +// shim that needs more of PATH than the test gives it. +const extractors: Record = { + unzip: undefined, + busybox: ["/bin/sh", "-c", "busybox --list | grep -x unzip"], + "7z": undefined, + "7zz": undefined, + "7za": undefined, + bsdtar: undefined, + python3: ["python3", "-m", "zipfile", "-h"], +}; +const extractorPaths = Object.entries(extractors).map( + ([name, probe]) => + [name, restrictedPathDir(name === "busybox" ? ["busybox", "grep"] : [name], [name], probe)] as const, +); +afterAll(() => { + for (const [, dir] of extractorPaths) dir?.[Symbol.dispose](); +}); - expect(stderr).not.toContain("error:"); - expect(stderr).toContain("Upgraded."); - expect(exitCode).toBe(0); +describe.concurrent("extracts the release archive when the only extractor in PATH is", () => { + for (const [name, dir] of extractorPaths) { + it.skipIf(!dir)(name, async () => { + const version = "9.9.9"; + using cwd = tempDir("bun-upgrade-extractor", {}); + const execPath = join(cwd, basename(bunExe())); + const zipPath = join(cwd, "release.zip"); + await Promise.all([copyFile(bunExe(), execPath), writeFakeReleaseZip(zipPath, version)]); + + using server = startReleaseServer({ tagName: `bun-v${version}`, zipPath }); + + await using proc = Bun.spawn({ + cmd: [execPath, "upgrade", "--stable"], + cwd: String(cwd), + stdout: null, + stdin: "pipe", + stderr: "pipe", + // The staging dir is $TMPDIR/, so each test needs its own. + env: { ...server.env, PATH: dir!, BUN_TMPDIR: String(cwd) }, + }); + + const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]); + + expect(stderr).not.toContain("error:"); + expect(stderr).toContain("Upgraded."); + expect(exitCode).toBe(0); + }); + } }); it("recreates the staging directory in the temp dir instead of reusing a pre-existing one", async () => { diff --git a/test/cli/install/fake-release.ts b/test/cli/install/fake-release.ts index a8b20c6fa350..2425872cc2bd 100644 --- a/test/cli/install/fake-release.ts +++ b/test/cli/install/fake-release.ts @@ -1,4 +1,4 @@ -import { tmpdirSync } from "harness"; +import { isWindows, tempDir } from "harness"; import { symlinkSync } from "node:fs"; import { join } from "node:path"; @@ -77,19 +77,33 @@ export function makeZipStored(entryName: string, data: Buffer, unixMode: number) return buf; } +export type RestrictedPath = string & Disposable; + // Build a PATH that holds only the named programs (those found on this host), // so a test can run the installer or `bun upgrade` on a host that appears to -// lack `curl` or `unzip`. Returns the directory, or null when a required -// program is missing on this host. -export function restrictedPathDir(programs: string[], required: string[] = []): string | null { - const dir = tmpdirSync("bun-restricted-path"); +// lack `curl` or `unzip`. Returns null on Windows, when a required program is +// missing, or when `probe` does not exit 0 under that PATH (a pyenv shim for +// python3, a busybox without the unzip applet). +export function restrictedPathDir(programs: string[], required: string[], probe?: string[]): RestrictedPath | null { + if (isWindows) return null; + const dir = tempDir("bun-restricted-path", {}); for (const name of programs) { const found = Bun.which(name); if (!found) { - if (required.includes(name)) return null; + if (required.includes(name)) { + dir[Symbol.dispose](); + return null; + } continue; } symlinkSync(found, join(dir, name)); } + if (probe) { + const { exitCode } = Bun.spawnSync({ cmd: probe, env: { PATH: dir }, stdout: "ignore", stderr: "ignore" }); + if (exitCode !== 0) { + dir[Symbol.dispose](); + return null; + } + } return dir; } diff --git a/test/cli/install/install-sh.test.ts b/test/cli/install/install-sh.test.ts index af8ae91dad8e..be676a841f5c 100644 --- a/test/cli/install/install-sh.test.ts +++ b/test/cli/install/install-sh.test.ts @@ -1,14 +1,36 @@ -import { describe, expect, test } from "bun:test"; -import { bunEnv, isWindows, tmpdirSync } from "harness"; +import { afterAll, describe, expect, test } from "bun:test"; +import { bunEnv, tempDir } from "harness"; import { statSync } from "node:fs"; import { join } from "node:path"; -import { makeZipStored, restrictedPathDir } from "./fake-release"; +import { makeZipStored, restrictedPathDir, type RestrictedPath } from "./fake-release"; const installScript = join(import.meta.dir, "../../../src/runtime/cli/install.sh"); // Everything install.sh runs besides the download and extract programs. const baseTools = ["bash", "uname", "mkdir", "mv", "chmod", "rm", "basename", "grep", "cat", "sysctl"]; +// Every extractor install.sh probes, with a command that proves the one on +// this host works under the restricted PATH. +const extractors: Record = { + unzip: undefined, + busybox: ["/bin/sh", "-c", "busybox --list | grep -x unzip"], + "7z": undefined, + "7zz": undefined, + "7za": undefined, + bsdtar: undefined, + python3: ["python3", "-m", "zipfile", "-h"], +}; + +const pathDirs: RestrictedPath[] = []; +function pathWith(programs: string[], probe?: string[]): RestrictedPath | null { + const dir = restrictedPathDir([...baseTools, ...programs], programs, probe); + if (dir) pathDirs.push(dir); + return dir; +} +afterAll(() => { + for (const dir of pathDirs) dir[Symbol.dispose](); +}); + // Serves any `bun-.zip` the installer asks for, with a shell script in // place of the binary. The folder name inside the zip must match the target // the installer computed, so it is taken from the request. @@ -28,53 +50,57 @@ function startReleaseServer() { async function runInstaller(pathDir: string) { using server = startReleaseServer(); - const home = tmpdirSync("bun-install-sh-home"); + using home = tempDir("bun-install-sh-home", {}); const installDir = join(home, ".bun"); await using proc = Bun.spawn({ cmd: ["bash", installScript], env: { ...bunEnv, PATH: pathDir, - HOME: home, + HOME: String(home), SHELL: "/bin/sh", BUN_INSTALL: installDir, GITHUB: `http://${server.hostname}:${server.port}`, }, - cwd: home, + cwd: String(home), stdout: "pipe", stderr: "pipe", }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - return { stdout, stderr, exitCode, exe: join(installDir, "bin", "bun") }; + const exe = join(installDir, "bin", "bun"); + const executable = exitCode === 0 && (statSync(exe).mode & 0o111) !== 0; + return { stdout, stderr, exitCode, executable }; } -describe.skipIf(isWindows).concurrent("install.sh", () => { - const wgetPath = restrictedPathDir([...baseTools, "wget", "unzip"], ["wget", "unzip"]); +describe.concurrent("install.sh", () => { + const wgetPath = pathWith(["wget", "unzip"]); test.skipIf(!wgetPath)("downloads with wget when curl is missing", async () => { - const { stdout, stderr, exitCode, exe } = await runInstaller(wgetPath!); + const { stdout, stderr, exitCode, executable } = await runInstaller(wgetPath!); expect(stderr).not.toContain("error"); expect(stdout).toContain("bun was installed successfully"); - expect(statSync(exe).mode & 0o111).not.toBe(0); + expect(executable).toBe(true); expect(exitCode).toBe(0); }); - const python3Path = restrictedPathDir([...baseTools, "curl", "python3"], ["curl", "python3"]); - test.skipIf(!python3Path)("extracts with python3 when unzip is missing", async () => { - const { stdout, stderr, exitCode, exe } = await runInstaller(python3Path!); - expect(stderr).not.toContain("error"); - expect(stdout).toContain("bun was installed successfully"); - expect(statSync(exe).mode & 0o111).not.toBe(0); - expect(exitCode).toBe(0); - }); + for (const [name, probe] of Object.entries(extractors)) { + const extractorPath = pathWith(["curl", name], probe); + test.skipIf(!extractorPath)(`extracts with ${name} when it is the only extractor`, async () => { + const { stdout, stderr, exitCode, executable } = await runInstaller(extractorPath!); + expect(stderr).not.toContain("error"); + expect(stdout).toContain("bun was installed successfully"); + expect(executable).toBe(true); + expect(exitCode).toBe(0); + }); + } - const noDownloaderPath = restrictedPathDir([...baseTools, "unzip"], ["unzip"]); + const noDownloaderPath = pathWith(["unzip"]); test.skipIf(!noDownloaderPath)("reports when neither curl nor wget exists", async () => { const { stderr, exitCode } = await runInstaller(noDownloaderPath!); expect(stderr).toContain("curl or wget is required to install bun"); expect(exitCode).toBe(1); }); - const noExtractorPath = restrictedPathDir([...baseTools, "curl"], ["curl"]); + const noExtractorPath = pathWith(["curl"]); test.skipIf(!noExtractorPath)("reports when no archive extractor exists", async () => { const { stderr, exitCode } = await runInstaller(noExtractorPath!); expect(stderr).toContain("unzip is required to install bun (7z, busybox, bsdtar, python3 supported)"); From 0b50c54e567d43b8302250637e6cfb212404ec99 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 21 Sep 2026 07:12:39 +0000 Subject: [PATCH 4/5] upgrade: name the extractor in the unzip failure messages `bun upgrade` can run one of seven extractors. The spawn error and the exit error said "unzip" for each of them. They now name the program that ran, for example `python3 failed (exit code: 1)`. #16881 had this. Co-authored-by: Doug Coleman --- src/runtime/cli/upgrade_command.rs | 27 +++++++++++++++++++-------- test/cli/install/bun-upgrade.test.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 8 deletions(-) diff --git a/src/runtime/cli/upgrade_command.rs b/src/runtime/cli/upgrade_command.rs index 2230cfa6b5e3..f5188b184f31 100644 --- a/src/runtime/cli/upgrade_command.rs +++ b/src/runtime/cli/upgrade_command.rs @@ -132,9 +132,13 @@ fn busybox_has_unzip(busybox: &[u8]) -> bool { && strings::split(result.stdout.as_slice(), b"\n").any(|line| line == b"unzip") } -/// Returns the argv of the first entry of `UNZIP_PROGRAMS` found in `path`. +/// Returns the name and the argv of the first entry of `UNZIP_PROGRAMS` found in `path`. #[cfg(unix)] -fn find_unzip_argv(path: &[u8], cwd: &[u8], archive: &[u8]) -> Option>> { +fn find_unzip_argv( + path: &[u8], + cwd: &[u8], + archive: &[u8], +) -> Option<(&'static [u8], Vec>)> { let mut buf = bun_paths::path_buffer_pool::get(); for program in UNZIP_PROGRAMS { let Some(exe) = which(&mut buf, path, cwd, program.bin) else { @@ -148,7 +152,7 @@ fn find_unzip_argv(path: &[u8], cwd: &[u8], archive: &[u8]) -> Option::from(*a))); argv.push(Box::<[u8]>::from(archive)); argv.extend(program.after.iter().map(|a| Box::<[u8]>::from(*a))); - return Some(argv); + return Some((program.bin, argv)); } None } @@ -906,7 +910,7 @@ impl UpgradeCommand { #[cfg(unix)] { - let Some(unzip_argv) = find_unzip_argv( + let Some((unzip_name, unzip_argv)) = find_unzip_argv( env_loader.map.get(b"PATH").unwrap_or(b""), filesystem.top_level_dir, tmpname.as_bytes(), @@ -933,7 +937,8 @@ impl UpgradeCommand { Ok(Err(err)) => { let _ = sys::unlinkat(&save_dir, tmpname); bun_core::pretty_errorln!( - "error: Failed to spawn unzip due to {}.", + "error: Failed to spawn {} due to {}.", + bstr::BStr::new(unzip_name), bstr::BStr::new(err.name()) ); Global::exit(1); @@ -941,7 +946,8 @@ impl UpgradeCommand { Err(err) => { let _ = sys::unlinkat(&save_dir, tmpname); bun_core::pretty_errorln!( - "error: Failed to spawn unzip due to {}.", + "error: Failed to spawn {} due to {}.", + bstr::BStr::new(unzip_name), err.name() ); Global::exit(1); @@ -952,14 +958,19 @@ impl UpgradeCommand { Status::Exited(e) if e.code == 0 => {} Status::Exited(e) => { bun_core::pretty_errorln!( - "Unzip failed (exit code: {})", + "{} failed (exit code: {})", + bstr::BStr::new(unzip_name), e.code ); let _ = sys::unlinkat(&save_dir, tmpname); Global::exit(1); } other => { - bun_core::pretty_errorln!("Unzip failed ({})", other); + bun_core::pretty_errorln!( + "{} failed ({})", + bstr::BStr::new(unzip_name), + other + ); let _ = sys::unlinkat(&save_dir, tmpname); Global::exit(1); } diff --git a/test/cli/install/bun-upgrade.test.ts b/test/cli/install/bun-upgrade.test.ts index 70a615eafb8b..57147bc47847 100644 --- a/test/cli/install/bun-upgrade.test.ts +++ b/test/cli/install/bun-upgrade.test.ts @@ -275,6 +275,32 @@ describe.concurrent("extracts the release archive when the only extractor in PAT } }); +// Any of the extractors above can run, so a failure has to say which one did. +// The last one found on the host is the one least likely to be `unzip`. +const [failingExtractor, failingExtractorPath] = extractorPaths.findLast(([, dir]) => dir) ?? []; +it.skipIf(!failingExtractorPath)("names the extractor that fails on a bad archive", async () => { + using cwd = tempDir("bun-upgrade-bad-archive", {}); + const execPath = join(cwd, basename(bunExe())); + await copyFile(bunExe(), execPath); + + // Without a zipPath the server answers the download with bytes that are not a zip. + using server = startReleaseServer({ tagName: "bun-v9.9.9" }); + + await using proc = Bun.spawn({ + cmd: [execPath, "upgrade", "--stable"], + cwd: String(cwd), + stdout: null, + stdin: "pipe", + stderr: "pipe", + env: { ...server.env, PATH: failingExtractorPath!, BUN_TMPDIR: String(cwd) }, + }); + + const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]); + + expect(stderr).toContain(`${failingExtractor} failed (exit code:`); + expect(exitCode).toBe(1); +}); + it("recreates the staging directory in the temp dir instead of reusing a pre-existing one", async () => { const tagName = "bun-v9.9.9"; // Simulate a directory that already exists at the predictable staging path From bd23996fd4c2d73525a6cf646493fc1ba1eb0c4c Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 21 Sep 2026 07:24:17 +0000 Subject: [PATCH 5/5] upgrade: put the busybox applet in the extractor table `find_unzip_argv` compared `program.bin` with `b"busybox"` to decide when to check for the unzip applet. The mordant `stringly_state` lint reports that comparison as an enum written as a string. The busybox row now names its applet. The probe and the argv both read it from the row. --- src/runtime/cli/upgrade_command.rs | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/src/runtime/cli/upgrade_command.rs b/src/runtime/cli/upgrade_command.rs index f5188b184f31..4f5f4077bd98 100644 --- a/src/runtime/cli/upgrade_command.rs +++ b/src/runtime/cli/upgrade_command.rs @@ -68,6 +68,8 @@ fn argv_contains(target: &[u8]) -> bool { #[cfg(unix)] struct UnzipProgram { bin: &'static [u8], + /// The first argument of a multi-call binary. A build can leave the applet out. + applet: Option<&'static [u8]>, before: &'static [&'static [u8]], after: &'static [&'static [u8]], } @@ -78,46 +80,52 @@ struct UnzipProgram { const UNZIP_PROGRAMS: &[UnzipProgram] = &[ UnzipProgram { bin: b"unzip", + applet: None, before: &[b"-q", b"-o"], after: &[], }, UnzipProgram { bin: b"busybox", - before: &[b"unzip", b"-q", b"-o"], + applet: Some(b"unzip"), + before: &[b"-q", b"-o"], after: &[], }, UnzipProgram { bin: b"7z", + applet: None, before: &[b"x", b"-y"], after: &[], }, UnzipProgram { bin: b"7zz", + applet: None, before: &[b"x", b"-y"], after: &[], }, UnzipProgram { bin: b"7za", + applet: None, before: &[b"x", b"-y"], after: &[], }, UnzipProgram { bin: b"bsdtar", + applet: None, before: &[b"--no-same-owner", b"-xf"], after: &[], }, UnzipProgram { bin: b"python3", + applet: None, before: &[b"-m", b"zipfile", b"-e"], after: &[b"."], }, ]; -/// A busybox build can leave out the unzip applet. `busybox --list` prints one -/// applet name per line. +/// `busybox --list` prints one applet name per line. #[cfg(unix)] -fn busybox_has_unzip(busybox: &[u8]) -> bool { - let argv: [&[u8]; 2] = [busybox, b"--list"]; +fn has_applet(exe: &[u8], applet: &[u8]) -> bool { + let argv: [&[u8]; 2] = [exe, b"--list"]; let Ok(Ok(result)) = spawn_sync::spawn(&spawn_sync::Options { argv: build_argv(&argv), envp: None, @@ -129,7 +137,7 @@ fn busybox_has_unzip(busybox: &[u8]) -> bool { return false; }; result.status.is_ok() - && strings::split(result.stdout.as_slice(), b"\n").any(|line| line == b"unzip") + && strings::split(result.stdout.as_slice(), b"\n").any(|line| line == applet) } /// Returns the name and the argv of the first entry of `UNZIP_PROGRAMS` found in `path`. @@ -144,11 +152,15 @@ fn find_unzip_argv( let Some(exe) = which(&mut buf, path, cwd, program.bin) else { continue; }; - if program.bin == b"busybox" && !busybox_has_unzip(exe.as_bytes()) { + if program + .applet + .is_some_and(|applet| !has_applet(exe.as_bytes(), applet)) + { continue; } - let mut argv = Vec::with_capacity(program.before.len() + program.after.len() + 2); + let mut argv = Vec::with_capacity(program.before.len() + program.after.len() + 3); argv.push(Box::<[u8]>::from(exe.as_bytes())); + argv.extend(program.applet.map(Box::<[u8]>::from)); argv.extend(program.before.iter().map(|a| Box::<[u8]>::from(*a))); argv.push(Box::<[u8]>::from(archive)); argv.extend(program.after.iter().map(|a| Box::<[u8]>::from(*a)));