Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
13 changes: 11 additions & 2 deletions src/js/node/fs.promises.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1638,7 +1638,11 @@ async function writeFileAsyncIterator(fdOrPath, iterable, optionsOrEncoding, fla
}

if (signal?.aborted) {
if (mustClose) await fs.close(fdOrPath);
if (mustClose) {
try {
await fs.close(fdOrPath);
} catch {}
}
throw $makeAbortError(undefined, { cause: signal.reason });
}
Comment thread
robobun marked this conversation as resolved.
Resolved

Expand All @@ -1660,7 +1664,12 @@ async function writeFileAsyncIterator(fdOrPath, iterable, optionsOrEncoding, fla
} catch {}
}

await fs.close(fdOrPath);
try {
await fs.close(fdOrPath);
Comment on lines +1671 to +1672

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟣 pre-existing, not blocking: pre-existing: users writing to SMB (or a FUSE daemon that reports a flush error once) with fs.promises.writeFile(path, iterable) still get a resolved promise after a lost write, which Node rejects with ENOSPC. writeFileAsyncIteratorInner writes through Bun.file(fd).writer(), a dup of the fd (src/io/openForWriting.rs:34), and its close drops the errno; cifs clears the error on the first close, so fs.close at src/js/node/fs.promises.ts:1668 sees 0. Fix: carry the sink's close error (or write through the original fd so one close reports), covering FileHandle.writeFile(iterable) too. The shim faults every close, so the test cannot see this.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

A user calls fs.promises.writeFile(path, asyncIterable) on a cifs mount that is out of space; write(2) succeeds and the error is reported at close. writeFileAsyncIteratorInner (src/js/node/fs.promises.ts:1574) creates Bun.file(fd).writer(), which open_for_writing turns into dup_with_flags(fd, 0) (src/io/openForWriting.rs:34). await writer.end() (src/js/node/fs.promises.ts:1600) closes that dup on the work pool; Closer::run calls Fd::close() (src/io/lib.rs:2225), which discards the errno. cifs_flush test_and_clear_bit()s AS_ENOSPC/AS_EIO, so only the first close of the open file description gets ENOSPC. When the dup's close runs first the fs.close at src/js/node/fs.promises.ts:1668 returns 0 and the new catch at 1669-1672 never runs; writeFile resolves. The base branch also resolves here, so this is pre-existing, but the PR's test (test/js/node/fs/fs-close-error.test.ts:67, 202) asserts "ENOSPC close" for this path, which passes only because fs-close-error-shim.c:57-62 fails every close of a matching file, including the dup.

Verification: pre-existing. Trigger: fs.promises.writeFile(path, asyncIterable) on a cifs mount, when the write error surfaces at close. The sink writes to a dup (src/io/openForWriting.rs:34); Closer::run drops the errno (src/io/lib.rs:2224); cifs_flush clears the error, so fs.close at fs.promises.ts:1668 returns 0 and the promise resolves after a lost write. The shim fails every close, so the dup also fails.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. The writer of writeFileAsyncIteratorInner is a FileSink on a duplicate of the descriptor, and its close drops the result. On NFS and SMB that first close gets the error, so the fs.close after it returns 0.

This PR does not change that. Downsides lists FileSink as not fixed, and the Notes have this case under "Not covered". To carry the error of the sink changes FileSink for every user of Bun.file().writer(), so it needs a change of its own.

The comment of the fixture now says that the shim fails both closes, and that on NFS and SMB only the first one gets the error.

} catch (closeError) {
// As node's handleFdClose, the error of the write keeps its place: https://github.com/nodejs/node/blob/v26.3.0/lib/internal/fs/promises.js#L1075-L1086
error = error ? require("internal/errors").aggregateTwoErrors(closeError as Error, error) : (closeError as Error);
}
}

// Abort signal shadows other errors
Expand Down
9 changes: 6 additions & 3 deletions src/js/node/http2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2995,9 +2995,10 @@ function withStreamFrame(handler) {
return runInFrame(frame, handler, undefined, self, stream, a, b, c);
};
}
// Node asserts on this close. The fd was only read: https://github.com/nodejs/node/blob/v26.3.0/lib/internal/http2/core.js#L475-L479
function tryClose(fd) {
try {
fs.close(fd);
fs.close(fd, () => {});
} catch {}
}

Expand Down Expand Up @@ -3139,15 +3140,17 @@ function doSendFileFD(options, fd, headers, err, stat) {
// stream itself goes away (peer reset, session destroy), stop reading the file. Like node's
// onFileUnpipe, only an fd the stream opened itself (respondWithFile) is closed here; an fd
// handed to respondWithFD stays the caller's to close.
fileStream.on("error", onFileStreamError.bind(this));
fileStream.on("error", onFileStreamError.bind(this, fileStream));
this.once("close", () => {
fileStream.unpipe(sink);
if (ownsFd) fileStream.destroy();
else fileStream.pause();
});
fileStream.pipe(sink);
}
function onFileStreamError(this: Http2Stream) {
function onFileStreamError(this: Http2Stream, fileStream) {
// After "end" only the close can fail, and the fd was only read. Node destroys the stream: https://github.com/nodejs/node/blob/v26.3.0/lib/internal/http2/core.js#L2685-L2691
if (fileStream.readableEnded) return;
if (!this.destroyed && !this.closed) this.close(NGHTTP2_INTERNAL_ERROR);
}
const kFileResponseFinal = Symbol("fileResponseFinal");
Expand Down
5 changes: 3 additions & 2 deletions src/js/node/wasi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -862,8 +862,9 @@ class WASI {
}),
fd_close: wrap(fd => {
const stats = CHECK_FD(fd, BigInt(0));
fs.closeSync(stats.real);
// close(2) releases the descriptor even when it reports an error, so the entry goes first. uvwasi keeps it: https://github.com/nodejs/node/blob/v26.3.0/deps/uvwasi/src/uvwasi.c#L813-L816
this.FD_MAP.delete(fd);
fs.closeSync(stats.real);
return WASI_ESUCCESS;
}),
fd_datasync: wrap(fd => {
Expand Down Expand Up @@ -1167,9 +1168,9 @@ class WASI {
fd_renumber: wrap((from, to) => {
const fromEntry = CHECK_FD(from, BigInt(0));
const toEntry = CHECK_FD(to, BigInt(0));
fs.closeSync(fromEntry.real);
this.FD_MAP.set(from, toEntry);
this.FD_MAP.delete(to);
fs.closeSync(fromEntry.real);
Comment on lines 1169 to +1173

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟣 pre-existing, not blocking: pre-existing: WASI guests calling fd_renumber(from, to) get the two descriptors swapped the wrong way, so the file they meant to keep is closed and to becomes EBADF. The reordered body at src/js/node/wasi.ts:1171-1173 still maps from to the old to entry, deletes to, and closes fromEntry.real, which is the inverse of WASI/uvwasi semantics (close to's file, move from's entry to to, delete from). The new test at test/js/bun/wasm/wasi.test.js:305 asserts this inverted mapping and so certifies it. Fix: close toEntry.real, set FD_MAP.set(to, fromEntry), delete from (no-op when from === to), and update the test to expect to holding the former from entry.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

A guest calls fd_renumber(5, 3) through wasiImport, expecting fd 3 to afterwards refer to the file that fd 5 held and fd 5 to be released (wasi_snapshot_preview1 fd_renumber; uvwasi_fd_table_renumber(dst=to, src=from) closes dst's file and copies src into dst). In src/js/node/wasi.ts:1169-1173 the code instead keeps entry 5 pointing at the old fd 3 file, deletes entry 3, and closes fromEntry.real, the file the guest wanted to keep. The guest's next read or write on fd 3 returns WASI_EBADF, and any further use of fd 5 hits the file that should have been discarded, while the real host descriptor of the kept file is already closed. The base branch behaves the same way (only the closeSync call moved), so this is pre-existing; the new test test/js/bun/wasm/wasi.test.js:298-306 pins the inverted result ({ from: secondEntry, to: false }), so it locks the bug in rather than guarding against it.

Verification: pre-existing — the base branch already has the inverted mapping; this PR reorders the body and adds a test that pins the inverted behavior. Triggering condition: any WASI guest calling fd_renumber(from, to). At src/js/node/wasi.ts:1168-1175 from now points at the old to resource, to is gone, and the real fd behind from is closed, so the next fd_read on to returns WASI_EBADF (8).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, and it is older than this PR. uvwasi closes to and moves from into it (fd_table.c#L441-L456). wasi.ts does the reverse.

This PR only moves the map update before the close, so I left the direction for a change of its own. The test no longer pins it: it now asserts that no guest number maps to the descriptor that the call closed. The Notes list the inversion under "Found, not changed here".

return WASI_ESUCCESS;
}),
fd_seek: wrap((fd, offset, whence, newOffsetPtr) => {
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/node/node_fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4727,7 +4727,7 @@ impl NodeFS {

pub(crate) fn close(&mut self, args: &args::Close, _: Flavor) -> Maybe<ret::Close> {
// Explicit `fs.close`/`fs.closeSync` must close the descriptor the user
// asked for, including stdio (0/1/2), and surface EBADF like Node does.
// asked for, including stdio (0/1/2), and report the error like Node does.
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
// The stdio guard only applies to Bun's own internal closes.
if let Some(err) = args.fd.close_allowing_standard_io(None) {
Err(err)
Expand Down
5 changes: 4 additions & 1 deletion src/sys/fd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ pub trait FdExt: Copy + Sized {
) -> Option<sys::Error>;
/// fd allows you to close standard io. It also returns the error.
/// Use fd API to implement `node:fs` close: stdio must actually close and
/// EBADF must surface to the caller. Consider fd the raw close method.
/// the error must surface to the caller. Consider fd the raw close method.
fn close_allowing_standard_io(self, return_address: Option<usize>) -> Option<sys::Error>;
/// Assumes given a valid file descriptor. If error, the handle has not been closed.
fn make_lib_uv_owned(self) -> Result<Fd, MakeLibUvOwnedError>;
Expand All @@ -68,6 +68,9 @@ pub trait FdExt: Copy + Sized {
impl FdExt for Fd {
fn close(self) {
let err = self.close_allowing_bad_file_descriptor(None);
#[cfg(unix)]
debug_assert!(err.is_none_or(|e| e.get_errno() != sys::E::EBADF)); // use after close!
#[cfg(windows)]
debug_assert!(err.is_none()); // use after close!
}

Expand Down
7 changes: 4 additions & 3 deletions src/sys/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1951,12 +1951,13 @@ mod posix_impl {
if rc < 0 { Err(last_errno()) } else { Ok(()) }
}
}
/// Closes `fd` and returns the error that callers see. Only EBADF surfaces.
/// Closes `fd` and returns the error for the caller. A file system can report a write error first at close.
#[inline]
pub(crate) fn close_error(fd: Fd) -> Option<Error> {
match close_once(fd) {
Err(libc::EBADF) => Some(Error::from_code_int(libc::EBADF, Tag::close).with_fd(fd)),
_ => None,
// A close in progress: https://github.com/nodejs/node/blob/v26.3.0/deps/uv/src/unix/fs.c#L158-L167
Ok(()) | Err(libc::EINTR | libc::EINPROGRESS) => None,
Err(errno) => Some(Error::from_code_int(errno, Tag::close).with_fd(fd)),
Comment on lines +1959 to +1960

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟣 pre-existing, not blocking: Apps that call fs.close(fd) without a callback now get an unhandled rejection instead of Node's uncaught exception when the close fails. src/sys/lib.rs:1960 makes ENOSPC/EDQUOT/EIO reach fs.close, and the no-callback arm at src/js/node/fs.ts:94 does fs.close(fd).then(() => {}), so the error surfaces only as an unhandled rejection. In Bun's default mode that prints, sets exit code 1 and keeps running; uncaughtException handlers never see it. Fix: route the no-callback case through fs.closeCb with a guarded default callback that rethrows the error, so every fs-reported close error takes the uncaughtException path like Node. Pre-existing for EBADF; this PR widens it to environment errors.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

User code opens a file on NFS/SMB/FUSE, writes, and calls fs.close(fd) with no callback, which is common fire-and-forget usage. After src/sys/lib.rs:1959-1960 the close's ENOSPC/EDQUOT/EIO is returned as an error where the base returned None. src/js/node/fs.ts:89-97 handles the missing callback with fs.close(fd).then(() => {}), so the rejection has no handler. src/jsc/VirtualMachine.rs:4392-4398 and 4450-4451 show the default Mode::Bun path: Bun__handleUnhandledRejection only consults unhandledRejection listeners, never uncaughtException, then the default handler prints the error and bumps unhandled_error_counter so the process later exits 1 while continuing to run. Node's close(fd, callback = defaultCloseCallback) throws the error from the FS callback, so it goes to process.on('uncaughtException') handlers or crashes. On the base branch only EBADF (a programming bug) could reach this arm; after the PR a file-system condition in production does.

Verification: src/sys/lib.rs:1957-1961 now returns Some(Error) for every errno except EINTR/EINPROGRESS (base returned it only for EBADF). src/js/node/fs.ts:89-97 (untouched by the PR) handles the missing-callback case with fs.close(fd).then(() => {}) — no rejection handler, so the error becomes an unhandled rejection. The process continues; uncaughtException listeners never see it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. Node throws the error from defaultCloseCallback (fs.js#L488-L505). Bun's arm for no callback has been a promise since #10229, so EBADF already takes this path.

To move it to the callback arm changes what an unhandledRejection handler sees for EBADF today. That is a change of its own, so it is not in this PR. The Notes list it under "Found, not changed here".

}
}
pub fn close(fd: Fd) -> Maybe<()> {
Expand Down
4 changes: 2 additions & 2 deletions src/sys/linux_syscall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,13 +149,13 @@ pub(crate) fn pwrite(fd: Fd, buf: &[u8], off: i64) -> Result<usize, i32> {

/// `close(2)` — single shot, never retried (Linux may have already released
/// the fd on EINTR; retrying could close a racing thread's new fd). Returns
/// `Err(EBADF)` etc. on failure; callers only surface `EBADF`.
/// the errno on failure.
#[inline]
pub(crate) fn close(fd: i32) -> Result<(), i32> {
// rustix's safe `io::close(OwnedFd)` is infallible by design (it swallows
// the rc because POSIX says "the fd is released regardless"), and
// constructing an `OwnedFd` from a possibly-invalid int is UB — but we
// *need* the rc to surface `EBADF` (debug double-close detection).
// *need* the rc: `EBADF` is a double close, and a file system can report a write error here.
//
// rustix has no public generic `syscall!`, so go through `libc::syscall`
// with `SYS_close`. This is *not* the glibc `close(3)` wrapper: `syscall(2)`
Expand Down
60 changes: 60 additions & 0 deletions test/js/bun/wasm/wasi.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -252,3 +252,63 @@ it("fd_pread counts each byte once and reads the next iov from where the last on
second: memory.toString("latin1", secondBuf, secondBuf + 4),
}).toEqual({ nread: 8, first: "2345", second: "6789" });
});

// A file system can report a write error first at close(2). The descriptor is
// released all the same, so the guest's entry for it must go.
function bindingsWithFailingClose(closed = []) {
return {
hrtime: () => process.hrtime.bigint(),
exit: () => {},
kill: () => {},
randomFillSync: array => crypto.getRandomValues(array),
isTTY: () => false,
path,
fs: {
...fs,
closeSync(fd) {
fs.closeSync(fd);
closed.push(fd);
throw Object.assign(new Error("ENOSPC: no space left on device, close"), { code: "ENOSPC" });
},
},
};
}

it("fd_close forgets the descriptor when the close reports an error", () => {
using dir = tempDir("wasi-fd-close-error", {});
const wasi = new WASI({ preopens: { "/": String(dir) }, bindings: bindingsWithFailingClose() });

const WASI_EBADF = 8;
const WASI_ENOSPC = 51;
const preopenFd = 3;

expect(wasi.wasiImport.fd_close(preopenFd)).toBe(WASI_ENOSPC);
expect(wasi.FD_MAP.has(preopenFd)).toBe(false);
// A second fd_close must not close the number again: another file can have it by now.
expect(wasi.wasiImport.fd_close(preopenFd)).toBe(WASI_EBADF);
});

it("fd_renumber forgets the descriptor that it closed when the close reports an error", () => {
using first = tempDir("wasi-fd-renumber-error-1", {});
using second = tempDir("wasi-fd-renumber-error-2", {});
const closed = [];
const wasi = new WASI({
preopens: { "/first": String(first), "/second": String(second) },
bindings: bindingsWithFailingClose(closed),
});

const WASI_ENOSPC = 51;
const preopened = [wasi.FD_MAP.get(3).real, wasi.FD_MAP.get(4).real];

try {
expect(wasi.wasiImport.fd_renumber(3, 4)).toBe(WASI_ENOSPC);
// The call closed one of the two. No number of the guest may still name it.
const mapped = [...wasi.FD_MAP.values()].map(entry => entry.real);
expect({ closed: closed.length, closedAndMapped: mapped.filter(real => closed.includes(real)) }).toEqual({
closed: 1,
closedAndMapped: [],
});
} finally {
for (const real of preopened) if (!closed.includes(real)) fs.closeSync(real);
}
});
63 changes: 63 additions & 0 deletions test/js/node/fs/fs-close-error-shim.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// LD_PRELOAD shim that stands in for a file system that reports a write error
// at close(2), as NFS, SMB and FUSE can do for ENOSPC, EDQUOT and EIO.
//
// It acts on a file whose name ends with ".<errno>.close-fault", for example
// "copy.28.close-fault" for ENOSPC, through a descriptor that is open for
// writing. A close of such a descriptor releases it, as the kernel does, then
// fails with that errno and writes one line to stderr. With
// CLOSE_FAULT_READERS set, a descriptor that is open for reading counts too
// (FUSE calls flush for each close).
//
// bun closes through syscall(SYS_close, fd), so syscall() is the symbol to
// interpose. glibc only.
#define _GNU_SOURCE
#include <ctype.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>

#define SUFFIX ".close-fault"

static long (*next_syscall)(long, ...);

// The errno that the close of `fd` reports, or 0.
static int fault_for(int fd) {
char link[64], target[4096];
if (fd < 3) return 0;
int flags = fcntl(fd, F_GETFL);
if (flags < 0) return 0;
if ((flags & O_ACCMODE) == O_RDONLY && !getenv("CLOSE_FAULT_READERS")) return 0;
snprintf(link, sizeof link, "/proc/self/fd/%d", fd);
ssize_t n = readlink(link, target, sizeof target - 1);
if (n <= (ssize_t)strlen(SUFFIX)) return 0;
target[n] = 0;
char *suffix = target + n - strlen(SUFFIX);
if (strcmp(suffix, SUFFIX) != 0) return 0;
char *digits = suffix;
while (digits > target && isdigit((unsigned char)digits[-1])) digits--;
if (digits == suffix || digits == target || digits[-1] != '.') return 0;
return atoi(digits);
}

long syscall(long nr, ...) {
va_list ap;
va_start(ap, nr);
long a1 = va_arg(ap, long), a2 = va_arg(ap, long), a3 = va_arg(ap, long);
long a4 = va_arg(ap, long), a5 = va_arg(ap, long), a6 = va_arg(ap, long);
va_end(ap);
if (!next_syscall) next_syscall = dlsym(RTLD_NEXT, "syscall");
if (nr != SYS_close) return next_syscall(nr, a1, a2, a3, a4, a5, a6);

int fault = fault_for((int)a1);
long rc = next_syscall(nr, a1);
if (fault == 0 || rc != 0) return rc;
dprintf(2, "close-fault: errno %d\n", fault);
errno = fault;
return -1;
}
Loading
Loading