Repository navigation
Conversation
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.
|
Warning Review limit reached
Next review available in: 8 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (3)
Comment |
|
Updated 6:45 AM PT - Aug 13th, 2026
❌ @robobun, your commit 581c359 has 1 failures in
🧪 To try this PR locally: bunx bun-pr 37954That installs a local version of the PR into your bun-37954 --bun |
|
Status: reproduced on bun 1.4.0 (Linux) with The block "bunshell cp operands that are links" in |
There was a problem hiding this comment.
I reviewed this PR and didn't find any bugs. Because it changes the shared copy_single_file_sync primitive across four platform branches (Linux, macOS, FreeBSD, Windows) and the Windows path is not yet verified per the status comment, a human look would still be worthwhile.
What was reviewed:
dereference: falsekeeps every existing arm ofcopy_single_file_syncbyte-for-byte, and the only otherCpFlagsconstructor (fs.cp'sfrom_js) sets it tofalse, sofs.cp/fs.cpSyncare unaffected.- The same-file guard:
bun_sys::staton Windows goes throughsys_uv::stat, and libuv populatesst_ino/st_devfrom the file index / volume serial, so the inode comparison is meaningful there too;st_ino == 0disables the check. - The FIFO hazard on the dereferencing Linux/FreeBSD path —
cp_open_dereferenced_sourcestats beforeopenand rejects non-regular targets withENOTSUP, so it can't block; covered by the new FIFO test. - The macOS
clonefileunlink-then-clone path for >128 KiB files — the same-file guard runs before the copy is scheduled, socp link target-of-linkcan't reach the unlink.
Extended reasoning...
Overview
The PR makes the shell cp builtin follow symlink operands (matching cp(1)) unless -R is given. It touches three files: src/runtime/shell/builtin/cp.rs (classify the source with stat instead of lstat when not recursive, add a same-file guard by st_dev/st_ino), src/runtime/node/node_fs.rs (add a dereference flag to CpFlags and honour it in each platform branch of copy_single_file_sync), and test/js/bun/shell/commands/cp.test.ts (nine new tests spawning a child bun with the builtin enabled).
Security risks
None identified. This is file-copy semantics for the shell builtin; no auth, crypto, or untrusted-input parsing is involved. The one safety-adjacent concern — the macOS >128 KiB path unlinks the destination before clonefile, which with dereferencing could delete the only copy of a file when copying a link onto its own target — is handled by the new same-file guard in run_from_thread_pool_impl, which runs before the copy is scheduled.
Level of scrutiny
Medium-high. copy_single_file_sync is the per-file primitive shared by fs.cp, fs.cpSync, and the shell, and it has four platform-specific arms. The change is carefully gated on the new flag (with the flag off, cp_source_stat(.., false) returns reuse_stat or takes the same lstat as before, and the Linux/FreeBSD/Windows arms take exactly their old code paths), and I confirmed the only other CpFlags construction site sets dereference: false. But per-platform file I/O with subtle OS semantics (O_NOFOLLOW/ELOOP vs EMLINK, COPYFILE_NOFOLLOW_SRC, reparse points, clonefile) is exactly the class of change REVIEW.md flags for cross-platform scrutiny.
Other factors
- The robobun status comment says the Windows build has not yet been run against the new tests; the builtin is the default on Windows, so that lane matters most.
- The PR description notes a test-expectation conflict with #37937 depending on merge order — a human should coordinate.
- One minor observation: the macOS branch previously attached the source path to an
lstatfailure viasync_error_buf;cp_source_statnow propagates the rawSyscall::stat/lstaterror with?. In practice the shell path always passesreuse_stat, and callers wrap errors, so this is unlikely to be user-visible — but it's the kind of small behaviour delta a maintainer may want to confirm. - Test coverage is thorough (file link, links-into-dir, 300 KiB clonefile path, dangling link, dir link, both same-file forms, FIFO, and
-Rstill copying links), and the tests follow harness conventions (tempDir,bunEnvspread, subprocess with drained pipes,test.concurrent).
|
Two follow-ups on the review above:
|
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.
|
Pushed two more commits after a review pass over the first revision:
Re-verified on Windows x64 (this branch built there): the file passes, 48 pass / 2 skip, and the |
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).
|
581c359 refines the |
There was a problem hiding this comment.
Thanks — 581c359 addresses the earlier note: is_same_file now also follows the link on whichever side has one under -R, and the two new tests (cp -R inner/target rel and cp -R rel inner/target) pin both directions. This automated review pass found no further issues.
Because the change threads a new dereference mode through copy_single_file_sync across four platform arms (Linux/FreeBSD open, macOS clonefile/copyfile, Windows reparse-point → CopyFileW) and that primitive is shared with fs.cp, a human look at the per-platform branches would still be worthwhile.
What was reviewed:
- Verified
dereference: falseleaves every existing arm ofcopy_single_file_syncbyte-identical in behaviour, andfs.cp'sCp::from_jsnever sets it. - Traced the new
is_same_fileunder-R: the(link, file)/(file, link)arms now catch the cases the earlier revision missed;(link, link)is intentionally allowed and covered by "with -R, two links to one file are copied". - Checked the FIFO guard: kind is checked via
statbefore opening withoutO_NOFOLLOW, so the dereferencing open cannot block on a FIFO.
Extended reasoning...
Overview
The PR changes the shell cp builtin to follow symlink source operands unless -R is given (matching cp(1)), and adds an inode-based same-file check so copying a file onto itself via a link/hardlink/directory-symlink is refused. To do so it adds a dereference flag to args::CpFlags and teaches NodeFS::copy_single_file_sync (in src/runtime/node/node_fs.rs) to honour it in each platform arm; ShellCpTask::run_from_thread_pool_impl (in src/runtime/shell/builtin/cp.rs) now classifies the source with stat/lstat per -R and runs the new is_same_file guard once the final destination path is known. ~250 lines of new tests in test/js/bun/shell/commands/cp.test.ts cover both halves.
Progress since the last review
My earlier inline note pointed out that under -R the identity check compared lstat(src) against lstat(tgt), so cp -R f l with l -> f (and its reverse) slipped through. Commit 581c359 adds the match (ISLNK(src), ISLNK(tgt)) fall-through in is_same_file that follows whichever side is a link and re-compares, plus two tests pinning both directions and one confirming that two distinct links to the same file are still allowed under -R. That resolves the note.
Security risks
Nothing sensitive is exposed. The change makes symlink handling in the shell builtin stricter (dangling links and links to directories are now errors without -R; copying onto self is refused), and the FIFO pre-check prevents the newly-following open from blocking. The fs.cp binding leaves dereference at its false default, so its behaviour is unchanged. The one thing worth a human eye is that copy_single_file_sync is a shared primitive: each per-platform arm (macOS clonefile/copyfile flag, Windows reparse-point vs CopyFileW, Linux/FreeBSD open flags) is gated on the new flag and the flag-off path is meant to be identical to before, which is what my read confirms — but only Linux and Windows have been run.
Level of scrutiny
Moderate–high. This is not a mechanical change: it alters symlink semantics in native filesystem code across four OS-specific branches of a primitive shared with fs.cp, and the same-file logic is subtle enough that it took two follow-up commits (0e62b6b to extend it to -R, 581c359 to catch link-on-one-side) to converge. The test coverage is thorough (23 new cases including large-file/clonefile, cross-volume copyfile fallback, FIFO, dangling link, hardlinks, directory symlinks, both modes) and the PR has been verified on Linux and Windows debug builds, but macOS and FreeBSD are asserted by cross-target cargo check only.
Other factors
The two unresolved comment-cop bot notes on cp.rs:591/614 flag the new 2–3-line invariant comments on is_same_file; these are the same automated pattern-match the author already justified for earlier instances and are not substantive. Given the cross-platform native surface and the shared primitive, I'm deferring rather than approving.
|
Thanks. On the platform coverage point: Linux and Windows have been run locally on this head (debug builds; the file passes on both, and the Windows run includes the pre-existing |
|
The macOS lanes have now run on this head (build 94338): macOS 14 and 26 both pass, so the macOS arm, including the cross-volume copyfile fallback test, is verified on real hardware as well. The single remaining red lane is the pre-existing |
|
Closing this PR because it has been inactive for more than 90 days. |
Problem
cpbuiltin (the default on Windows,BUN_ENABLE_EXPERIMENTAL_SHELL_BUILTINS=1on POSIX) copies a symlink operand as a link even without-R. cp(1) follows the operand unless-R(or-P) is given and produces a regular file:cp dangling outandcp link-to-dir outexit 0 and create a link (cp: "cannot stat" / "omitting directory").cp link target-of-link,cp file hardlink,cp file dirwithdir/filehard-linked,cp -R file hardlink, and so on exit 0 (cp: "are the same file"). The only same-file check compares the two path strings. On macOS a file over 128 KiB is copied by unlinking the destination and cloning the source, so in these cases the file's only name is removed before the clone and the data is lost.ShellCpTask::run_from_thread_pool_impl(src/runtime/shell/builtin/cp.rs) classifies the source withlstat(GetFileAttributesWon Windows) whether or not-Rwas given, and the native copy it hands the operand to,NodeFS::copy_single_file_sync(src/runtime/node/node_fs.rs), never follows a symlink: it opens withO_NOFOLLOWand recreates the link onELOOP(Linux/FreeBSD), copies withCOPYFILE_NOFOLLOW_SRC(macOS), or takes the reparse-point branch (Windows). So the builtin always behaves ascp -P; the flag parser also rejects-H/-L/-P, so there is no way to opt out.Fix
cp.rs: the source operand is classified withstatwithout-R(follows the link, on every platform) andlstatwith-R, so a link to a directory is reported as a directory and a dangling link as "No such file or directory", whilecp -R link deststill copies the link itself. The-Rclassification is what the POSIX build already did; on Windows it moves fromGetFileAttributesWtolstat, which changes no outcome (checked by hand: directory symlinks and junctions are still recreated as links under-R, since the native copy decides that on its own).cp.rs: once the final destination path is known, it is compared byst_dev/st_inowith the source, looked at the same way the source was (statwithout-R,lstatwith it), and refused with "aandbare identical (not copied)" when it is the same file, in both modes. Under-R, when exactly one operand is a link, that side is additionally followed and compared, because the destination is written through a link and a link source would be recreated over the file it points at (cp -R f link-to-f,cp -R link-to-f f); two different links to one file remain copyable, since the link itself is what gets copied. This gives the same exit code as GNU cp 9.7 on every shape tried (listed in the review thread). The message names the destination the copy would have landed on (operand plus basename when one was appended). An inode number of 0 (a filesystem without file identity) disables the check; the existing path comparison stays as the fallback.node_fs.rs:args::CpFlagsgetsdereference, set by the shell when-Ris absent and left off by thefs.cp/fs.cpSyncbinding.copy_single_file_synchonours it per platform:cp_open_dereferenced_sourcechecks the kind from a followingstatand then opens withoutO_NOFOLLOW. The kind is checked before the open becauseopen(2)on a FIFO blocks until a writer appears; a non-regular target fails withENOTSUP, the error the existing post-openfstatcheck already uses for non-regular sources.cp_source_stat, which re-stats a symlink when dereferencing (callers pass theirlstatasreuse_stat).clonefile(.., 0)and the plainopenin the existing regular-file paths already follow links; thecopyfilefallback dropsCOPYFILE_NOFOLLOW_SRCwhen dereferencing.CopyFileWbranch when dereferencing;CopyFileWcopies the target of a symlink source.-Ris given, and refuse a source and destination that are one file), and the native change is confined to the dereferencing mode: with the flag off, every arm ofcopy_single_file_syncruns the code it ran before (cp_source_stat(.., false)returnsreuse_stator takes the samelstat), andfs.cpnever sets the flag (its JS layer implementsdereferenceitself and only sends regular files to the native copy). Comparing inodes in the mode's own follow semantics is what makes the check meaningful under-Rtoo: there the operand is a link that is copied as a link, so it is the link's own inode that must not be the destination (cp -R link .).-H/-L/-Pare still rejected as unsupported, the link-target rewriting under-Rthat shell(cp): copy symlinks with their targets as written #37942 fixes is untouched, copying a directory into itself is shell(cp): refuse copying a directory into itself and walk trees without recursion #37927, and the destination operand is still classified without following links (reported separately).test/js/bun/shell/commands/cp.test.ts, new block "bunshell cp operands that are links" (each cp runs in a child bun with the builtin enabled). Following: a file link, several links into a directory, a link to a 300 KiB file (theclonefilepath on macOS), on macOS a link to/usr/share/dict/words(another volume, soclonefilefails withEXDEVand thecopyfilefallback runs), a dangling link, a link to a directory, a link to a FIFO (POSIX), and-Rstill copying the links themselves. Same file: link and target (small and 300 KiB), target and link, two links, a hard link, a file into its own directory, a link into the directory holding its target, one identical operand among several (the others are still copied), and under-Ra hard link, a file into a directory holding a hard link of it, a 300 KiB file through a directory symlink, a link into its own directory, a file onto a link to it, a link onto its target, and (allowed) one link over another link to the same file. On bun 1.4.0 on Linux 20 of the 22 applicable tests fail (the two that pass pin behaviour that is meant to stay:-Rcopying links as links, and the two-link case); the whole file passes with the fix on a Linux and a Windows debug build (51 pass / 2 skip on Windows, including the pre-existingcpsuite that only runs there; on the Windows canary the same cases fail except the link-to-directory one, which was already an error there).test/js/node/fs/cp.test.tsandcp-symlink-target.test.tspass with the fix (one test incp.test.tshits its 5 s budget on this debug/ASAN build; its child completes successfully in about 4 s when run directly, and it exercises the JS-layer recursive copy, which this diff does not touch).cargo check -p bun_runtimepasses for the darwin, windows-msvc and freebsd targets; clippy is clean. On CI (build 94338 for this head) the macOS 14 and 26, Windows and Linux test lanes all pass, which covers the macOS arm (including the cross-volumecopyfiletest) on real hardware; the one red lane istest/cli/run/require-cache.test.tson the x64 ASAN lane, which fails on main as well and is unrelated to this change.cp link outwithout-Rand expects a link; after this change that command refuses the FIFO behind the link instead (covered by the FIFO test here), so whichever PR lands second needs that one expectation updated.Background
cpbuiltin:ShellCpTaskruns on the work pool, resolves the operands to absolute paths, decides which of the POSIXcpsynopses applies (file to file,-Rsources to target, files into a directory), and then starts aShellAsyncCpTask, the sameNewAsyncCpTaskthatfs.promises.cpuses. For a non-directory source that task callscopy_single_file_synconce; for a directory it walks the tree and calls it per entry.copy_single_file_syncis the per-file primitive shared byfs.cp,fs.cpSyncand the shell. Its contract so far was "copy the entry as it is", which is what a recursive copy wants for the links inside a tree;dereferenceadds the "copy what the operand points at" mode that a non-recursive cp wants for its operands.reuse_stat: callers that alreadylstated the source (to tell directories from files) pass that stat down so the primitive does not repeat the syscall. When dereferencing, a stat that says "symlink" describes the wrong object, which is whycp_source_statreplaces it with a followingstat.statvslstat:statreports the file a symlink points at,lstatreports the link itself (symlinks in the middle of the path are followed by both). Two paths name one file when theirst_devandst_inomatch; hard links and paths through directory symlinks are the cases a string comparison misses. libuv fills these in on Windows from the volume serial number and file index, so the same comparison works there.-Rswitches to copying links as links (-P), with-H/-Las opt-ins to follow; and a source and destination that resolve to the same inode are refused as the same file.cpis normally spawned andBUN_ENABLE_EXPERIMENTAL_SHELL_BUILTINS=1, read once per process, switches the builtin on, which is why the tests spawn a child bun per case.Earlier version of this PR
The first revision only ran the same-file check without
-R, framed as a consequence of dereferencing. Review pointed out that the-Rhalf then kept the old per-platform behaviour forcp -R file hardlinkand friends (including the macOS unlink-before-clone data loss), that the destination-side refusals were untested, and that thecopyfilefallback on macOS was unexercised; the second commit addresses all three.