From 6761f6a402bd7e14f149b9c66a977349a01f166a Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 12 Aug 2026 23:41:46 +0000 Subject: [PATCH 1/4] shell(cp): copy the file a symlink operand points at unless -R is given The cp builtin classified every source operand with lstat and handed it to the native copy, which never follows symlinks, so `cp link dest` recreated the link instead of copying the file (cp -P behaviour), a dangling link or a link to a directory copied successfully, and `cp link target-of-link` did nothing. Without -R the shell now classifies the operand with stat, refuses a target that is the same file as the dereferenced source, and asks the native copy to dereference via a new CpFlags::dereference, which the POSIX arms of copy_single_file_sync honour by stat-checking the kind and opening without O_NOFOLLOW (or letting clonefile/copyfile follow on macOS) and the Windows arm by letting CopyFileW follow the link. -R and fs.cp are unchanged. --- src/runtime/node/node_fs.rs | 113 +++++++++++++------- src/runtime/shell/builtin/cp.rs | 59 +++++++++- test/js/bun/shell/commands/cp.test.ts | 148 +++++++++++++++++++++++++- 3 files changed, 278 insertions(+), 42 deletions(-) diff --git a/src/runtime/node/node_fs.rs b/src/runtime/node/node_fs.rs index f0941840d3d2..d43082db4dad 100644 --- a/src/runtime/node/node_fs.rs +++ b/src/runtime/node/node_fs.rs @@ -4343,6 +4343,12 @@ pub mod args { pub(crate) recursive: bool, pub(crate) error_on_exist: bool, pub(crate) force: bool, + /// A symlink source is followed and the file it points at is copied, + /// the way `cp` without `-R` treats its operands. Off, a symlink is + /// recreated (`fs.cp` handles `dereference` itself and never sets + /// this). Only consulted by `copy_single_file_sync`; directories are + /// still classified without following links. + pub(crate) dereference: bool, } pub struct Cp { @@ -4389,6 +4395,7 @@ pub mod args { recursive, error_on_exist, force, + dereference: false, }, }) } @@ -8539,7 +8546,42 @@ impl NodeFS { Syscall::symlink(ZStr::from_buf(&resolved_buf[..], resolved_len), dest) } - /// This is `copyFile`, but it copies symlinks as-is + /// The stat `copy_single_file_sync` classifies its source by. Callers pass + /// the `lstat` they already took as `reuse_stat`; when dereferencing, a + /// symlink is stat'd again so the copy is described by its target. + #[cfg(not(windows))] + fn cp_source_stat( + src: &ZStr, + reuse_stat: Option<&sys::Stat>, + dereference: bool, + ) -> Maybe { + if let Some(stat_) = reuse_stat { + if !dereference || !sys::S::ISLNK(stat_.st_mode as Mode) { + return Ok(*stat_); + } + } + if dereference { + Syscall::stat(src) + } else { + Syscall::lstat(src) + } + } + + /// Opens the file a dereferenced source resolves to. The kind is checked + /// from the stat first: `open(2)` on a FIFO blocks until a writer shows up. + #[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))] + fn cp_open_dereferenced_source(src: &ZStr, reuse_stat: Option<&sys::Stat>) -> Maybe { + let stat_ = Self::cp_source_stat(src, reuse_stat, true)?; + if !sys::S::ISREG(stat_.st_mode as Mode) { + return Err( + sys::Error::from_code(E::ENOTSUP, sys::Tag::copyfile).with_path(src.as_bytes()) + ); + } + Syscall::open(src, sys::O::RDONLY, 0o644) + } + + /// This is `copyFile`, but it copies symlinks as-is unless + /// `args.flags.dereference` is set. pub(crate) fn copy_single_file_sync( &mut self, src: &OSPathSliceZ, @@ -8550,8 +8592,6 @@ impl NodeFS { #[cfg(not(windows))] reuse_stat: Option<&sys::Stat>, args: &args::Cp, ) -> Maybe { - let _ = args; // only the Windows branch consults `args` (shouldIgnoreEbusy) - // TODO: do we need to fchown? #[cfg(target_os = "macos")] { @@ -8564,16 +8604,7 @@ impl NodeFS { ) .unwrap_or(Ok(())); } - let stat_ = match reuse_stat { - Some(s) => *s, - None => match Syscall::lstat(src) { - Ok(result) => result, - Err(err) => { - self.sync_error_buf[..src.len()].copy_from_slice(src.as_bytes()); - return Err(err.with_path(&self.sync_error_buf[..src.len()])); - } - }, - }; + let stat_ = Self::cp_source_stat(src, reuse_stat, args.flags.dereference)?; if !sys::S::ISREG(stat_.st_mode as u32) { if sys::S::ISLNK(stat_.st_mode as u32) { @@ -8657,9 +8688,10 @@ impl NodeFS { // we fallback to copyfile() when the file is > 128 KB and clonefile fails // clonefile() isn't supported on all devices // nor is it supported across devices - let mut mode_: u32 = bun_sys::c::COPYFILE_ACL - | bun_sys::c::COPYFILE_DATA - | bun_sys::c::COPYFILE_NOFOLLOW_SRC; + let mut mode_: u32 = bun_sys::c::COPYFILE_ACL | bun_sys::c::COPYFILE_DATA; + if !args.flags.dereference { + mode_ |= bun_sys::c::COPYFILE_NOFOLLOW_SRC; + } if mode.shouldnt_overwrite() { mode_ |= bun_sys::c::COPYFILE_EXCL; } @@ -8688,21 +8720,24 @@ impl NodeFS { #[cfg(any(target_os = "linux", target_os = "android"))] { - let _ = reuse_stat; // https://manpages.debian.org/testing/manpages-dev/ioctl_ficlone.2.en.html if mode.is_force_clone() { return Maybe::::todo(); } - let src_fd = match Syscall::open(src, sys::O::RDONLY | sys::O::NOFOLLOW, 0o644) { - Ok(result) => result, - Err(err) => { - if err.get_errno() == E::ELOOP { - // ELOOP is returned when you open a symlink with NOFOLLOW. - // as in, it does not actually let you open it. - return self.cp_symlink(src, dest); + let src_fd = if args.flags.dereference { + Self::cp_open_dereferenced_source(src, reuse_stat)? + } else { + match Syscall::open(src, sys::O::RDONLY | sys::O::NOFOLLOW, 0o644) { + Ok(result) => result, + Err(err) => { + if err.get_errno() == E::ELOOP { + // ELOOP is returned when you open a symlink with NOFOLLOW. + // as in, it does not actually let you open it. + return self.cp_symlink(src, dest); + } + return Err(err); } - return Err(err); } }; let _close_src = scopeguard::guard(src_fd, |fd| fd.close()); @@ -8856,7 +8891,6 @@ impl NodeFS { #[cfg(target_os = "freebsd")] { - let _ = reuse_stat; if mode.is_force_clone() { return Err(sys::Error { errno: SystemErrno::EOPNOTSUPP as _, @@ -8865,16 +8899,20 @@ impl NodeFS { }); } - let src_fd = match Syscall::open(src, sys::O::RDONLY | sys::O::NOFOLLOW, 0o644) { - Ok(result) => result, - Err(err) => { - // O_NOFOLLOW on a symlink → recreate the link. FreeBSD's - // open(2) returns EMLINK for this case, though POSIX - // specifies ELOOP; accept either. - if matches!(err.get_errno(), E::EMLINK | E::ELOOP) { - return self.cp_symlink(src, dest); + let src_fd = if args.flags.dereference { + Self::cp_open_dereferenced_source(src, reuse_stat)? + } else { + match Syscall::open(src, sys::O::RDONLY | sys::O::NOFOLLOW, 0o644) { + Ok(result) => result, + Err(err) => { + // O_NOFOLLOW on a symlink → recreate the link. FreeBSD's + // open(2) returns EMLINK for this case, though POSIX + // specifies ELOOP; accept either. + if matches!(err.get_errno(), E::EMLINK | E::ELOOP) { + return self.cp_symlink(src, dest); + } + return Err(err); } - return Err(err); } }; let _close_src = scopeguard::guard(src_fd, |fd| fd.close()); @@ -9025,7 +9063,8 @@ impl NodeFS { a } }; - if stat_ & sys::c::FILE_ATTRIBUTE_REPARSE_POINT == 0 { + // `CopyFileW` itself copies the file a symlink source points at. + if stat_ & sys::c::FILE_ATTRIBUTE_REPARSE_POINT == 0 || args.flags.dereference { if unsafe { sys::c::CopyFileW( src.as_ptr(), @@ -9133,7 +9172,7 @@ impl NodeFS { windows )))] { - let _ = (src, dest, mode, reuse_stat); + let _ = (src, dest, mode, reuse_stat, args); Maybe::::todo() } } diff --git a/src/runtime/shell/builtin/cp.rs b/src/runtime/shell/builtin/cp.rs index bb84b01e0054..fc8b42fa4002 100644 --- a/src/runtime/shell/builtin/cp.rs +++ b/src/runtime/shell/builtin/cp.rs @@ -563,6 +563,7 @@ impl ShellCpTask { .is_some_and(|&c| resolve_path::Platform::AUTO.is_separator(c)) } + /// Classifies a path without following a symlink. fn is_dir(path: &bun_core::ZStr) -> bun_sys::Maybe { #[cfg(windows)] { @@ -581,6 +582,16 @@ impl ShellCpTask { } } + /// Is `tgt` (following symlinks, like the copy will) the file `src_stat` + /// describes? An inode number of 0 means the filesystem reports no identity. + fn is_same_file(src_stat: &bun_sys::Stat, tgt: &bun_core::ZStr) -> bool { + bun_sys::stat(tgt).is_ok_and(|tgt_stat| { + src_stat.st_ino != 0 + && src_stat.st_ino == tgt_stat.st_ino + && src_stat.st_dev == tgt_stat.st_dev + }) + } + /// Resolves src/tgt to absolute paths, classifies them per the three /// POSIX `cp` synopses /// (), then hands off to @@ -616,9 +627,23 @@ impl ShellCpTask { // folder -> folder // We need to check dest to see what it is; if it doesn't exist we // need to create it. - let src_is_dir = match Self::is_dir(src) { - Ok(x) => x, - Err(e) => return Some(ShellErr::new_sys(&e)), + + // cp(1) copies the file a symlink operand points at; only `-R` copies + // the link itself. + let src_stat = if self.opts.recursive { + None + } else { + match bun_sys::stat(src) { + Ok(st) => Some(st), + Err(e) => return Some(ShellErr::new_sys(&e)), + } + }; + let src_is_dir = match &src_stat { + Some(st) => bun_sys::S::ISDIR(st.st_mode as _), + None => match Self::is_dir(src) { + Ok(x) => x, + Err(e) => return Some(ShellErr::new_sys(&e)), + }, }; // Any source directory without -R is an error. @@ -651,6 +676,8 @@ impl ShellCpTask { }; let mut _copying_many = false; + // Set when the copy lands at `tgt/`, for error messages. + let mut dest_basename: Option<&[u8]> = None; // The following logic is based on the POSIX spec. if !src_is_dir && !tgt_is_dir && self.operands == 2 { @@ -694,9 +721,34 @@ impl ShellCpTask { buf3.as_mut_slice(), &[tgt.as_bytes(), basename], ); + dest_basename = Some(basename); _copying_many = true; } + // With the operand dereferenced, `cp link target-of-link` would read + // and write one file; cp(1) refuses that as the same file. + if let Some(src_stat) = &src_stat { + if Self::is_same_file(src_stat, tgt) { + let mut shown_buf = bun_paths::path_buffer_pool::get(); + let shown_tgt: &[u8] = match dest_basename { + Some(basename) => resolve_path::join_string_buf::( + &mut shown_buf[..], + &[&self.tgt, basename], + ), + None => &self.tgt, + }; + return Some(ShellErr::Custom( + format!( + "{} and {} are identical (not copied)", + bstr::BStr::new(&self.src), + bstr::BStr::new(shown_tgt) + ) + .into_bytes() + .into_boxed_slice(), + )); + } + } + self.src_absolute = Some(src.as_bytes().to_vec()); self.tgt_absolute = Some(tgt.as_bytes().to_vec()); @@ -713,6 +765,7 @@ impl ShellCpTask { recursive: self.opts.recursive, force: true, error_on_exist: false, + dereference: !self.opts.recursive, }, }; diff --git a/test/js/bun/shell/commands/cp.test.ts b/test/js/bun/shell/commands/cp.test.ts index 80a28d2c7e2c..6b7271305ec3 100644 --- a/test/js/bun/shell/commands/cp.test.ts +++ b/test/js/bun/shell/commands/cp.test.ts @@ -1,7 +1,10 @@ import { $ } from "bun"; import { shellInternals } from "bun:internal-for-testing"; -import { describe, expect } from "bun:test"; -import { tempDirWithFiles } from "harness"; +import { describe, expect, test } from "bun:test"; +import { bunEnv, DirectoryTree, isWindows, tempDir, tempDirWithFiles } from "harness"; +import { mkfifo } from "mkfifo"; +import { lstatSync, readFileSync, readlinkSync, symlinkSync } from "node:fs"; +import { join } from "node:path"; import { bunExe, createTestBuilder } from "../test_builder"; import { sortedShellOutput } from "../util"; const { builtinDisabled } = shellInternals; @@ -173,6 +176,147 @@ describe.if(!builtinDisabled("cp"))("bunshell cp", async () => { }); }); +// cp(1) copies the file a symlink operand points at; only `cp -R` copies the +// link itself. The builtin is the default only on Windows; on POSIX it is +// switched on by an env var that is read once per process, so every cp below +// runs in a child bun. +describe.concurrent("bunshell cp follows a symlink operand unless -R is given", () => { + const builtinEnv = { ...bunEnv, BUN_ENABLE_EXPERIMENTAL_SHELL_BUILTINS: "1" }; + + // Runs argv[2] through the shell inside `work/` and prints what cp returned. + const runCpScript = /* ts */ ` + import { $ } from "bun"; + import { join } from "node:path"; + const result = await $\`\${{ raw: process.argv[2] }}\`.cwd(join(import.meta.dir, "work")).nothrow().quiet(); + console.log(JSON.stringify({ exitCode: result.exitCode, stderr: result.stderr.toString() })); + `; + + /** + * A temp dir holding the runner script and `work/`, which contains + * `inner/target`, an empty `dest/`, the link `rel -> inner/target` and + * whatever `extra` adds. Returns the temp dir; `work()` locates the work dir. + */ + function setup(name: string, extra: DirectoryTree = {}) { + const dir = tempDir(`shell-cp-follow-${name}`, { + "run-cp.ts": runCpScript, + "work": { "inner/target": "target\n", "dest": {}, ...extra }, + }); + symlinkSync(join("inner", "target"), join(work(dir), "rel")); + return dir; + } + + function work(dir: string, ...inside: string[]): string { + return join(String(dir), "work", ...inside); + } + + async function cp(dir: string, command: string): Promise<{ exitCode: number; stderr: string }> { + await using proc = Bun.spawn({ + cmd: [bunExe(), "run-cp.ts", command], + cwd: String(dir), + env: builtinEnv, + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + expect(exitCode).toBe(0); + return JSON.parse(stdout); + } + + const copied = { exitCode: 0, stderr: "" }; + + /** What `work/` is now: a regular file's contents, a symlink's target, or `missing`. */ + function entry(dir: string, name: string): string { + const path = work(dir, name); + const stat = lstatSync(path, { throwIfNoEntry: false }); + if (stat === undefined) return "missing"; + if (stat.isSymbolicLink()) return `symlink -> ${readlinkSync(path)}`; + return `file: ${readFileSync(path, "utf8")}`; + } + + test("cp link file copies the file the link points at", async () => { + using dir = setup("file"); + expect(await cp(dir, "cp rel out")).toEqual(copied); + expect(entry(dir, "out")).toBe("file: target\n"); + }); + + test("cp link... dir copies the files the links point at", async () => { + using dir = setup("into-dir", { "outside.txt": "outside\n", "elsewhere": {} }); + symlinkSync(join("..", "outside.txt"), work(dir, "elsewhere", "up")); + expect(await cp(dir, "cp rel elsewhere/up dest")).toEqual(copied); + expect([entry(dir, "dest/rel"), entry(dir, "dest/up")]).toEqual(["file: target\n", "file: outside\n"]); + }); + + // Past 128 KiB the macOS copy switches from read/write to clonefile(). + test("a link to a large file is copied as a file", async () => { + const big = Buffer.alloc(300 * 1024, "big file\n").toString(); + using dir = setup("big", { big }); + symlinkSync("big", work(dir, "biglink")); + expect(await cp(dir, "cp biglink out")).toEqual(copied); + expect(lstatSync(work(dir, "out")).isSymbolicLink()).toBe(false); + expect(readFileSync(work(dir, "out"), "utf8")).toBe(big); + }); + + test("a dangling link is an error", async () => { + using dir = setup("dangling"); + symlinkSync("missing", work(dir, "dangling")); + expect(await cp(dir, "cp dangling out")).toEqual({ + exitCode: 1, + stderr: `cp: No such file or directory: ${work(dir, "dangling")}\n`, + }); + expect(entry(dir, "out")).toBe("missing"); + }); + + test("a link to a directory is an error without -R", async () => { + using dir = setup("dirlink"); + symlinkSync("inner", work(dir, "dirlink"), "dir"); + expect(await cp(dir, "cp dirlink out")).toEqual({ + exitCode: 1, + stderr: "cp: dirlink is a directory (not copied)\n", + }); + expect(entry(dir, "out")).toBe("missing"); + }); + + test("a link and the file it points at are the same file", async () => { + using dir = setup("identical"); + expect(await cp(dir, "cp rel inner/target")).toEqual({ + exitCode: 1, + stderr: "cp: rel and inner/target are identical (not copied)\n", + }); + expect(entry(dir, "inner/target")).toBe("file: target\n"); + }); + + test("a link and the same-named file it points at in the destination directory are the same file", async () => { + using dir = setup("identical-in-dir", { "elsewhere": {} }); + symlinkSync(join("..", "inner", "target"), work(dir, "elsewhere", "target")); + expect(await cp(dir, "cp elsewhere/target inner")).toEqual({ + exitCode: 1, + stderr: `cp: elsewhere/target and ${p("inner/target")} are identical (not copied)\n`, + }); + expect(entry(dir, "inner/target")).toBe("file: target\n"); + }); + + test("cp -R copies the links themselves", async () => { + using dir = setup("recursive"); + symlinkSync("inner", work(dir, "dirlink"), "dir"); + expect(await cp(dir, "cp -R rel dirlink dest")).toEqual(copied); + expect(entry(dir, "dest/rel")).toStartWith("symlink -> "); + expect(entry(dir, "dest/dirlink")).toStartWith("symlink -> "); + }); + + // Following the link must not mean reading the FIFO: open(2) on a FIFO with + // no writer blocks forever. + test.skipIf(isWindows)("a link to a FIFO is refused", async () => { + using dir = setup("fifo"); + mkfifo(work(dir, "fifo")); + symlinkSync("fifo", work(dir, "fifolink")); + expect(await cp(dir, "cp fifolink out")).toEqual({ + exitCode: 1, + stderr: `cp: Operation not supported: ${work(dir, "fifolink")}\n`, + }); + expect(entry(dir, "out")).toBe("missing"); + }); +}); + function expectSortedOutput(expected: string) { return (stdout: string, tempdir: string) => expect(sortedShellOutput(stdout).join("\n")).toEqual( From 0e62b6bd1c843f1e4131d688b413e628da7449d3 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 13 Aug 2026 06:33:31 +0000 Subject: [PATCH 2/4] shell(cp): refuse copying a file onto itself in both modes Take the source stat in both modes (stat without -R, lstat with -R) and compare it with the destination looked at the same way, so hard links, links and paths through directory symlinks are refused as identical whether or not -R is given. The message shows the destination as cp would land on it (operand plus basename, unnormalized). Tests cover the destination-side shapes (hard link, link, two links, file into its own directory, one identical operand among several, the -R forms) and, on macOS, a link to a file on another volume, which exercises the copyfile fallback. --- src/runtime/shell/builtin/cp.rs | 79 +++++---- test/js/bun/shell/commands/cp.test.ts | 240 +++++++++++++++++--------- 2 files changed, 202 insertions(+), 117 deletions(-) diff --git a/src/runtime/shell/builtin/cp.rs b/src/runtime/shell/builtin/cp.rs index fc8b42fa4002..c9e3a541543b 100644 --- a/src/runtime/shell/builtin/cp.rs +++ b/src/runtime/shell/builtin/cp.rs @@ -563,7 +563,7 @@ impl ShellCpTask { .is_some_and(|&c| resolve_path::Platform::AUTO.is_separator(c)) } - /// Classifies a path without following a symlink. + /// Classifies the target operand without following a symlink. fn is_dir(path: &bun_core::ZStr) -> bun_sys::Maybe { #[cfg(windows)] { @@ -582,10 +582,16 @@ impl ShellCpTask { } } - /// Is `tgt` (following symlinks, like the copy will) the file `src_stat` - /// describes? An inode number of 0 means the filesystem reports no identity. - fn is_same_file(src_stat: &bun_sys::Stat, tgt: &bun_core::ZStr) -> bool { - bun_sys::stat(tgt).is_ok_and(|tgt_stat| { + /// Is `tgt` the file `src_stat` describes? `follow` says whether a symlink + /// at `tgt` is looked through, and must match how `src_stat` was taken. + /// An inode number of 0 means the filesystem reports no identity. + fn is_same_file(src_stat: &bun_sys::Stat, tgt: &bun_core::ZStr, follow: bool) -> bool { + let tgt_stat = if follow { + bun_sys::stat(tgt) + } else { + bun_sys::lstat(tgt) + }; + tgt_stat.is_ok_and(|tgt_stat| { src_stat.st_ino != 0 && src_stat.st_ino == tgt_stat.st_ino && src_stat.st_dev == tgt_stat.st_dev @@ -630,21 +636,17 @@ impl ShellCpTask { // cp(1) copies the file a symlink operand points at; only `-R` copies // the link itself. - let src_stat = if self.opts.recursive { - None + let follow_src = !self.opts.recursive; + let src_stat = if follow_src { + bun_sys::stat(src) } else { - match bun_sys::stat(src) { - Ok(st) => Some(st), - Err(e) => return Some(ShellErr::new_sys(&e)), - } + bun_sys::lstat(src) }; - let src_is_dir = match &src_stat { - Some(st) => bun_sys::S::ISDIR(st.st_mode as _), - None => match Self::is_dir(src) { - Ok(x) => x, - Err(e) => return Some(ShellErr::new_sys(&e)), - }, + let src_stat = match src_stat { + Ok(st) => st, + Err(e) => return Some(ShellErr::new_sys(&e)), }; + let src_is_dir = bun_sys::S::ISDIR(src_stat.st_mode as _); // Any source directory without -R is an error. if src_is_dir && !self.opts.recursive { @@ -690,6 +692,7 @@ impl ShellCpTask { buf3.as_mut_slice(), &[tgt.as_bytes(), basename], ); + dest_basename = Some(basename); } else if self.operands == 2 { // source_dir -> new_target_dir. } else { @@ -725,28 +728,24 @@ impl ShellCpTask { _copying_many = true; } - // With the operand dereferenced, `cp link target-of-link` would read - // and write one file; cp(1) refuses that as the same file. - if let Some(src_stat) = &src_stat { - if Self::is_same_file(src_stat, tgt) { - let mut shown_buf = bun_paths::path_buffer_pool::get(); - let shown_tgt: &[u8] = match dest_basename { - Some(basename) => resolve_path::join_string_buf::( - &mut shown_buf[..], - &[&self.tgt, basename], - ), - None => &self.tgt, - }; - return Some(ShellErr::Custom( - format!( - "{} and {} are identical (not copied)", - bstr::BStr::new(&self.src), - bstr::BStr::new(shown_tgt) - ) - .into_bytes() - .into_boxed_slice(), - )); - } + // Copying a file onto itself (through a link, a hard link or a path + // going through a directory symlink, which the path comparison above + // misses) is refused, as cp(1) does. Reading and writing one file would + // otherwise go ahead, and the macOS copy unlinks the destination first. + if !src_is_dir && Self::is_same_file(&src_stat, tgt, follow_src) { + let shown_tgt = match dest_basename { + Some(basename) => bun_paths::join_sep_maybe_z::(&[&self.tgt, basename]), + None => self.tgt.as_slice().into(), + }; + return Some(ShellErr::Custom( + format!( + "{} and {} are identical (not copied)", + bstr::BStr::new(&self.src), + bstr::BStr::new(&shown_tgt) + ) + .into_bytes() + .into_boxed_slice(), + )); } self.src_absolute = Some(src.as_bytes().to_vec()); @@ -765,7 +764,7 @@ impl ShellCpTask { recursive: self.opts.recursive, force: true, error_on_exist: false, - dereference: !self.opts.recursive, + dereference: follow_src, }, }; diff --git a/test/js/bun/shell/commands/cp.test.ts b/test/js/bun/shell/commands/cp.test.ts index 6b7271305ec3..55fb8451caee 100644 --- a/test/js/bun/shell/commands/cp.test.ts +++ b/test/js/bun/shell/commands/cp.test.ts @@ -1,9 +1,9 @@ import { $ } from "bun"; import { shellInternals } from "bun:internal-for-testing"; import { describe, expect, test } from "bun:test"; -import { bunEnv, DirectoryTree, isWindows, tempDir, tempDirWithFiles } from "harness"; +import { bunEnv, DirectoryTree, isMacOS, isWindows, tempDir, tempDirWithFiles } from "harness"; import { mkfifo } from "mkfifo"; -import { lstatSync, readFileSync, readlinkSync, symlinkSync } from "node:fs"; +import { linkSync, lstatSync, readFileSync, readlinkSync, statSync, symlinkSync } from "node:fs"; import { join } from "node:path"; import { bunExe, createTestBuilder } from "../test_builder"; import { sortedShellOutput } from "../util"; @@ -176,11 +176,9 @@ describe.if(!builtinDisabled("cp"))("bunshell cp", async () => { }); }); -// cp(1) copies the file a symlink operand points at; only `cp -R` copies the -// link itself. The builtin is the default only on Windows; on POSIX it is -// switched on by an env var that is read once per process, so every cp below -// runs in a child bun. -describe.concurrent("bunshell cp follows a symlink operand unless -R is given", () => { +// The builtin is the default only on Windows; on POSIX it is switched on by an +// env var that is read once per process, so every cp below runs in a child bun. +describe.concurrent("bunshell cp operands that are links", () => { const builtinEnv = { ...bunEnv, BUN_ENABLE_EXPERIMENTAL_SHELL_BUILTINS: "1" }; // Runs argv[2] through the shell inside `work/` and prints what cp returned. @@ -194,14 +192,14 @@ describe.concurrent("bunshell cp follows a symlink operand unless -R is given", /** * A temp dir holding the runner script and `work/`, which contains * `inner/target`, an empty `dest/`, the link `rel -> inner/target` and - * whatever `extra` adds. Returns the temp dir; `work()` locates the work dir. + * whatever `extra` adds. Returns the temp dir; `work()` locates paths in it. */ function setup(name: string, extra: DirectoryTree = {}) { - const dir = tempDir(`shell-cp-follow-${name}`, { + const dir = tempDir(`shell-cp-links-${name}`, { "run-cp.ts": runCpScript, "work": { "inner/target": "target\n", "dest": {}, ...extra }, }); - symlinkSync(join("inner", "target"), join(work(dir), "rel")); + symlinkSync(join("inner", "target"), work(dir, "rel")); return dir; } @@ -224,6 +222,10 @@ describe.concurrent("bunshell cp follows a symlink operand unless -R is given", const copied = { exitCode: 0, stderr: "" }; + function identical(src: string, tgt: string) { + return { exitCode: 1, stderr: `cp: ${src} and ${tgt} are identical (not copied)\n` }; + } + /** What `work/` is now: a regular file's contents, a symlink's target, or `missing`. */ function entry(dir: string, name: string): string { const path = work(dir, name); @@ -233,87 +235,171 @@ describe.concurrent("bunshell cp follows a symlink operand unless -R is given", return `file: ${readFileSync(path, "utf8")}`; } - test("cp link file copies the file the link points at", async () => { - using dir = setup("file"); - expect(await cp(dir, "cp rel out")).toEqual(copied); - expect(entry(dir, "out")).toBe("file: target\n"); - }); + // Past 128 KiB the macOS copy switches from read/write to clonefile(), and + // unlinks an existing destination first. + const big = Buffer.alloc(300 * 1024, "big file\n").toString(); + + // cp(1) copies the file a symlink operand points at; only `cp -R` copies the + // link itself. + describe("a symlink source is followed unless -R is given", () => { + test("cp link file copies the file the link points at", async () => { + using dir = setup("file"); + expect(await cp(dir, "cp rel out")).toEqual(copied); + expect(entry(dir, "out")).toBe("file: target\n"); + }); - test("cp link... dir copies the files the links point at", async () => { - using dir = setup("into-dir", { "outside.txt": "outside\n", "elsewhere": {} }); - symlinkSync(join("..", "outside.txt"), work(dir, "elsewhere", "up")); - expect(await cp(dir, "cp rel elsewhere/up dest")).toEqual(copied); - expect([entry(dir, "dest/rel"), entry(dir, "dest/up")]).toEqual(["file: target\n", "file: outside\n"]); - }); + test("cp link... dir copies the files the links point at", async () => { + using dir = setup("into-dir", { "outside.txt": "outside\n", "elsewhere": {} }); + symlinkSync(join("..", "outside.txt"), work(dir, "elsewhere", "up")); + expect(await cp(dir, "cp rel elsewhere/up dest")).toEqual(copied); + expect([entry(dir, "dest/rel"), entry(dir, "dest/up")]).toEqual(["file: target\n", "file: outside\n"]); + }); - // Past 128 KiB the macOS copy switches from read/write to clonefile(). - test("a link to a large file is copied as a file", async () => { - const big = Buffer.alloc(300 * 1024, "big file\n").toString(); - using dir = setup("big", { big }); - symlinkSync("big", work(dir, "biglink")); - expect(await cp(dir, "cp biglink out")).toEqual(copied); - expect(lstatSync(work(dir, "out")).isSymbolicLink()).toBe(false); - expect(readFileSync(work(dir, "out"), "utf8")).toBe(big); - }); + test("a link to a large file is copied as a file", async () => { + using dir = setup("big", { big }); + symlinkSync("big", work(dir, "biglink")); + expect(await cp(dir, "cp biglink out")).toEqual(copied); + expect(lstatSync(work(dir, "out")).isSymbolicLink()).toBe(false); + expect(readFileSync(work(dir, "out"), "utf8")).toBe(big); + }); - test("a dangling link is an error", async () => { - using dir = setup("dangling"); - symlinkSync("missing", work(dir, "dangling")); - expect(await cp(dir, "cp dangling out")).toEqual({ - exitCode: 1, - stderr: `cp: No such file or directory: ${work(dir, "dangling")}\n`, + // The temp dir is on the data volume and /usr/share on the sealed system + // volume, so clonefile() fails with EXDEV and the copy takes the copyfile() + // fallback, the one large-file path the other tests do not reach. + test.skipIf(!isMacOS)("a link to a large file on another volume is copied as a file", async () => { + const systemFile = "/usr/share/dict/words"; + expect(statSync(systemFile).size).toBeGreaterThan(128 * 1024); + using dir = setup("other-volume"); + symlinkSync(systemFile, work(dir, "syslink")); + expect(await cp(dir, "cp syslink out")).toEqual(copied); + expect(lstatSync(work(dir, "out")).isSymbolicLink()).toBe(false); + expect(readFileSync(work(dir, "out")).equals(readFileSync(systemFile))).toBe(true); }); - expect(entry(dir, "out")).toBe("missing"); - }); - test("a link to a directory is an error without -R", async () => { - using dir = setup("dirlink"); - symlinkSync("inner", work(dir, "dirlink"), "dir"); - expect(await cp(dir, "cp dirlink out")).toEqual({ - exitCode: 1, - stderr: "cp: dirlink is a directory (not copied)\n", + test("a dangling link is an error", async () => { + using dir = setup("dangling"); + symlinkSync("missing", work(dir, "dangling")); + expect(await cp(dir, "cp dangling out")).toEqual({ + exitCode: 1, + stderr: `cp: No such file or directory: ${work(dir, "dangling")}\n`, + }); + expect(entry(dir, "out")).toBe("missing"); }); - expect(entry(dir, "out")).toBe("missing"); - }); - test("a link and the file it points at are the same file", async () => { - using dir = setup("identical"); - expect(await cp(dir, "cp rel inner/target")).toEqual({ - exitCode: 1, - stderr: "cp: rel and inner/target are identical (not copied)\n", + test("a link to a directory is an error without -R", async () => { + using dir = setup("dirlink"); + symlinkSync("inner", work(dir, "dirlink"), "dir"); + expect(await cp(dir, "cp dirlink out")).toEqual({ + exitCode: 1, + stderr: "cp: dirlink is a directory (not copied)\n", + }); + expect(entry(dir, "out")).toBe("missing"); }); - expect(entry(dir, "inner/target")).toBe("file: target\n"); - }); - test("a link and the same-named file it points at in the destination directory are the same file", async () => { - using dir = setup("identical-in-dir", { "elsewhere": {} }); - symlinkSync(join("..", "inner", "target"), work(dir, "elsewhere", "target")); - expect(await cp(dir, "cp elsewhere/target inner")).toEqual({ - exitCode: 1, - stderr: `cp: elsewhere/target and ${p("inner/target")} are identical (not copied)\n`, + // Following the link must not mean reading the FIFO: open(2) on a FIFO with + // no writer blocks forever. + test.skipIf(isWindows)("a link to a FIFO is refused", async () => { + using dir = setup("fifo"); + mkfifo(work(dir, "fifo")); + symlinkSync("fifo", work(dir, "fifolink")); + expect(await cp(dir, "cp fifolink out")).toEqual({ + exitCode: 1, + stderr: `cp: Operation not supported: ${work(dir, "fifolink")}\n`, + }); + expect(entry(dir, "out")).toBe("missing"); }); - expect(entry(dir, "inner/target")).toBe("file: target\n"); - }); - test("cp -R copies the links themselves", async () => { - using dir = setup("recursive"); - symlinkSync("inner", work(dir, "dirlink"), "dir"); - expect(await cp(dir, "cp -R rel dirlink dest")).toEqual(copied); - expect(entry(dir, "dest/rel")).toStartWith("symlink -> "); - expect(entry(dir, "dest/dirlink")).toStartWith("symlink -> "); + test("cp -R copies the links themselves", async () => { + using dir = setup("recursive"); + symlinkSync("inner", work(dir, "dirlink"), "dir"); + expect(await cp(dir, "cp -R rel dirlink dest")).toEqual(copied); + expect(entry(dir, "dest/rel")).toStartWith("symlink -> "); + expect(entry(dir, "dest/dirlink")).toStartWith("symlink -> "); + }); }); - // Following the link must not mean reading the FIFO: open(2) on a FIFO with - // no writer blocks forever. - test.skipIf(isWindows)("a link to a FIFO is refused", async () => { - using dir = setup("fifo"); - mkfifo(work(dir, "fifo")); - symlinkSync("fifo", work(dir, "fifolink")); - expect(await cp(dir, "cp fifolink out")).toEqual({ - exitCode: 1, - stderr: `cp: Operation not supported: ${work(dir, "fifolink")}\n`, + // The source and the destination are compared by inode, so every way of + // naming the same file twice is refused, not only spelling the path twice. + describe("copying a file onto itself is refused", () => { + test("a link and the file it points at", async () => { + using dir = setup("link-and-target"); + expect(await cp(dir, "cp rel inner/target")).toEqual(identical("rel", "inner/target")); + expect(entry(dir, "inner/target")).toBe("file: target\n"); + }); + + test("a link and the large file it points at", async () => { + using dir = setup("link-and-big-target", { big }); + symlinkSync("big", work(dir, "biglink")); + expect(await cp(dir, "cp biglink big")).toEqual(identical("biglink", "big")); + expect(readFileSync(work(dir, "big"), "utf8")).toBe(big); + }); + + test("a file and a link pointing at it", async () => { + using dir = setup("target-and-link"); + expect(await cp(dir, "cp inner/target rel")).toEqual(identical("inner/target", "rel")); + expect(entry(dir, "rel")).toBe(`symlink -> ${join("inner", "target")}`); + }); + + test("two links to one file", async () => { + using dir = setup("two-links"); + symlinkSync(join("inner", "target"), work(dir, "rel2")); + expect(await cp(dir, "cp rel rel2")).toEqual(identical("rel", "rel2")); + expect(entry(dir, "rel2")).toBe(`symlink -> ${join("inner", "target")}`); + }); + + test("a file and a hard link to it", async () => { + using dir = setup("hard-link"); + linkSync(work(dir, "inner", "target"), work(dir, "hard")); + expect(await cp(dir, "cp inner/target hard")).toEqual(identical("inner/target", "hard")); + expect(entry(dir, "hard")).toBe("file: target\n"); + }); + + test("a file and the directory it is in", async () => { + using dir = setup("own-directory"); + expect(await cp(dir, "cp inner/target inner")).toEqual(identical("inner/target", p("inner/target"))); + expect(entry(dir, "inner/target")).toBe("file: target\n"); + }); + + test("a link and the same-named file it points at in the destination directory", async () => { + using dir = setup("link-into-target-dir", { "elsewhere": {} }); + symlinkSync(join("..", "inner", "target"), work(dir, "elsewhere", "target")); + expect(await cp(dir, "cp elsewhere/target inner")).toEqual(identical("elsewhere/target", p("inner/target"))); + expect(entry(dir, "inner/target")).toBe("file: target\n"); + }); + + test("the other operands are still copied", async () => { + using dir = setup("one-of-many", { "outside.txt": "outside\n" }); + linkSync(work(dir, "inner", "target"), work(dir, "dest", "rel")); + expect(await cp(dir, "cp rel outside.txt dest")).toEqual(identical("rel", p("dest/rel"))); + expect([entry(dir, "dest/rel"), entry(dir, "dest/outside.txt")]).toEqual(["file: target\n", "file: outside\n"]); + }); + + test("with -R, a file and a hard link to it", async () => { + using dir = setup("recursive-hard-link"); + linkSync(work(dir, "inner", "target"), work(dir, "hard")); + expect(await cp(dir, "cp -R inner/target hard")).toEqual(identical("inner/target", "hard")); + expect(entry(dir, "hard")).toBe("file: target\n"); + }); + + test("with -R, a file and itself inside the destination directory", async () => { + using dir = setup("recursive-into-dir"); + linkSync(work(dir, "inner", "target"), work(dir, "dest", "target")); + expect(await cp(dir, "cp -R inner/target dest")).toEqual(identical("inner/target", p("dest/target"))); + expect(entry(dir, "dest/target")).toBe("file: target\n"); + }); + + test("with -R, a large file and itself reached through a directory link", async () => { + using dir = setup("recursive-through-dirlink", { "d/big": big }); + symlinkSync("d", work(dir, "dlink"), "dir"); + expect(await cp(dir, "cp -R d/big dlink/big")).toEqual(identical("d/big", "dlink/big")); + expect(readFileSync(work(dir, "d", "big"), "utf8")).toBe(big); + }); + + test("with -R, a link and itself inside the destination directory", async () => { + using dir = setup("recursive-link"); + expect(await cp(dir, "cp -R rel .")).toEqual(identical("rel", p("./rel"))); + expect(entry(dir, "rel")).toBe(`symlink -> ${join("inner", "target")}`); }); - expect(entry(dir, "out")).toBe("missing"); }); }); From 3d2f08721a3f6fb1c0c51cc19e4ddde2ac00c6ba Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 13 Aug 2026 07:00:39 +0000 Subject: [PATCH 3/4] shell(cp): shorten the comments on the new helpers --- src/runtime/node/node_fs.rs | 16 ++++++---------- src/runtime/shell/builtin/cp.rs | 12 +++++------- 2 files changed, 11 insertions(+), 17 deletions(-) diff --git a/src/runtime/node/node_fs.rs b/src/runtime/node/node_fs.rs index d43082db4dad..dd1e0f565601 100644 --- a/src/runtime/node/node_fs.rs +++ b/src/runtime/node/node_fs.rs @@ -4343,11 +4343,9 @@ pub mod args { pub(crate) recursive: bool, pub(crate) error_on_exist: bool, pub(crate) force: bool, - /// A symlink source is followed and the file it points at is copied, - /// the way `cp` without `-R` treats its operands. Off, a symlink is - /// recreated (`fs.cp` handles `dereference` itself and never sets - /// this). Only consulted by `copy_single_file_sync`; directories are - /// still classified without following links. + /// Copy the file a symlink source points at instead of recreating the + /// link (`cp` without `-R`). Read by `copy_single_file_sync` only; + /// `fs.cp` never sets it. pub(crate) dereference: bool, } @@ -8546,9 +8544,8 @@ impl NodeFS { Syscall::symlink(ZStr::from_buf(&resolved_buf[..], resolved_len), dest) } - /// The stat `copy_single_file_sync` classifies its source by. Callers pass - /// the `lstat` they already took as `reuse_stat`; when dereferencing, a - /// symlink is stat'd again so the copy is described by its target. + /// `reuse_stat` is the caller's `lstat`, so when dereferencing a symlink + /// is stat'd again to describe its target. #[cfg(not(windows))] fn cp_source_stat( src: &ZStr, @@ -8567,8 +8564,7 @@ impl NodeFS { } } - /// Opens the file a dereferenced source resolves to. The kind is checked - /// from the stat first: `open(2)` on a FIFO blocks until a writer shows up. + /// The kind is checked before the open: `open(2)` on a FIFO blocks. #[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))] fn cp_open_dereferenced_source(src: &ZStr, reuse_stat: Option<&sys::Stat>) -> Maybe { let stat_ = Self::cp_source_stat(src, reuse_stat, true)?; diff --git a/src/runtime/shell/builtin/cp.rs b/src/runtime/shell/builtin/cp.rs index c9e3a541543b..f92d584b884f 100644 --- a/src/runtime/shell/builtin/cp.rs +++ b/src/runtime/shell/builtin/cp.rs @@ -582,9 +582,8 @@ impl ShellCpTask { } } - /// Is `tgt` the file `src_stat` describes? `follow` says whether a symlink - /// at `tgt` is looked through, and must match how `src_stat` was taken. - /// An inode number of 0 means the filesystem reports no identity. + /// `follow` must match how `src_stat` was taken. An inode number of 0 + /// means the filesystem reports no identity. fn is_same_file(src_stat: &bun_sys::Stat, tgt: &bun_core::ZStr, follow: bool) -> bool { let tgt_stat = if follow { bun_sys::stat(tgt) @@ -728,10 +727,9 @@ impl ShellCpTask { _copying_many = true; } - // Copying a file onto itself (through a link, a hard link or a path - // going through a directory symlink, which the path comparison above - // misses) is refused, as cp(1) does. Reading and writing one file would - // otherwise go ahead, and the macOS copy unlinks the destination first. + // A link, hard link or directory symlink can name `src` again; copying + // a file onto itself is refused like cp(1) does (on macOS the copy + // would unlink it first). if !src_is_dir && Self::is_same_file(&src_stat, tgt, follow_src) { let shown_tgt = match dest_basename { Some(basename) => bun_paths::join_sep_maybe_z::(&[&self.tgt, basename]), From 581c359224cfa73c6f97f471ce1f0bb6da7d8fdc Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 13 Aug 2026 07:36:30 +0000 Subject: [PATCH 4/4] shell(cp): under -R, also refuse a link on one side of the copy With -R the destination is still written through a link, and a link source would be recreated over the file it points at, so when exactly one operand is a link the link side is followed before comparing inodes. Two links to one file stay copyable, as in cp(1). --- src/runtime/shell/builtin/cp.rs | 43 +++++++++++++++++++++------ test/js/bun/shell/commands/cp.test.ts | 24 +++++++++++++++ 2 files changed, 58 insertions(+), 9 deletions(-) diff --git a/src/runtime/shell/builtin/cp.rs b/src/runtime/shell/builtin/cp.rs index f92d584b884f..0c9cdef79972 100644 --- a/src/runtime/shell/builtin/cp.rs +++ b/src/runtime/shell/builtin/cp.rs @@ -582,19 +582,44 @@ impl ShellCpTask { } } - /// `follow` must match how `src_stat` was taken. An inode number of 0 - /// means the filesystem reports no identity. - fn is_same_file(src_stat: &bun_sys::Stat, tgt: &bun_core::ZStr, follow: bool) -> bool { + /// An inode number of 0 means the filesystem reports no identity. + fn is_same_inode(a: &bun_sys::Stat, b: &bun_sys::Stat) -> bool { + a.st_ino != 0 && a.st_ino == b.st_ino && a.st_dev == b.st_dev + } + + /// Would the copy read and write one file? `follow` must match how + /// `src_stat` was taken. + fn is_same_file( + src: &bun_core::ZStr, + src_stat: &bun_sys::Stat, + tgt: &bun_core::ZStr, + follow: bool, + ) -> bool { let tgt_stat = if follow { bun_sys::stat(tgt) } else { bun_sys::lstat(tgt) }; - tgt_stat.is_ok_and(|tgt_stat| { - src_stat.st_ino != 0 - && src_stat.st_ino == tgt_stat.st_ino - && src_stat.st_dev == tgt_stat.st_dev - }) + let Ok(tgt_stat) = tgt_stat else { + return false; + }; + if Self::is_same_inode(src_stat, &tgt_stat) { + return true; + } + if follow { + return false; + } + // -R copies a link as a link, so one link may be copied over another + // link to the same file. A link on one side only is copied onto, or + // recreated over, the file it points at. + match ( + bun_sys::S::ISLNK(src_stat.st_mode as _), + bun_sys::S::ISLNK(tgt_stat.st_mode as _), + ) { + (true, false) => bun_sys::stat(src).is_ok_and(|s| Self::is_same_inode(&s, &tgt_stat)), + (false, true) => bun_sys::stat(tgt).is_ok_and(|t| Self::is_same_inode(src_stat, &t)), + _ => false, + } } /// Resolves src/tgt to absolute paths, classifies them per the three @@ -730,7 +755,7 @@ impl ShellCpTask { // A link, hard link or directory symlink can name `src` again; copying // a file onto itself is refused like cp(1) does (on macOS the copy // would unlink it first). - if !src_is_dir && Self::is_same_file(&src_stat, tgt, follow_src) { + if !src_is_dir && Self::is_same_file(src, &src_stat, tgt, follow_src) { let shown_tgt = match dest_basename { Some(basename) => bun_paths::join_sep_maybe_z::(&[&self.tgt, basename]), None => self.tgt.as_slice().into(), diff --git a/test/js/bun/shell/commands/cp.test.ts b/test/js/bun/shell/commands/cp.test.ts index 55fb8451caee..8a40890f5aab 100644 --- a/test/js/bun/shell/commands/cp.test.ts +++ b/test/js/bun/shell/commands/cp.test.ts @@ -400,6 +400,30 @@ describe.concurrent("bunshell cp operands that are links", () => { expect(await cp(dir, "cp -R rel .")).toEqual(identical("rel", p("./rel"))); expect(entry(dir, "rel")).toBe(`symlink -> ${join("inner", "target")}`); }); + + // Under -R the file is written through a link at the destination, and a + // link source would be recreated over the very file it points at. + test("with -R, a file and a link pointing at it", async () => { + using dir = setup("recursive-target-and-link"); + expect(await cp(dir, "cp -R inner/target rel")).toEqual(identical("inner/target", "rel")); + expect(entry(dir, "rel")).toBe(`symlink -> ${join("inner", "target")}`); + }); + + test("with -R, a link and the file it points at", async () => { + using dir = setup("recursive-link-and-target"); + expect(await cp(dir, "cp -R rel inner/target")).toEqual(identical("rel", "inner/target")); + expect(entry(dir, "inner/target")).toBe("file: target\n"); + }); + + // Two links to one file are not the same file under -R: the link itself is + // what gets copied, as cp(1) also allows. + test("with -R, two links to one file are copied", async () => { + using dir = setup("recursive-two-links"); + symlinkSync(join("inner", "target"), work(dir, "rel2")); + expect(await cp(dir, "cp -R rel rel2")).toEqual(copied); + expect(entry(dir, "rel2")).toStartWith("symlink -> "); + expect(entry(dir, "inner/target")).toBe("file: target\n"); + }); }); });