diff --git a/src/runtime/webcore/blob/copy_file.rs b/src/runtime/webcore/blob/copy_file.rs index 5fda339a635d..b966708affa3 100644 --- a/src/runtime/webcore/blob/copy_file.rs +++ b/src/runtime/webcore/blob/copy_file.rs @@ -214,11 +214,13 @@ impl CopyFile { } } - pub(crate) fn do_open_file(&mut self) -> Result<(), crate::Error> { + /// Opens nothing, and leaves `destination_fd` invalid, when the destination path names `source`'s file. + pub(crate) fn do_open_file( + &mut self, + source: Option<&Stat>, + ) -> Result<(), crate::Error> { let mut path_buf1 = bun_paths::path_buffer_pool::get(); - // open source file first - // if it fails, we don't want the extra destination file hanging out - if matches!(WHICH, IOWhich::Both | IOWhich::Source) { + if matches!(WHICH, IOWhich::Source) { self.source_fd = match bun_sys::open( self.source_file_store .pathlike @@ -246,7 +248,7 @@ impl CopyFile { }; } - if matches!(WHICH, IOWhich::Both | IOWhich::Destination) { + if matches!(WHICH, IOWhich::Destination) { loop { // detach `dest` lifetime from `self` (borrowck) — slice_z // copies into path_buf1, so build the ZStr directly from the buffer. @@ -259,6 +261,12 @@ impl CopyFile { }; // SAFETY: path_buf1[dest_len] == 0 written above. let dest: &bun_core::ZStr = bun_core::ZStr::from_buf(&path_buf1[..], dest_len); + // Before every open: a parent directory from the last pass can make the path name the source. + if source + .is_some_and(|source| Self::is_same_file(source, &bun_sys::stat_no_path(dest))) + { + return Ok(()); + } let mode = self.destination_mode.unwrap_or(node_fs::DEFAULT_PERMISSION); match bun_sys::open(dest, OPEN_DESTINATION_FLAGS, mode) { bun_sys::Result::Ok(result) => { @@ -277,20 +285,11 @@ impl CopyFile { match blob::mkdir_if_not_exists(self, &errno, dest, dest.as_bytes()) { Retry::Continue => continue, Retry::Fail => { - if matches!(WHICH, IOWhich::Both) { - self.source_fd.close(); - self.source_fd = Fd::INVALID; - } return Err(bun_errno::from_errno(errno.errno as i32).into()); } Retry::No => {} } - if matches!(WHICH, IOWhich::Both) { - self.source_fd.close(); - self.source_fd = Fd::INVALID; - } - self.system_error = Some( errno .with_path(self.destination_file_store.pathlike.path().slice()) @@ -595,12 +594,14 @@ impl CopyFile { Ok(()) } - pub(crate) fn run_async(&mut self) { - #[cfg(target_os = "macos")] - let mut stat_: Option = None; - #[cfg(not(target_os = "macos"))] - let stat_: Option = None; + /// Whether `dest` is the file that `source` describes. + fn is_same_file(source: &Stat, dest: &bun_sys::Result) -> bool { + // An inode number of 0 means the file system reports no identity. + matches!(dest, bun_sys::Result::Ok(dest) + if source.st_ino != 0 && dest.st_dev == source.st_dev && dest.st_ino == source.st_ino) + } + pub(crate) fn run_async(&mut self) { if let PathOrFileDescriptor::Fd(fd) = &self.destination_file_store.pathlike { self.destination_fd = *fd; } @@ -609,8 +610,8 @@ impl CopyFile { self.source_fd = *fd; } - // Do we need to open both files? - if self.destination_fd == Fd::INVALID && self.source_fd == Fd::INVALID { + // The source comes first: the destination is compared with it before it is opened. + if self.source_fd == Fd::INVALID { // First, we attempt to clonefile() on macOS // This is the fastest way to copy a file. #[cfg(target_os = "macos")] @@ -630,15 +631,13 @@ impl CopyFile { // stat the output file, make sure it: // 1. Exists - match bun_sys::stat( + let stat_size = match bun_sys::stat( self.source_file_store .pathlike .path() .slice_z(&mut path_buf), ) { bun_sys::Result::Ok(result) => { - stat_ = Some(result); - if bun_sys::S::ISDIR(result.st_mode as u32) { self.system_error = Some(unsupported_directory_error()); return; @@ -647,17 +646,18 @@ impl CopyFile { if !bun_sys::S::ISREG(result.st_mode as u32) { break 'do_clonefile; } + + result.st_size } bun_sys::Result::Err(err) => { // If we can't stat it, we also can't copy it. self.system_error = Some(err.to_system_error()); return; } - } + }; match self.do_clonefile() { Ok(()) => { - let stat_size = stat_.unwrap().st_size; if self.max_length != MAX_SIZE && self.max_length < SizeType::try_from(stat_size).expect("int cast") @@ -710,21 +710,7 @@ impl CopyFile { } } - if self.do_open_file::<{ IOWhich::Both }>().is_err() { - return; - } - // Do we need to open only one file? - } else if self.destination_fd == Fd::INVALID { - self.source_fd = self.source_file_store.pathlike.fd(); - - if self.do_open_file::<{ IOWhich::Destination }>().is_err() { - return; - } - // Do we need to open only one file? - } else if self.source_fd == Fd::INVALID { - self.destination_fd = self.destination_file_store.pathlike.fd(); - - if self.do_open_file::<{ IOWhich::Source }>().is_err() { + if self.do_open_file::<{ IOWhich::Source }>(None).is_err() { return; } } @@ -733,7 +719,6 @@ impl CopyFile { return; } - debug_assert!(self.destination_fd.is_valid()); debug_assert!(self.source_fd.is_valid()); if matches!( @@ -743,16 +728,14 @@ impl CopyFile { // nothing to do for the Fd case } - let stat: Stat = match stat_ { - Some(s) => s, - None => match bun_sys::fstat(self.source_fd) { - bun_sys::Result::Ok(result) => result, - bun_sys::Result::Err(err) => { - self.do_close(); - self.system_error = Some(err.to_system_error()); - return; - } - }, + // From the opened fd: the source path can name another file by now. + let stat: Stat = match bun_sys::fstat(self.source_fd) { + bun_sys::Result::Ok(result) => result, + bun_sys::Result::Err(err) => { + self.system_error = Some(err.to_system_error()); + self.do_close(); + return; + } }; if bun_sys::S::ISDIR(stat.st_mode as _) { @@ -761,6 +744,32 @@ impl CopyFile { return; } + if self.destination_fd == Fd::INVALID { + // Only a regular file has an identity to compare. + let source = bun_sys::S::ISREG(stat.st_mode as _).then_some(&stat); + if self + .do_open_file::<{ IOWhich::Destination }>(source) + .is_err() + { + self.do_close(); + return; + } + + if self.destination_fd == Fd::INVALID { + // A copy of a file onto itself: nothing to empty or write. + self.read_len = SizeType::try_from(stat.st_size).expect("int cast"); + if let Some(mode) = self.destination_mode { + if let bun_sys::Result::Err(err) = bun_sys::fchmod(self.source_fd, mode) { + self.system_error = Some(err.to_system_error()); + } + } + self.do_close(); + return; + } + } + + debug_assert!(self.destination_fd.is_valid()); + // BSD fstat on a pipe reports bytes currently buffered in st_size; // only a regular-file st_size is a length. if stat.st_size != 0 && bun_sys::S::ISREG(stat.st_mode as _) { @@ -781,6 +790,8 @@ impl CopyFile { ) && self.max_length > PREALLOCATE_LENGTH && self.max_length != MAX_SIZE + // A rename after the compare can make the source the destination: do not zero-fill it. + && !Self::is_same_file(&stat, &bun_sys::fstat(self.destination_fd)) { let _ = bun_sys::preallocate_file( self.destination_fd.native(), diff --git a/src/sys/lib.rs b/src/sys/lib.rs index 903d7ed2fadd..6913cbece4f5 100644 --- a/src/sys/lib.rs +++ b/src/sys/lib.rs @@ -2026,19 +2026,22 @@ mod posix_impl { } } pub fn stat(path: &ZStr) -> Maybe { + stat_no_path(path).map_err(|e| e.with_path(path.as_bytes())) + } + /// [`stat`] with an error that has no `path`: a failure does not allocate. + pub fn stat_no_path(path: &ZStr) -> Maybe { #[cfg(any(target_os = "linux", target_os = "android"))] { return super::linux_syscall::stat(path) - .map_err(|e| Error::from_code_int(e, Tag::stat).with_path(path.as_bytes())); + .map_err(|e| Error::from_code_int(e, Tag::stat)); } #[cfg(not(any(target_os = "linux", target_os = "android")))] { let mut st = core::mem::MaybeUninit::::uninit(); - check_p!( + check!( // SAFETY: `path` is NUL-terminated; `st` is a valid out-param. unsafe { libc::stat(path.as_ptr(), st.as_mut_ptr()) }, - Tag::stat, - path + Tag::stat ); // SAFETY: rc == 0 ⇒ kernel populated `st`. Ok(unsafe { st.assume_init() }) diff --git a/test/js/bun/io/bun-write.test.js b/test/js/bun/io/bun-write.test.js index 8b8ca4978298..36b5f892f27e 100644 --- a/test/js/bun/io/bun-write.test.js +++ b/test/js/bun/io/bun-write.test.js @@ -7,6 +7,7 @@ import { exampleSite, gcTick, isASAN, + isLinux, isMacOS, isWindows, tempDir, @@ -302,6 +303,221 @@ const IS_UV_FS_COPYFILE_DISABLED = expect(fs.statSync(existing).size).toBe(100); }); + // https://github.com/oven-sh/bun/issues/20462 + describe("Bun.write(dest, Bun.file(src)) where dest is the same file as src", () => { + const content = Buffer.alloc(100_000, "0123456789").toString(); + + // Outside of tests, the Windows read/write loop only runs for pipes and devices. + it.skipIf(IS_UV_FS_COPYFILE_DISABLED).each([ + ["the same path", ({ file }) => Bun.write(file, Bun.file(file))], + [ + "one BunFile as both arguments", + ({ file }) => { + const bunFile = Bun.file(file); + return Bun.write(bunFile, bunFile); + }, + ], + ["two BunFile objects", ({ file }) => Bun.write(Bun.file(file), Bun.file(file))], + ["BunFile.write()", ({ file }) => Bun.file(file).write(Bun.file(file))], + ["a symlink as the destination", ({ file, symlink }) => Bun.write(symlink, Bun.file(file))], + ["a symlink as the source", ({ file, symlink }) => Bun.write(file, Bun.file(symlink))], + ["a hard link as the destination", ({ file, hardlink }) => Bun.write(hardlink, Bun.file(file))], + ["a relative and an absolute path", ({ file }) => Bun.write(path.relative(process.cwd(), file), Bun.file(file))], + // The first open fails, Bun makes `new`, and only then does the path name the file. + [ + "a path through a directory that does not exist yet", + ({ file, dir }) => Bun.write(`${dir}/new/../file.txt`, Bun.file(file)), + ], + [ + "an open fd as the source", + async ({ file }) => { + const fd = fs.openSync(file, "r"); + try { + return await Bun.write(file, Bun.file(fd)); + } finally { + fs.closeSync(fd); + } + }, + ], + ["a Response around the file as the source", ({ file }) => Bun.write(file, new Response(Bun.file(file)))], + ])("%s leaves the file intact", async (_, write) => { + using dir = tempDir("bun-write-same-file", { "file.txt": content }); + const file = join(String(dir), "file.txt"); + const symlink = join(String(dir), "symlink.txt"); + const hardlink = join(String(dir), "hardlink.txt"); + fs.symlinkSync(file, symlink); + fs.linkSync(file, hardlink); + + const written = await write({ file, symlink, hardlink, dir: String(dir) }); + expect({ written, intact: fs.readFileSync(file, "utf8") === content }).toEqual({ + written: content.length, + intact: true, + }); + }); + + it.skipIf(IS_UV_FS_COPYFILE_DISABLED)("a build output written to its own path stays intact", async () => { + using dir = tempDir("bun-write-same-file-artifact", { "entry.js": "console.log(0.1 + 0.2);" }); + const build = await Bun.build({ entrypoints: [join(String(dir), "entry.js")], outdir: join(String(dir), "out") }); + const [output] = build.outputs; + const built = fs.readFileSync(output.path, "utf8"); + expect(built).toContain("0.1 + 0.2"); + + const written = await Bun.write(output.path, output); + expect({ written, intact: fs.readFileSync(output.path, "utf8") === built }).toEqual({ + written: Buffer.byteLength(built), + intact: true, + }); + }); + + // The copy is a no-op, so it does not open the file for writing. The mode option still applies. + // Not on Windows: a file has no POSIX mode bits there. + it.skipIf(isWindows)("a file without write permission stays intact and gets the mode option", async () => { + using dir = tempDir("bun-write-same-file-mode", { "file.txt": content }); + const file = join(String(dir), "file.txt"); + fs.chmodSync(file, 0o444); + + const written = await Bun.write(file, Bun.file(file), { mode: 0o640 }); + expect({ + written, + mode: fs.statSync(file).mode & 0o777, + intact: fs.readFileSync(file, "utf8") === content, + }).toEqual({ written: content.length, mode: 0o640, intact: true }); + }); + + // Compared with another destination, so the row holds once the copy honours a source slice(). + it.skipIf(IS_UV_FS_COPYFILE_DISABLED)( + "a slice of the file as the source gives the same result as for another destination", + async () => { + using dir = tempDir("bun-write-same-file-slice", { "file.txt": content }); + const file = join(String(dir), "file.txt"); + const other = join(String(dir), "other.txt"); + + const onOther = await Bun.write(other, Bun.file(file).slice(10, 20)); + const expected = fs.readFileSync(other, "utf8"); + const onItself = await Bun.write(file, Bun.file(file).slice(10, 20)); + const actual = fs.readFileSync(file, "utf8"); + expect({ written: onItself, length: actual.length, same: actual === expected }).toEqual({ + written: onOther, + length: expected.length, + same: true, + }); + }, + ); + + // Windows still cuts the file to the size the destination BunFile cached. + it.todoIf(isWindows)("a destination that cached its size before the file grew does not cut the file", async () => { + using dir = tempDir("bun-write-same-file-stale-size", { "file.txt": "0123456789" }); + const file = join(String(dir), "file.txt"); + const destination = Bun.file(file); + expect(destination.size).toBe(10); + fs.appendFileSync(file, "ABCDEFGHIJ"); + + const written = await Bun.write(destination, Bun.file(file)); + expect({ written, content: fs.readFileSync(file, "utf8") }).toEqual({ + written: 20, + content: "0123456789ABCDEFGHIJ", + }); + }); + + // `/dev/full` is a Linux device. + it.skipIf(!isLinux)("one character device as the source and the destination is still copied", async () => { + expect(fs.statSync("/dev/full").isCharacterDevice()).toBe(true); + await expect(Bun.write("/dev/full", Bun.file("/dev/full"))).rejects.toThrow( + expect.objectContaining({ code: "ENOSPC" }), + ); + }); + }); + + // POSIX only: these source checks are in the POSIX copy job. Windows copies in `CopyFileWindows`. + describe.skipIf(isWindows)("Bun.write(dest, Bun.file(src)) with a source that cannot be copied", () => { + const content = Buffer.alloc(100_000, "0123456789").toString(); + + it.each(["path", "fd"])("a directory %s rejects and leaves the destination as it was", async kind => { + using dir = tempDir("bun-write-directory-source", { "dest.txt": content }); + const dest = join(String(dir), "dest.txt"); + const missing = join(String(dir), "missing.txt"); + const fd = kind === "fd" ? fs.openSync(String(dir), "r") : undefined; + try { + for (const destination of [dest, missing]) { + await expect(Bun.write(destination, Bun.file(fd ?? String(dir)))).rejects.toThrow( + "That doesn't work on folders", + ); + } + } finally { + if (fd !== undefined) fs.closeSync(fd); + } + expect({ intact: fs.readFileSync(dest, "utf8") === content, created: fs.existsSync(missing) }).toEqual({ + intact: true, + created: false, + }); + }); + + it("a source fd that is not open rejects and leaves the destination as it was", async () => { + using dir = tempDir("bun-write-bad-source-fd", { "dest.txt": content, "open.txt": content }); + const dest = join(String(dir), "dest.txt"); + const open = join(String(dir), "open.txt"); + const missing = join(String(dir), "missing.txt"); + fs.chmodSync(dest, 0o644); + fs.chmodSync(open, 0o644); + + const fd = fs.openSync(open, "r+"); + try { + for (const destination of [dest, missing, Bun.file(fd)]) { + await expect(Bun.write(destination, Bun.file(987_654), { mode: 0o600 })).rejects.toThrow( + expect.objectContaining({ code: "EBADF" }), + ); + } + } finally { + fs.closeSync(fd); + } + expect({ + modes: [dest, open].map(file => fs.statSync(file).mode & 0o777), + intact: [dest, open].every(file => fs.readFileSync(file, "utf8") === content), + created: fs.existsSync(missing), + }).toEqual({ modes: [0o644, 0o644], intact: true, created: false }); + }); + }); + + describe("Bun.write(dest, Bun.file(src)) onto an existing dest", () => { + it("a longer destination is replaced", async () => { + using dir = tempDir("bun-write-shorter-source", { + "src.txt": "short", + "dest.txt": Buffer.alloc(100_000, "0123456789").toString(), + }); + const dest = join(String(dir), "dest.txt"); + const written = await Bun.write(dest, Bun.file(join(String(dir), "src.txt"))); + expect({ written, content: fs.readFileSync(dest, "utf8") }).toEqual({ written: 5, content: "short" }); + }); + + // `/dev/null` is a POSIX path. + it.skipIf(isWindows)("a destination path that is not a regular file is written", async () => { + expect(fs.statSync("/dev/null").isCharacterDevice()).toBe(true); + using dir = tempDir("bun-write-dev-null", { "src.txt": "short" }); + expect(await Bun.write("/dev/null", Bun.file(join(String(dir), "src.txt")))).toBe(5); + }); + + // Only Linux has `/proc/self/fd`, which names the file behind each open fd. + it.skipIf(!isLinux)("a destination that cannot be opened does not leave the source open", async () => { + using dir = tempDir("bun-write-dest-open-fails", { "src.txt": "short", "file.txt": "not a directory" }); + const src = fs.realpathSync(join(String(dir), "src.txt")); + const openSources = () => + fs.readdirSync("/proc/self/fd").filter(fd => { + try { + return fs.readlinkSync(`/proc/self/fd/${fd}`) === src; + } catch { + return false; + } + }).length; + + for (let i = 0; i < 20; i++) { + await expect(Bun.write(join(String(dir), "file.txt", "below-a-file"), Bun.file(src))).rejects.toThrow( + expect.objectContaining({ code: "ENOTDIR" }), + ); + } + expect(openSources()).toBe(0); + }); + }); + it("Bun.file", async () => { const file = path.join(import.meta.dir, "fetch.js.txt"); await gcTick();