Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 63 additions & 16 deletions src/runtime/webcore/blob/copy_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,26 @@ 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<bool> {
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) {
Comment thread
robobun marked this conversation as resolved.
Resolved
// 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,
Expand Down Expand Up @@ -614,11 +634,6 @@ impl CopyFile {
}

pub(crate) fn run_async(&mut self) {
#[cfg(target_os = "macos")]
let mut stat_: Option<Stat> = None;
#[cfg(not(target_os = "macos"))]
let stat_: Option<Stat> = None;

if let PathOrFileDescriptor::Fd(fd) = &self.destination_file_store.pathlike {
self.destination_fd = *fd;
}
Expand All @@ -627,6 +642,8 @@ impl CopyFile {
self.source_fd = *fd;
}

let mut source_stat: Option<Stat> = 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
Expand All @@ -648,15 +665,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;
Expand All @@ -665,17 +680,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")
Expand Down Expand Up @@ -735,6 +751,15 @@ 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;
}
Expand All @@ -761,13 +786,14 @@ impl CopyFile {
// nothing to do for the Fd case
}

let stat: Stat = match stat_ {
Some(s) => s,
// From the opened fd: the source path can name another file by now.
let stat: Stat = match source_stat {
Some(stat) => stat,
Comment thread
robobun marked this conversation as resolved.
Resolved
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());
self.do_close();
return;
}
},
Expand All @@ -779,6 +805,28 @@ 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;
}
}
}

// 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 _) {
Expand Down Expand Up @@ -861,7 +909,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(_)
Expand Down Expand Up @@ -1022,8 +1070,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;
Comment thread
robobun marked this conversation as resolved.
Resolved
#[cfg(not(windows))]
const OPEN_SOURCE_FLAGS: i32 = bun_sys::O::CLOEXEC | bun_sys::O::RDONLY;

Expand Down
180 changes: 180 additions & 0 deletions test/js/bun/io/bun-write.test.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { dlopen } from "bun:ffi";
import { describe, expect, it, test } from "bun:test";
import fs, { mkdirSync } from "fs";
import {
Expand All @@ -7,7 +8,9 @@ import {
exampleSite,
gcTick,
isASAN,
isLinux,
isWindows,
libcPathForDlopen,
tempDir,
withoutAggressiveGC,
} from "harness";
Expand Down Expand Up @@ -300,6 +303,183 @@ 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 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,
});
});

// 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",
});
});

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 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"])(
Comment thread
robobun marked this conversation as resolved.
Resolved
"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);
},
);

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,
});
});

// 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 () => {
const file = path.join(import.meta.dir, "fetch.js.txt");
await gcTick();
Expand Down
Loading