From 1ccd1571f4f2bcf692288622b2e27dc161629424 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 29 Sep 2026 12:30:17 +0000 Subject: [PATCH 01/11] Bun.write: leave a file intact when it is copied onto itself CopyFile opened the destination with O_TRUNC before it read the source. When both name one inode, the open emptied the file and the copy read 0 bytes, so Bun.write(path, Bun.file(path)) resolved 0 and destroyed the data. Open the destination without O_TRUNC. For a regular destination, compare st_dev and st_ino with the source. A match is a no-op that resolves with the file size, as uv_fs_copyfile already does on Windows. Otherwise truncate a destination that has content before the copy. On macOS, drop the source stat taken from the path when clonefile fails, so the comparison uses fstat of the opened source fd. --- src/runtime/webcore/blob/copy_file.rs | 37 +++++++++++-- test/js/bun/io/bun-write.test.js | 76 +++++++++++++++++++++++++++ 2 files changed, 110 insertions(+), 3 deletions(-) diff --git a/src/runtime/webcore/blob/copy_file.rs b/src/runtime/webcore/blob/copy_file.rs index e41579856cdd..4e40aed5c5ae 100644 --- a/src/runtime/webcore/blob/copy_file.rs +++ b/src/runtime/webcore/blob/copy_file.rs @@ -722,6 +722,8 @@ impl CopyFile { // or if the output is not a directory // or if it's a network volume self.system_error = None; + // The path can name another file by the time it is opened. + stat_ = None; } } } @@ -779,6 +781,36 @@ impl CopyFile { return; } + // No O_TRUNC at open: it would empty a destination that is also the source. + if matches!( + self.destination_file_store.pathlike, + PathOrFileDescriptor::Path(_) + ) { + let dest_stat = match bun_sys::fstat(self.destination_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::ISREG(dest_stat.st_mode as _) { + if dest_stat.st_dev == stat.st_dev && dest_stat.st_ino == stat.st_ino { + // `max_length` may be a stale cached size: never cut the file here. + self.read_len = SizeType::try_from(dest_stat.st_size).expect("int cast"); + self.do_close(); + return; + } + if dest_stat.st_size != 0 + && let bun_sys::Result::Err(err) = bun_sys::ftruncate(self.destination_fd, 0) + { + self.system_error = Some(err.to_system_error()); + self.do_close(); + return; + } + } + } + // 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 _) { @@ -861,7 +893,7 @@ impl CopyFile { #[cfg(target_os = "macos")] { // fcopyfile rewrites dest from offset 0 and the slice trim is - // ftruncate; both are only safe for a dest Bun opened O_TRUNC. + // ftruncate; both are only safe for a dest Bun opened and emptied. if matches!( self.destination_file_store.pathlike, PathOrFileDescriptor::Path(_) @@ -1022,8 +1054,7 @@ const PREALLOCATE_SUPPORTED: bool = cfg!(any(target_os = "linux", target_os = "a const PREALLOCATE_LENGTH: SizeType = 2048 * 1024; #[cfg(not(windows))] -const OPEN_DESTINATION_FLAGS: i32 = - bun_sys::O::CLOEXEC | bun_sys::O::CREAT | bun_sys::O::WRONLY | bun_sys::O::TRUNC; +const OPEN_DESTINATION_FLAGS: i32 = bun_sys::O::CLOEXEC | bun_sys::O::CREAT | bun_sys::O::WRONLY; #[cfg(not(windows))] const OPEN_SOURCE_FLAGS: i32 = bun_sys::O::CLOEXEC | bun_sys::O::RDONLY; diff --git a/test/js/bun/io/bun-write.test.js b/test/js/bun/io/bun-write.test.js index 87156a840aed..9b5e6da05d1f 100644 --- a/test/js/bun/io/bun-write.test.js +++ b/test/js/bun/io/bun-write.test.js @@ -300,6 +300,82 @@ 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))], + [ + "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 slice of the file as the source", ({ file }) => Bun.write(file, Bun.file(file).slice(10, 20))], + ["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 }); + expect({ written, intact: fs.readFileSync(file, "utf8") === content }).toEqual({ + written: content.length, + intact: 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", + }); + }); + + it("a longer existing destination is still replaced", async () => { + using dir = tempDir("bun-write-shorter-source", { "src.txt": "short", "dest.txt": content }); + 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" }); + }); + + it.skipIf(isWindows)("a destination path that is not a regular file is still written", async () => { + 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); + }); + }); + it("Bun.file", async () => { const file = path.join(import.meta.dir, "fetch.js.txt"); await gcTick(); From cec27422982cdee87d9198ee051f1ef08ac37f7d Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 29 Sep 2026 14:59:45 +0000 Subject: [PATCH 02/11] Bun.write: always compare the destination with the opened source fd On macOS the source stat came from the path, taken before the source was opened, and the copy reused it when clonefile did not run or failed. If the path names another file by the time it is opened, the same-file check compares the wrong inode. Take the stat from the opened source fd on every path. The path stat now serves only the clonefile attempt. --- src/runtime/webcore/blob/copy_file.rs | 33 +++++++++------------------ 1 file changed, 11 insertions(+), 22 deletions(-) diff --git a/src/runtime/webcore/blob/copy_file.rs b/src/runtime/webcore/blob/copy_file.rs index 4e40aed5c5ae..302767df329e 100644 --- a/src/runtime/webcore/blob/copy_file.rs +++ b/src/runtime/webcore/blob/copy_file.rs @@ -614,11 +614,6 @@ impl CopyFile { } 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; - if let PathOrFileDescriptor::Fd(fd) = &self.destination_file_store.pathlike { self.destination_fd = *fd; } @@ -648,15 +643,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; @@ -665,17 +658,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") @@ -722,8 +716,6 @@ impl CopyFile { // or if the output is not a directory // or if it's a network volume self.system_error = None; - // The path can name another file by the time it is opened. - stat_ = None; } } } @@ -763,16 +755,13 @@ 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; - } - }, + let stat: Stat = 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; + } }; if bun_sys::S::ISDIR(stat.st_mode as _) { From 0054fe21b361563cd9fc3638616e0965be467d46 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 30 Sep 2026 10:20:51 +0000 Subject: [PATCH 03/11] Bun.write: keep the errors and the times of a copy as they were A source fd that the caller already closed made the copy resolve with nothing copied: the destination open reused the fd number, so both fstat calls saw one file. Reject with EBADF, as before this branch. A destination that cannot be emptied now rejects with the destination path, not the source path. An inode number of 0 is not an identity. An empty source still updates the times of an empty destination. Tests: a slice of the same file is compared with the same slice written to another file. New rows cover a directory source, a closed source fd, one character device on both sides, and a sealed destination. --- src/runtime/webcore/blob/copy_file.rs | 55 ++++++++---- test/js/bun/io/bun-write.test.js | 125 +++++++++++++++++++++++++- 2 files changed, 161 insertions(+), 19 deletions(-) diff --git a/src/runtime/webcore/blob/copy_file.rs b/src/runtime/webcore/blob/copy_file.rs index 302767df329e..b50fe54527e6 100644 --- a/src/runtime/webcore/blob/copy_file.rs +++ b/src/runtime/webcore/blob/copy_file.rs @@ -167,6 +167,27 @@ impl CopyFile { ) } + /// Empties a regular destination. Returns `true`, and empties nothing, when it is `source`'s file. + fn empty_destination(&mut self, source: &Stat) -> bun_sys::Result { + let dest = bun_sys::fstat(self.destination_fd)?; + if !bun_sys::S::ISREG(dest.st_mode as _) { + return Ok(false); + } + // An inode number of 0 means the file system reports no identity. + if dest.st_ino != 0 && dest.st_dev == source.st_dev && dest.st_ino == source.st_ino { + // `max_length` may be a stale cached size: never cut the file here. + self.read_len = SizeType::try_from(dest.st_size).expect("int cast"); + return Ok(true); + } + if dest.st_size != 0 { + bun_sys::ftruncate(self.destination_fd, 0)?; + } else if source.st_size == 0 { + // An empty source writes nothing, so this is what updates the times. + let _ = bun_sys::ftruncate(self.destination_fd, 0); + } + Ok(false) + } + pub(crate) fn do_close(&mut self) { let close_input = !matches!( self.destination_file_store.pathlike, @@ -732,6 +753,15 @@ impl CopyFile { if self.do_open_file::<{ IOWhich::Destination }>().is_err() { return; } + // The caller closed its source fd, and the open above reused the number. + if self.destination_fd == self.source_fd { + self.system_error = Some( + bun_sys::Error::from_code(bun_sys::E::EBADF, bun_sys::Tag::fstat) + .to_system_error(), + ); + self.do_close(); + 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(); @@ -755,6 +785,7 @@ impl CopyFile { // nothing to do for the Fd case } + // 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) => { @@ -775,25 +806,17 @@ impl CopyFile { self.destination_file_store.pathlike, PathOrFileDescriptor::Path(_) ) { - let dest_stat = match bun_sys::fstat(self.destination_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::ISREG(dest_stat.st_mode as _) { - if dest_stat.st_dev == stat.st_dev && dest_stat.st_ino == stat.st_ino { - // `max_length` may be a stale cached size: never cut the file here. - self.read_len = SizeType::try_from(dest_stat.st_size).expect("int cast"); + match self.empty_destination(&stat) { + bun_sys::Result::Ok(false) => {} + bun_sys::Result::Ok(true) => { self.do_close(); return; } - if dest_stat.st_size != 0 - && let bun_sys::Result::Err(err) = bun_sys::ftruncate(self.destination_fd, 0) - { - self.system_error = Some(err.to_system_error()); + bun_sys::Result::Err(err) => { + self.system_error = Some( + err.with_path(self.destination_file_store.pathlike.path().slice()) + .to_system_error(), + ); self.do_close(); return; } diff --git a/test/js/bun/io/bun-write.test.js b/test/js/bun/io/bun-write.test.js index 9b5e6da05d1f..bb02f55418c1 100644 --- a/test/js/bun/io/bun-write.test.js +++ b/test/js/bun/io/bun-write.test.js @@ -1,3 +1,4 @@ +import { dlopen } from "bun:ffi"; import { describe, expect, it, test } from "bun:test"; import fs, { mkdirSync } from "fs"; import { @@ -7,7 +8,9 @@ import { exampleSite, gcTick, isASAN, + isLinux, isWindows, + libcPathForDlopen, tempDir, withoutAggressiveGC, } from "harness"; @@ -331,7 +334,6 @@ const IS_UV_FS_COPYFILE_DISABLED = } }, ], - ["a slice of the file as the source", ({ file }) => Bun.write(file, Bun.file(file).slice(10, 20))], ["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 }); @@ -348,6 +350,26 @@ const IS_UV_FS_COPYFILE_DISABLED = }); }); + // 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" }); @@ -363,17 +385,114 @@ const IS_UV_FS_COPYFILE_DISABLED = }); }); - it("a longer existing destination is still replaced", async () => { + 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" }), + ); + }); + }); + + describe("Bun.write(dest, Bun.file(src)) onto an existing dest", () => { + const content = Buffer.alloc(100_000, "0123456789").toString(); + + it("a longer destination is replaced", async () => { using dir = tempDir("bun-write-shorter-source", { "src.txt": "short", "dest.txt": content }); 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" }); }); - it.skipIf(isWindows)("a destination path that is not a regular file is still written", async () => { + 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); }); + + it.skipIf(!isLinux)("an empty source updates the times of an empty destination", async () => { + using dir = tempDir("bun-write-empty-onto-empty", { "src.txt": "", "dest.txt": "" }); + const dest = join(String(dir), "dest.txt"); + const old = new Date("2001-01-01T00:00:00Z"); + fs.utimesSync(dest, old, old); + + const written = await Bun.write(dest, Bun.file(join(String(dir), "src.txt"))); + expect({ written, updated: fs.statSync(dest).mtimeMs > old.getTime() }).toEqual({ written: 0, updated: true }); + }); + + it.skipIf(isWindows).each(["path", "fd"])( + "a directory %s as the source rejects and leaves the destination intact", + async kind => { + using dir = tempDir("bun-write-directory-source", { "dest.txt": content }); + const dest = join(String(dir), "dest.txt"); + const fd = kind === "fd" ? fs.openSync(String(dir), "r") : undefined; + try { + await expect(Bun.write(dest, Bun.file(fd ?? String(dir)))).rejects.toThrow("That doesn't work on folders"); + } finally { + if (fd !== undefined) fs.closeSync(fd); + } + expect(fs.readFileSync(dest, "utf8") === content).toBe(true); + }, + ); + + // In a child process: the closed fd number is free, and another test in this process could take it. + it.skipIf(!isLinux)("a source fd that is already closed rejects and leaves the destination intact", async () => { + using dir = tempDir("bun-write-closed-source-fd", { "src.txt": "source", "dest.txt": content }); + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + const fs = require("fs"); + const fd = fs.openSync("src.txt", "r"); + fs.closeSync(fd); + Bun.write("dest.txt", Bun.file(fd)).then( + written => console.log(JSON.stringify({ written })), + error => console.log(JSON.stringify({ code: error.code, size: fs.statSync("dest.txt").size })), + ); + `, + ], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect({ result: exitCode === 0 ? JSON.parse(stdout) : { stdout, stderr }, exitCode }).toEqual({ + result: { code: "EBADF", size: content.length }, + exitCode: 0, + }); + }); + + // A memfd sealed with F_SEAL_SHRINK opens for writing, and every ftruncate on it fails with EPERM. + it.skipIf(!isLinux)("a destination that cannot be emptied rejects, names it, and keeps its bytes", async () => { + const MFD_ALLOW_SEALING = 2; + const F_ADD_SEALS = 1033; + const F_SEAL_SHRINK = 2; + const libc = dlopen(libcPathForDlopen(), { + memfd_create: { args: ["ptr", "u32"], returns: "i32" }, + fcntl: { args: ["i32", "i32", "i32"], returns: "i32" }, + }); + using dir = tempDir("bun-write-sealed-destination", { "src.txt": "short" }); + const fd = libc.symbols.memfd_create(Buffer.from("sealed\0"), MFD_ALLOW_SEALING); + try { + expect(fd).toBeGreaterThan(2); + fs.writeSync(fd, content); + expect(libc.symbols.fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK)).toBe(0); + const dest = `/proc/self/fd/${fd}`; + + const outcome = await Bun.write(dest, Bun.file(join(String(dir), "src.txt"))).then( + written => ({ written }), + error => ({ code: error.code, syscall: error.syscall, path: error.path }), + ); + expect({ outcome, intact: fs.readFileSync(dest, "utf8") === content }).toEqual({ + outcome: { code: "EPERM", syscall: "ftruncate", path: dest }, + intact: true, + }); + } finally { + if (fd > 2) fs.closeSync(fd); + libc.close(); + } + }); }); it("Bun.file", async () => { From 21b3b60f0544d18a8a878a17fe852f16275fc845 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 30 Sep 2026 14:02:15 +0000 Subject: [PATCH 04/11] Bun.write: always truncate a destination that is not the source The copy skipped ftruncate when fstat reported a size of 0. On a mount with an attribute cache (FUSE, virtiofs) that size can be stale, and the old tail of the file stayed. O_TRUNC never had that gap. Truncate every regular destination that is not the source, as libuv does, and ignore only EACCES on a file that reports a size of 0. A failed fstat of the source no longer applies the mode option to the destination: the error is recorded before the close. --- src/runtime/webcore/blob/copy_file.rs | 13 ++++++------- test/js/bun/io/bun-write.test.js | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/runtime/webcore/blob/copy_file.rs b/src/runtime/webcore/blob/copy_file.rs index b50fe54527e6..0a7c7d1e89d3 100644 --- a/src/runtime/webcore/blob/copy_file.rs +++ b/src/runtime/webcore/blob/copy_file.rs @@ -179,13 +179,12 @@ impl CopyFile { self.read_len = SizeType::try_from(dest.st_size).expect("int cast"); return Ok(true); } - if dest.st_size != 0 { - bun_sys::ftruncate(self.destination_fd, 0)?; - } else if source.st_size == 0 { - // An empty source writes nothing, so this is what updates the times. - let _ = bun_sys::ftruncate(self.destination_fd, 0); + // Also for a size of 0: a network mount can report a stale size. + match bun_sys::ftruncate(self.destination_fd, 0) { + // ceph-fuse refuses this on a file that was just created read-only. libuv ignores it too. + Err(err) if dest.st_size != 0 || err.get_errno() != bun_sys::E::EACCES => Err(err), + _ => Ok(false), } - Ok(false) } pub(crate) fn do_close(&mut self) { @@ -789,8 +788,8 @@ impl CopyFile { let stat: Stat = 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()); + self.do_close(); return; } }; diff --git a/test/js/bun/io/bun-write.test.js b/test/js/bun/io/bun-write.test.js index bb02f55418c1..509b83531af7 100644 --- a/test/js/bun/io/bun-write.test.js +++ b/test/js/bun/io/bun-write.test.js @@ -434,6 +434,20 @@ const IS_UV_FS_COPYFILE_DISABLED = }, ); + it.skipIf(isWindows)("a source fd that is not open rejects before the destination changes", async () => { + using dir = tempDir("bun-write-bad-source-fd", { "dest.txt": content }); + const dest = join(String(dir), "dest.txt"); + fs.chmodSync(dest, 0o644); + + await expect(Bun.write(dest, Bun.file(987_654), { mode: 0o600 })).rejects.toThrow( + expect.objectContaining({ code: "EBADF" }), + ); + expect({ mode: fs.statSync(dest).mode & 0o777, intact: fs.readFileSync(dest, "utf8") === content }).toEqual({ + mode: 0o644, + intact: true, + }); + }); + // In a child process: the closed fd number is free, and another test in this process could take it. it.skipIf(!isLinux)("a source fd that is already closed rejects and leaves the destination intact", async () => { using dir = tempDir("bun-write-closed-source-fd", { "src.txt": "source", "dest.txt": content }); From df5598ded9e31644947fa2aaf40915e462832cd5 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 30 Sep 2026 15:14:27 +0000 Subject: [PATCH 05/11] Bun.write: check a caller's source fd before the destination open The guard for a closed source fd compared fd numbers after the destination open. Its test failed once on Alpine aarch64: another allocation can take the free number first, and then nothing matched. Call fstat on a caller's source fd before the destination opens. A closed fd now rejects with EBADF before the destination is opened or created, and no later open can take its number first. The guard and its child-process test are gone. The row with an fd that was never open covers this exit in every run. --- src/runtime/webcore/blob/copy_file.rs | 37 +++++++++++++++------------ test/js/bun/io/bun-write.test.js | 29 --------------------- 2 files changed, 21 insertions(+), 45 deletions(-) diff --git a/src/runtime/webcore/blob/copy_file.rs b/src/runtime/webcore/blob/copy_file.rs index 0a7c7d1e89d3..461236ba826b 100644 --- a/src/runtime/webcore/blob/copy_file.rs +++ b/src/runtime/webcore/blob/copy_file.rs @@ -642,6 +642,8 @@ impl CopyFile { self.source_fd = *fd; } + let mut source_stat: Option = None; + // Do we need to open both files? if self.destination_fd == Fd::INVALID && self.source_fd == Fd::INVALID { // First, we attempt to clonefile() on macOS @@ -749,16 +751,16 @@ impl CopyFile { } 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; + // Before the open below: it could take the number of an fd that the caller closed. + match bun_sys::fstat(self.source_fd) { + bun_sys::Result::Ok(result) => source_stat = Some(result), + bun_sys::Result::Err(err) => { + self.system_error = Some(err.to_system_error()); + return; + } } - // The caller closed its source fd, and the open above reused the number. - if self.destination_fd == self.source_fd { - self.system_error = Some( - bun_sys::Error::from_code(bun_sys::E::EBADF, bun_sys::Tag::fstat) - .to_system_error(), - ); - self.do_close(); + + if self.do_open_file::<{ IOWhich::Destination }>().is_err() { return; } // Do we need to open only one file? @@ -785,13 +787,16 @@ impl CopyFile { } // 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; - } + let stat: Stat = match source_stat { + Some(stat) => stat, + None => 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 _) { diff --git a/test/js/bun/io/bun-write.test.js b/test/js/bun/io/bun-write.test.js index 509b83531af7..809d2d63ab41 100644 --- a/test/js/bun/io/bun-write.test.js +++ b/test/js/bun/io/bun-write.test.js @@ -448,35 +448,6 @@ const IS_UV_FS_COPYFILE_DISABLED = }); }); - // In a child process: the closed fd number is free, and another test in this process could take it. - it.skipIf(!isLinux)("a source fd that is already closed rejects and leaves the destination intact", async () => { - using dir = tempDir("bun-write-closed-source-fd", { "src.txt": "source", "dest.txt": content }); - await using proc = Bun.spawn({ - cmd: [ - bunExe(), - "-e", - ` - const fs = require("fs"); - const fd = fs.openSync("src.txt", "r"); - fs.closeSync(fd); - Bun.write("dest.txt", Bun.file(fd)).then( - written => console.log(JSON.stringify({ written })), - error => console.log(JSON.stringify({ code: error.code, size: fs.statSync("dest.txt").size })), - ); - `, - ], - env: bunEnv, - cwd: String(dir), - stdout: "pipe", - stderr: "pipe", - }); - const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - expect({ result: exitCode === 0 ? JSON.parse(stdout) : { stdout, stderr }, exitCode }).toEqual({ - result: { code: "EBADF", size: content.length }, - exitCode: 0, - }); - }); - // A memfd sealed with F_SEAL_SHRINK opens for writing, and every ftruncate on it fails with EPERM. it.skipIf(!isLinux)("a destination that cannot be emptied rejects, names it, and keeps its bytes", async () => { const MFD_ALLOW_SEALING = 2; From 9fbdd107d4963d77ea067724fc3da0b08c5e1c44 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 30 Sep 2026 15:56:28 +0000 Subject: [PATCH 06/11] Bun.write: take both stats after the destination open again The last commit called fstat on a caller's source fd before the destination open and used that stat for the same-file check. On overlayfs, the open copies an image-layer file to the writable layer, and a file with several hard links gets a new inode number then. The two stats no longer matched for one file, and the copy emptied it. Take the source stat after the destination open, as before, so both stats describe the same moment. A closed source fd whose number the destination open takes rejects with EBADF through the fd-number check. --- src/runtime/webcore/blob/copy_file.rs | 37 ++++++++++++--------------- 1 file changed, 16 insertions(+), 21 deletions(-) diff --git a/src/runtime/webcore/blob/copy_file.rs b/src/runtime/webcore/blob/copy_file.rs index 461236ba826b..0a7c7d1e89d3 100644 --- a/src/runtime/webcore/blob/copy_file.rs +++ b/src/runtime/webcore/blob/copy_file.rs @@ -642,8 +642,6 @@ impl CopyFile { self.source_fd = *fd; } - let mut source_stat: Option = None; - // Do we need to open both files? if self.destination_fd == Fd::INVALID && self.source_fd == Fd::INVALID { // First, we attempt to clonefile() on macOS @@ -751,18 +749,18 @@ impl CopyFile { } else if self.destination_fd == Fd::INVALID { self.source_fd = self.source_file_store.pathlike.fd(); - // Before the open below: it could take the number of an fd that the caller closed. - match bun_sys::fstat(self.source_fd) { - bun_sys::Result::Ok(result) => source_stat = Some(result), - bun_sys::Result::Err(err) => { - self.system_error = Some(err.to_system_error()); - return; - } - } - if self.do_open_file::<{ IOWhich::Destination }>().is_err() { return; } + // The caller closed its source fd, and the open above reused the number. + if self.destination_fd == self.source_fd { + self.system_error = Some( + bun_sys::Error::from_code(bun_sys::E::EBADF, bun_sys::Tag::fstat) + .to_system_error(), + ); + self.do_close(); + 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(); @@ -787,16 +785,13 @@ impl CopyFile { } // From the opened fd: the source path can name another file by now. - let stat: Stat = match source_stat { - Some(stat) => stat, - None => 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; - } - }, + 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 _) { From 85d6c65e22dc7948ffef07872fb29b038d1a7668 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 2 Oct 2026 07:30:17 +0000 Subject: [PATCH 07/11] Bun.write: compare the destination with the source before the open The copy job opens the source first and reads its identity. Then it reads the identity of the destination path. When both name one regular file, the copy is a no-op. In every other case the destination opens with O_TRUNC, as before. A directory source and a source fd that is not open now reject before the destination is opened or created. --- src/runtime/webcore/blob/copy_file.rs | 143 ++++++++++++-------------- src/sys/lib.rs | 11 +- test/js/bun/io/bun-write.test.js | 132 ++++++++++++------------ 3 files changed, 139 insertions(+), 147 deletions(-) diff --git a/src/runtime/webcore/blob/copy_file.rs b/src/runtime/webcore/blob/copy_file.rs index 0a7c7d1e89d3..6bcb2bcba8c3 100644 --- a/src/runtime/webcore/blob/copy_file.rs +++ b/src/runtime/webcore/blob/copy_file.rs @@ -167,26 +167,6 @@ impl CopyFile { ) } - /// Empties a regular destination. Returns `true`, and empties nothing, when it is `source`'s file. - fn empty_destination(&mut self, source: &Stat) -> bun_sys::Result { - let dest = bun_sys::fstat(self.destination_fd)?; - if !bun_sys::S::ISREG(dest.st_mode as _) { - return Ok(false); - } - // An inode number of 0 means the file system reports no identity. - if dest.st_ino != 0 && dest.st_dev == source.st_dev && dest.st_ino == source.st_ino { - // `max_length` may be a stale cached size: never cut the file here. - self.read_len = SizeType::try_from(dest.st_size).expect("int cast"); - return Ok(true); - } - // Also for a size of 0: a network mount can report a stale size. - match bun_sys::ftruncate(self.destination_fd, 0) { - // ceph-fuse refuses this on a file that was just created read-only. libuv ignores it too. - Err(err) if dest.st_size != 0 || err.get_errno() != bun_sys::E::EACCES => Err(err), - _ => Ok(false), - } - } - pub(crate) fn do_close(&mut self) { let close_input = !matches!( self.destination_file_store.pathlike, @@ -633,7 +613,33 @@ impl CopyFile { Ok(()) } + /// 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) + } + + /// Whether the destination path names the regular file that `source` describes. + fn destination_is_source(&self, source: &Stat) -> bool { + if !bun_sys::S::ISREG(source.st_mode as _) { + return false; + } + let mut path_buf = bun_paths::path_buffer_pool::get(); + let path = self + .destination_file_store + .pathlike + .path() + .slice_z(&mut path_buf); + Self::is_same_file(source, &bun_sys::stat_no_path(path)) + } + 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; + if let PathOrFileDescriptor::Fd(fd) = &self.destination_file_store.pathlike { self.destination_fd = *fd; } @@ -642,8 +648,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")] @@ -663,13 +669,15 @@ impl CopyFile { // stat the output file, make sure it: // 1. Exists - let stat_size = match bun_sys::stat( + 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; @@ -678,18 +686,17 @@ 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") @@ -742,29 +749,6 @@ 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; - } - // The caller closed its source fd, and the open above reused the number. - if self.destination_fd == self.source_fd { - self.system_error = Some( - bun_sys::Error::from_code(bun_sys::E::EBADF, bun_sys::Tag::fstat) - .to_system_error(), - ); - self.do_close(); - 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() { return; } @@ -774,7 +758,6 @@ impl CopyFile { return; } - debug_assert!(self.destination_fd.is_valid()); debug_assert!(self.source_fd.is_valid()); if matches!( @@ -784,14 +767,16 @@ impl CopyFile { // nothing to do for the Fd case } - // 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; - } + 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; + } + }, }; if bun_sys::S::ISDIR(stat.st_mode as _) { @@ -800,28 +785,27 @@ impl CopyFile { return; } - // No O_TRUNC at open: it would empty a destination that is also the source. - if matches!( - self.destination_file_store.pathlike, - PathOrFileDescriptor::Path(_) - ) { - match self.empty_destination(&stat) { - bun_sys::Result::Ok(false) => {} - bun_sys::Result::Ok(true) => { - self.do_close(); - return; - } - bun_sys::Result::Err(err) => { - self.system_error = Some( - err.with_path(self.destination_file_store.pathlike.path().slice()) - .to_system_error(), - ); - self.do_close(); - return; + if self.destination_fd == Fd::INVALID { + if self.destination_is_source(&stat) { + // A copy of a file onto itself: nothing to open, 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; + } + + if self.do_open_file::<{ IOWhich::Destination }>().is_err() { + 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 _) { @@ -842,6 +826,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(), @@ -904,7 +890,7 @@ impl CopyFile { #[cfg(target_os = "macos")] { // fcopyfile rewrites dest from offset 0 and the slice trim is - // ftruncate; both are only safe for a dest Bun opened and emptied. + // ftruncate; both are only safe for a dest Bun opened O_TRUNC. if matches!( self.destination_file_store.pathlike, PathOrFileDescriptor::Path(_) @@ -1065,7 +1051,8 @@ const PREALLOCATE_SUPPORTED: bool = cfg!(any(target_os = "linux", target_os = "a const PREALLOCATE_LENGTH: SizeType = 2048 * 1024; #[cfg(not(windows))] -const OPEN_DESTINATION_FLAGS: i32 = bun_sys::O::CLOEXEC | bun_sys::O::CREAT | bun_sys::O::WRONLY; +const OPEN_DESTINATION_FLAGS: i32 = + bun_sys::O::CLOEXEC | bun_sys::O::CREAT | bun_sys::O::WRONLY | bun_sys::O::TRUNC; #[cfg(not(windows))] const OPEN_SOURCE_FLAGS: i32 = bun_sys::O::CLOEXEC | bun_sys::O::RDONLY; diff --git a/src/sys/lib.rs b/src/sys/lib.rs index e1e5255b4296..6c400c0084de 100644 --- a/src/sys/lib.rs +++ b/src/sys/lib.rs @@ -2046,19 +2046,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 809d2d63ab41..961dd6113ba3 100644 --- a/test/js/bun/io/bun-write.test.js +++ b/test/js/bun/io/bun-write.test.js @@ -1,4 +1,3 @@ -import { dlopen } from "bun:ffi"; import { describe, expect, it, test } from "bun:test"; import fs, { mkdirSync } from "fs"; import { @@ -10,7 +9,6 @@ import { isASAN, isLinux, isWindows, - libcPathForDlopen, tempDir, withoutAggressiveGC, } from "harness"; @@ -350,6 +348,34 @@ const IS_UV_FS_COPYFILE_DISABLED = }); }); + 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. + 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", @@ -393,90 +419,66 @@ const IS_UV_FS_COPYFILE_DISABLED = }); }); - describe("Bun.write(dest, Bun.file(src)) onto an existing dest", () => { + describe("Bun.write(dest, Bun.file(src)) with a source that cannot be copied", () => { const content = Buffer.alloc(100_000, "0123456789").toString(); - it("a longer destination is replaced", async () => { - using dir = tempDir("bun-write-shorter-source", { "src.txt": "short", "dest.txt": content }); - 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" }); - }); - - 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); - }); - - it.skipIf(!isLinux)("an empty source updates the times of an empty destination", async () => { - using dir = tempDir("bun-write-empty-onto-empty", { "src.txt": "", "dest.txt": "" }); - const dest = join(String(dir), "dest.txt"); - const old = new Date("2001-01-01T00:00:00Z"); - fs.utimesSync(dest, old, old); - - const written = await Bun.write(dest, Bun.file(join(String(dir), "src.txt"))); - expect({ written, updated: fs.statSync(dest).mtimeMs > old.getTime() }).toEqual({ written: 0, updated: true }); - }); - it.skipIf(isWindows).each(["path", "fd"])( - "a directory %s as the source rejects and leaves the destination intact", + "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 { - await expect(Bun.write(dest, Bun.file(fd ?? String(dir)))).rejects.toThrow("That doesn't work on folders"); + 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(fs.readFileSync(dest, "utf8") === content).toBe(true); + expect({ intact: fs.readFileSync(dest, "utf8") === content, created: fs.existsSync(missing) }).toEqual({ + intact: true, + created: false, + }); }, ); - it.skipIf(isWindows)("a source fd that is not open rejects before the destination changes", async () => { + it.skipIf(isWindows)("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 }); const dest = join(String(dir), "dest.txt"); + const missing = join(String(dir), "missing.txt"); fs.chmodSync(dest, 0o644); - await expect(Bun.write(dest, Bun.file(987_654), { mode: 0o600 })).rejects.toThrow( - expect.objectContaining({ code: "EBADF" }), - ); - expect({ mode: fs.statSync(dest).mode & 0o777, intact: fs.readFileSync(dest, "utf8") === content }).toEqual({ - mode: 0o644, - intact: true, - }); + for (const destination of [dest, missing]) { + await expect(Bun.write(destination, Bun.file(987_654), { mode: 0o600 })).rejects.toThrow( + expect.objectContaining({ code: "EBADF" }), + ); + } + expect({ + mode: fs.statSync(dest).mode & 0o777, + intact: fs.readFileSync(dest, "utf8") === content, + created: fs.existsSync(missing), + }).toEqual({ mode: 0o644, intact: true, created: false }); }); + }); - // A memfd sealed with F_SEAL_SHRINK opens for writing, and every ftruncate on it fails with EPERM. - it.skipIf(!isLinux)("a destination that cannot be emptied rejects, names it, and keeps its bytes", async () => { - const MFD_ALLOW_SEALING = 2; - const F_ADD_SEALS = 1033; - const F_SEAL_SHRINK = 2; - const libc = dlopen(libcPathForDlopen(), { - memfd_create: { args: ["ptr", "u32"], returns: "i32" }, - fcntl: { args: ["i32", "i32", "i32"], returns: "i32" }, + 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(), }); - using dir = tempDir("bun-write-sealed-destination", { "src.txt": "short" }); - const fd = libc.symbols.memfd_create(Buffer.from("sealed\0"), MFD_ALLOW_SEALING); - try { - expect(fd).toBeGreaterThan(2); - fs.writeSync(fd, content); - expect(libc.symbols.fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK)).toBe(0); - const dest = `/proc/self/fd/${fd}`; - - const outcome = await Bun.write(dest, Bun.file(join(String(dir), "src.txt"))).then( - written => ({ written }), - error => ({ code: error.code, syscall: error.syscall, path: error.path }), - ); - expect({ outcome, intact: fs.readFileSync(dest, "utf8") === content }).toEqual({ - outcome: { code: "EPERM", syscall: "ftruncate", path: dest }, - intact: true, - }); - } finally { - if (fd > 2) fs.closeSync(fd); - libc.close(); - } + 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" }); + }); + + 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); }); }); From c80c365e9ad87941dbd5371aede356f0039191f3 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 2 Oct 2026 10:53:34 +0000 Subject: [PATCH 08/11] Bun.write: read the source identity from the opened fd The compare with the destination now always uses fstat of the opened source. On macOS the job reused a stat of the source path that it took before the open. A failed source fstat records the error before the close, so the mode option is not applied to a destination fd of the caller. --- src/runtime/webcore/blob/copy_file.rs | 32 ++++++++------------ test/js/bun/io/bun-write.test.js | 43 ++++++++++++++++++++++----- 2 files changed, 47 insertions(+), 28 deletions(-) diff --git a/src/runtime/webcore/blob/copy_file.rs b/src/runtime/webcore/blob/copy_file.rs index 6bcb2bcba8c3..227cec724863 100644 --- a/src/runtime/webcore/blob/copy_file.rs +++ b/src/runtime/webcore/blob/copy_file.rs @@ -635,11 +635,6 @@ impl CopyFile { } 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; - if let PathOrFileDescriptor::Fd(fd) = &self.destination_file_store.pathlike { self.destination_fd = *fd; } @@ -669,15 +664,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; @@ -686,17 +679,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") @@ -767,16 +761,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 _) { diff --git a/test/js/bun/io/bun-write.test.js b/test/js/bun/io/bun-write.test.js index 961dd6113ba3..a8bcd3ad64ce 100644 --- a/test/js/bun/io/bun-write.test.js +++ b/test/js/bun/io/bun-write.test.js @@ -446,21 +446,28 @@ const IS_UV_FS_COPYFILE_DISABLED = ); it.skipIf(isWindows)("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 }); + 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); - for (const destination of [dest, missing]) { - await expect(Bun.write(destination, Bun.file(987_654), { mode: 0o600 })).rejects.toThrow( - expect.objectContaining({ code: "EBADF" }), - ); + 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({ - mode: fs.statSync(dest).mode & 0o777, - intact: fs.readFileSync(dest, "utf8") === content, + 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({ mode: 0o644, intact: true, created: false }); + }).toEqual({ modes: [0o644, 0o644], intact: true, created: false }); }); }); @@ -480,6 +487,26 @@ const IS_UV_FS_COPYFILE_DISABLED = 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); }); + + 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 () => { From 20ea5767580e915adc39d20246e33e4ab9e57ea9 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 2 Oct 2026 16:05:33 +0000 Subject: [PATCH 09/11] Bun.write: compare before every open of the destination The compare with the source now runs inside the loop that opens the destination. The open can fail, make the parent directories, and try again. After that the path can name the source: new/../file with no directory new. do_open_file loses the arms for both files at once, which nothing calls now. --- src/runtime/webcore/blob/copy_file.rs | 62 +++++++++++---------------- test/js/bun/io/bun-write.test.js | 7 ++- 2 files changed, 32 insertions(+), 37 deletions(-) diff --git a/src/runtime/webcore/blob/copy_file.rs b/src/runtime/webcore/blob/copy_file.rs index 227cec724863..da0279437eaf 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()) @@ -620,20 +619,6 @@ impl CopyFile { if source.st_ino != 0 && dest.st_dev == source.st_dev && dest.st_ino == source.st_ino) } - /// Whether the destination path names the regular file that `source` describes. - fn destination_is_source(&self, source: &Stat) -> bool { - if !bun_sys::S::ISREG(source.st_mode as _) { - return false; - } - let mut path_buf = bun_paths::path_buffer_pool::get(); - let path = self - .destination_file_store - .pathlike - .path() - .slice_z(&mut path_buf); - Self::is_same_file(source, &bun_sys::stat_no_path(path)) - } - pub(crate) fn run_async(&mut self) { if let PathOrFileDescriptor::Fd(fd) = &self.destination_file_store.pathlike { self.destination_fd = *fd; @@ -743,7 +728,7 @@ impl CopyFile { } } - if self.do_open_file::<{ IOWhich::Source }>().is_err() { + if self.do_open_file::<{ IOWhich::Source }>(None).is_err() { return; } } @@ -778,8 +763,18 @@ impl CopyFile { } if self.destination_fd == Fd::INVALID { - if self.destination_is_source(&stat) { - // A copy of a file onto itself: nothing to open, empty or write. + // 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) { @@ -789,11 +784,6 @@ impl CopyFile { self.do_close(); return; } - - if self.do_open_file::<{ IOWhich::Destination }>().is_err() { - self.do_close(); - return; - } } debug_assert!(self.destination_fd.is_valid()); diff --git a/test/js/bun/io/bun-write.test.js b/test/js/bun/io/bun-write.test.js index a8bcd3ad64ce..8192925cded0 100644 --- a/test/js/bun/io/bun-write.test.js +++ b/test/js/bun/io/bun-write.test.js @@ -321,6 +321,11 @@ const IS_UV_FS_COPYFILE_DISABLED = ["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 }) => { @@ -341,7 +346,7 @@ const IS_UV_FS_COPYFILE_DISABLED = fs.symlinkSync(file, symlink); fs.linkSync(file, hardlink); - const written = await write({ file, symlink, 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, From f7503887c6a7a9c07e2febf3f978df76cdd8b5a5 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 3 Oct 2026 00:57:05 +0000 Subject: [PATCH 10/11] ci: retrigger From dca77b29f183f2bd88ba4abf3560d7c6d56a413e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:41:54 +0000 Subject: [PATCH 11/11] Bun.write tests: say why each platform gate is there Each skipIf that this branch adds now has its reason above it. The rows for a source that cannot be copied share one gate on their describe. --- test/js/bun/io/bun-write.test.js | 48 +++++++++++++++++--------------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/test/js/bun/io/bun-write.test.js b/test/js/bun/io/bun-write.test.js index 6653c3b894e9..36b5f892f27e 100644 --- a/test/js/bun/io/bun-write.test.js +++ b/test/js/bun/io/bun-write.test.js @@ -370,6 +370,7 @@ const IS_UV_FS_COPYFILE_DISABLED = }); // 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"); @@ -418,6 +419,7 @@ const IS_UV_FS_COPYFILE_DISABLED = }); }); + // `/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( @@ -426,33 +428,31 @@ const IS_UV_FS_COPYFILE_DISABLED = }); }); - describe("Bun.write(dest, Bun.file(src)) with a source that cannot be copied", () => { + // 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.skipIf(isWindows).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); + 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", + ); } - expect({ intact: fs.readFileSync(dest, "utf8") === content, created: fs.existsSync(missing) }).toEqual({ - intact: true, - created: false, - }); - }, - ); + } finally { + if (fd !== undefined) fs.closeSync(fd); + } + expect({ intact: fs.readFileSync(dest, "utf8") === content, created: fs.existsSync(missing) }).toEqual({ + intact: true, + created: false, + }); + }); - it.skipIf(isWindows)("a source fd that is not open rejects and leaves the destination as it was", async () => { + 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"); @@ -489,12 +489,14 @@ const IS_UV_FS_COPYFILE_DISABLED = 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"));