Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
17 changes: 8 additions & 9 deletions src/install/lifecycle_script_runner.zig
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,10 @@ pub const LifecycleScriptSubprocess = struct {
combined_script,
null,
};
if (Environment.isWindows) {
const buffer_output = this.manager.options.log_level != .silent and
!this.manager.options.log_level.isVerbose() and
!this.foreground;
if (Environment.isWindows and buffer_output) {
this.stdout.source = .{ .pipe = bun.new(uv.Pipe, std.mem.zeroes(uv.Pipe)) };
this.stderr.source = .{ .pipe = bun.new(uv.Pipe, std.mem.zeroes(uv.Pipe)) };
}
Expand All @@ -196,20 +199,16 @@ pub const LifecycleScriptSubprocess = struct {
else
.ignore,

.stdout = if (this.manager.options.log_level == .silent)
.ignore
else if (this.manager.options.log_level.isVerbose() or this.foreground)
.inherit
.stdout = if (!buffer_output)
if (this.manager.options.log_level == .silent) .ignore else .inherit
else if (Environment.isPosix)
.buffer
else
.{
.buffer = this.stdout.source.?.pipe,
},
.stderr = if (this.manager.options.log_level == .silent)
.ignore
else if (this.manager.options.log_level.isVerbose() or this.foreground)
.inherit
.stderr = if (!buffer_output)
if (this.manager.options.log_level == .silent) .ignore else .inherit
else if (Environment.isPosix)
.buffer
else
Expand Down
11 changes: 7 additions & 4 deletions src/io/PipeReader.zig
Original file line number Diff line number Diff line change
Expand Up @@ -980,11 +980,11 @@
MaxBuf.removeFromPipereader(&this.maxbuf);
this.buffer().deinit();
const source = this.source orelse return;
this.source = null;
if (!source.isClosed()) {
// closeImpl will take care of freeing the source
this.closeImpl(false);
}
this.source = null;
}

pub fn setRawMode(this: *WindowsBufferedReader, value: bool) bun.sys.Maybe(void) {
Comment on lines 980 to 990

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.

🟣 This is a pre-existing issue: in WindowsBufferedReader.deinit(), buffer().deinit() frees _buffer before closeImpl(false) runs file.detach()/uv_cancel(), leaving a theoretical window where an in-flight uv_fs_read thread-pool worker could write into freed memory. This PR does not introduce or worsen the race — the old code was strictly worse (closeImpl was a complete no-op due to the earlier this.source = null assignment). All current callers that use file sources either assert remaining_fds == 0 before deinit or call close() first, so the vulnerable code path is not reachable in practice.

Extended reasoning...

What the bug is and how it manifests

In WindowsBufferedReader.deinit() (PipeReader.zig ~line 938), this.buffer().deinit() is called first, freeing the heap memory backing _buffer. Then, if the source is not yet closed, closeImpl(false) is called, which for .file sources calls file.detach() → file.stop() → uv_cancel(). The libuv uv_fs_read API uses a thread-pool worker that calls ReadFile directly into file.iov.base, which points into the already-freed _buffer.allocatedSlice(). If the thread-pool worker is actively writing when deinit() frees the buffer, this is a write to freed memory (heap corruption / UAF).

The specific code path that triggers it

For a .file or .sync_file source with an in-flight uv_fs_read:

  1. Caller calls deinit()
  2. this.buffer().deinit() → frees _buffer heap allocation
  3. closeImpl(false) → file.detach() → file.stop() → uv_cancel()
  4. If uv_cancel returns UV_EBUSY (I/O already submitted to kernel), the OS ReadFile completes and writes into the freed memory region
  5. onFileRead fires, sees parent_ptr == null (detach set fs.data = null), and returns safely — but the buffer corruption already occurred at step 4

Why existing code doesn't prevent it

uv_cancel is not guaranteed to succeed for I/O that is already in-flight with the kernel. After uv_cancel returns, the thread-pool worker may still be in the middle of ReadFile, writing into the freed buffer memory.

Why this is pre-existing and not introduced by this PR

Before this PR, this.source = null was assigned BEFORE the closeImpl call, making closeImpl a complete no-op (it checks if (this.source) |source| immediately). This was strictly worse: the buffer was freed AND the in-flight read was never even attempted to be cancelled. Additionally, onFileRead would fire with a non-null parent_ptr pointing to potentially freed/reused struct memory — a UAF of the struct itself. The PR's fix makes closeImpl actually run and adds file.detach() which sets fs.data = null so onFileRead returns early without touching this, improving safety even though the buffer-memory ordering concern remains.

Impact and current exploitability

In practice, this is not reachable through any current caller. The lifecycle script runner uses .pipe sources on Windows (not .file) when buffer_output is true, so the uv_fs_read path is never taken. Additionally, resetPolls() asserts remaining_fds == 0 before calling deinit(), guaranteeing all reads have completed. Other callers either assert the source is closed/null before deinit, or call close() first which properly defers cleanup via the defer_done_callback mechanism.

How to fix it

Move buffer().deinit() to after closeImpl() completes — or defer the _buffer free to the onFileRead callback after cancel completes (similar to how defer_done_callback defers the done() call). A simpler short-term fix is to document the ordering invariant: callers must ensure no in-flight reads exist before calling deinit(), which is already enforced by the assertions in current callers.

Expand Down Expand Up @@ -1053,12 +1053,13 @@
// Get parent before completing (fs.data may be null if detached)
const parent_ptr = fs.data;

// ALWAYS complete the read first (cleans up fs_t, updates state)
// ALWAYS complete the read first (cleans up fs_t, updates state).
// NOTE: when detached (parent_ptr == null), complete() finalizes `file`
// (async close or immediate destroy) — must not be dereferenced past
// this point on the detached branch.
file.complete(was_canceled);

// If detached, file should be closing itself now
if (parent_ptr == null) {
bun.assert(file.state == .closing); // complete should have started close
return;
}

Expand Down Expand Up @@ -1194,10 +1195,12 @@

pub fn closeImpl(this: *WindowsBufferedReader, comptime callDone: bool) void {
if (this.source) |source| {
switch (source) {
.sync_file, .file => |file| {
// Detach - file will close itself after operation completes
// (or just free the struct if the caller owns the fd).
file.close_fd = this.flags.close_handle;
file.detach();

Check notice on line 1203 in src/io/PipeReader.zig

View check run for this annotation

Claude / Claude Code Review

closeImpl .pipe/.tty arms still ignore flags.close_handle

🟣 Pre-existing (not introduced here, just adjacent to fix #3): the `.pipe`/`.tty` arms of `closeImpl` still call `pipe.close()`/`tty.close()` unconditionally, ignoring `flags.close_handle`. `FileResponseStream` sets `close_handle = false` and closes the fd itself via `Closer.close(this.fd)`, so on Windows when the served fd resolves to a named pipe (`uv_guess_handle` → `.pipe`), both `uv_close` and `uv_fs_close` end up closing the same CRT fd. This was already reachable on the common EOF path be
Comment on lines +1201 to 1203

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 touched by this PR): the parallel writer path in WindowsPipeWriter.close() (src/io/PipeWriter.zig:829-835) leaks the heap Source.File when owns_fd=false — it does file.stop(); file.fs.data = null; without ever reaching finalize(), so the struct allocated in openFile() is never freed (reachable via shell/IOWriter.zig:26 on Windows). The close_fd mechanism added here is exactly what would fix it (file.close_fd = false; file.detach();), so it may be worth applying symmetrically while you're in this area.

Extended reasoning...

What the bug is

This PR adds Source.File.close_fd and threads it through WindowsBufferedReader.closeImpl (PipeReader.zig:1158-1160) so that when the caller owns the fd, file.detach() → finalize() frees the heap struct without calling uv_fs_close. The parallel code path in WindowsPipeWriter.close() was not updated and still leaks the heap Source.File struct in the !owns_fd branch:

// src/io/PipeWriter.zig:826-835
switch (source) {
    .sync_file, .file => |file| {
        if (this.owns_fd) {
            file.detach();
        } else {
            // Don't own fd, just stop operations and detach parent
            file.stop();
            file.fs.data = null;   // <-- struct never freed
        }
    },

The specific code path that triggers it

shell/IOWriter.zig:26 sets .owns_fd = false on Windows. When such a writer's source is a .file/.sync_file (heap-allocated via bun.default_allocator.create in Source.openFile()), close() enters the else branch above.

Why existing code doesn't free it — step-by-step proof

  1. close() is called with owns_fd == false and source == .file.
  2. file.stop(): if a write is in flight (state == .operating), attempts uv_cancel and may set state = .canceling. It does not set close_after_operation. If no op is in flight (state == .deinitialized), stop() is a no-op.
  3. file.fs.data = null and this.source = null. The writer drops its only pointer to the struct.
    4a. No op in flight: nothing else ever touches this File*. Leaked outright.
    4b. Op in flight: onFsWriteComplete fires (PipeWriter.zig:1025-1037 / 1355-1368). It reads parent_ptr = fs.data (now null), calls file.complete(was_canceled). Inside complete() (source.zig:108-123), close_after_operation is still false (only detach() sets it), so it does fs.deinit(); state = .deinitialized; and returns without calling finalize(). Back in onFsWriteComplete, parent_ptr == null → return. The struct is leaked.

In neither case does any path reach bun.default_allocator.destroy(file) or onCloseComplete.

Why this is pre-existing and unrelated to this PR

src/io/PipeWriter.zig is not in the diff. The PR adds no new callers of this path and does not change its reachability. The new close_fd/finalize() machinery has zero effect on the writer's !owns_fd branch because that branch never invokes detach() or finalize(). The leak existed before this PR and behaves identically after it.

Impact

A small (@sizeOf(Source.File), dominated by uv.fs_t) heap leak per shell IOWriter whose underlying handle is a regular file on Windows. Not a correctness issue — the fd itself is not leaked (the caller closes it).

How to fix

Replace the else branch with the same pattern this PR uses on the reader side:

} else {
    // Don't own fd — free the struct without closing.
    file.close_fd = false;
    file.detach();
}

detach() sets close_after_operation = true, calls stop(), and either finalizes immediately (idle) or via complete() after the in-flight write fires — and with close_fd = false, finalize() destroys the struct without uv_fs_close. This is safe with the existing onFsWriteComplete callbacks since they already capture parent_ptr before file.complete() and don't dereference file afterward on the detached branch.

Comment on lines 1198 to 1203

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 introduced here, just adjacent to fix #3): the .pipe/.tty arms of closeImpl still call pipe.close()/tty.close() unconditionally, ignoring flags.close_handle. FileResponseStream sets close_handle = false and closes the fd itself via Closer.close(this.fd), so on Windows when the served fd resolves to a named pipe (uv_guess_handle → .pipe), both uv_close and uv_fs_close end up closing the same CRT fd. This was already reachable on the common EOF path before this PR (onRead(.eof) → close() → closeImpl(true)); the deinit reordering only adds the rarer read-error path. Worth a follow-up to gate .pipe/.tty on close_handle for symmetry, but not blocking.

Extended reasoning...

What the bug is

This PR's fix #3 threads flags.close_handle into the .file/.sync_file arm of WindowsBufferedReader.closeImpl (PipeReader.zig:1198-1203) via the new file.close_fd field, so that when the caller owns the fd the reader frees the heap struct without issuing uv_fs_close. The .pipe arm (lines 1205-1209) and .tty arm (lines 1210-1219) immediately below were not given the same treatment — they still call pipe.close(onPipeClose) / tty.close(onTTYClose) unconditionally, regardless of this.flags.close_handle.

The specific code path

FileResponseStream (src/runtime/server/FileResponseStream.zig:104) sets reader.flags.close_handle = false and later closes the fd itself in deinit (line 382) via bun.Async.Closer.close(this.fd, …) → uv_fs_close. On Windows, reader.start() calls Source.open() which dispatches on uv_guess_handle; if the served fd is a named pipe (e.g. serving Bun.file('\\\\.\\pipe\\foo') as an HTTP response body), the resulting source is .pipe, not .file.

When that pipe reaches closeImpl, the .pipe arm runs pipe.close(onPipeClose) → uv_close. libuv's pipe__close_pipe for a handle opened via uv_pipe_open calls _close(fd) on the stored CRT fd. Then FileResponseStream.deinit runs Closer.close(this.fd) → uv_fs_close → _close(fd) on the same CRT fd. That is a double close — exactly the class of bug fix #3 addresses for .file sources (a later open can reuse the fd between the two closes, so the second close hits an unrelated handle).

Why this is pre-existing, not introduced by this PR

The dominant trigger was already reachable before any change in this PR. On the normal EOF path: onStreamRead(UV_EOF) → onRead(.eof) → close(this) → closeImpl(true) → .pipe arm → pipe.close(onPipeClose). That call chain is untouched by the diff and never depended on the source = null ordering bug (that bug only affected deinit's closeImpl, not close()'s). So a FileResponseStream wrapping a Windows named pipe with auto_close=true was already calling both pipe.close() and Closer.close(fd) on every successful completion prior to this PR. Fix #1's deinit reordering merely adds the read-error path (onStreamRead error → onError → onReaderError → deref → deinit with a live .pipe source) as a second, rarer entry into the same pre-existing defect.

Step-by-step proof (EOF path, pre-PR and post-PR identical)

  1. Windows: user returns new Response(Bun.file('\\\\.\\pipe\\name')) from a Bun.serve handler; FileResponseStream is created with auto_close=true (RequestContext.zig:992 / FileRoute.zig:339 default).
  2. reader.flags.close_handle = false is set (FileResponseStream.zig:104); reader.start(fd, …) → Source.open → uv_guess_handle returns .named_pipe → source = .{ .pipe = … } with uv_pipe_open(fd).
  3. Writer closes the pipe → libuv fires onStreamRead with UV_EOF → onRead(.{.result=0}, "", .eof) → _onReadChunk then close(this).
  4. close() → stopReading() → closeImpl(true) → .pipe arm: pipe.close(onPipeClose) → uv_close queued; on the next loop tick libuv's pipe close runs _close(crt_fd).
  5. done() → onReaderDone → … → response finishes → FileResponseStream refcount hits 0 → deinit → Closer.close(this.fd, loop) → uv_fs_close → threadpool _close(crt_fd) again. Double close.

Impact

Edge-case (serving a Windows named-pipe handle as an HTTP body), but when hit it is the same fd-reuse corruption fix #3 was written to eliminate for regular files. The PR strictly improves the .file case and does not make the .pipe case meaningfully worse than it already was on the common path.

How to fix

Apply the same gating to the .pipe/.tty arms. Note that you cannot simply skip uv_close on a uv_pipe_t (the handle struct must be uv_closed before being freed, and uv_close on a pipe opened via uv_pipe_open will close the fd), so the cleaner fix is probably on the consumer side: when Source.open produced a .pipe/.tty for a close_handle=false reader, have FileResponseStream skip its own Closer.close (the reader has effectively taken ownership of the fd). Either way it's a sensible follow-up while in this area, not a blocker for this PR.

},
.pipe => |pipe| {
pipe.data = pipe;
Expand Down
42 changes: 30 additions & 12 deletions src/io/source.zig
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ pub const Source = union(enum) {
/// When true, file will close itself when the current operation completes.
close_after_operation: bool = false,

/// When false, finalize() frees this struct without calling uv_fs_close
/// — the caller owns the fd. Mirrors BufferedReader.flags.close_handle.
close_fd: bool = true,

/// Get the File struct from an fs_t pointer using field offset.
pub fn fromFS(fs: *uv.fs_t) *File {
return @fieldParentPtr("fs", fs);
Expand Down Expand Up @@ -84,22 +88,25 @@ pub const Source = union(enum) {
}
}

/// Detach from parent and schedule automatic cleanup.
/// If an operation is in progress, it will complete and then close the file.
/// If idle, closes the file immediately.
/// Detach from parent and schedule automatic cleanup. After this call,
/// `this` may be freed (immediately when idle and `close_fd == false`,
/// or via `onCloseComplete` once the async close finishes).
pub fn detach(this: *File) void {
this.fs.data = null;
this.close_after_operation = true;
this.stop();

if (this.state == .deinitialized) {
this.close_after_operation = false;
this.startClose();
this.finalize();
}
}

/// Mark the operation as complete and clean up.
/// Must be called first in the callback before processing data.
/// Mark the operation as complete and clean up. Called first in the
/// callback. When detached with an op in flight (`close_after_operation`),
/// this frees `this` (immediately when `close_fd == false`, or via the
/// async close callback) — callers must not dereference `this` afterward
/// on that branch.
pub fn complete(this: *File, was_canceled: bool) void {
bun.assert(this.state == .operating or this.state == .canceling);
if (was_canceled) {
Expand All @@ -111,14 +118,21 @@ pub const Source = union(enum) {

if (this.close_after_operation) {
this.close_after_operation = false;
this.startClose();
this.finalize();
}
}

fn startClose(this: *File) void {
/// Either start an async close (when `close_fd`) or destroy immediately.
/// `this` must not be dereferenced after this returns.
fn finalize(this: *File) void {
bun.assert(this.state == .deinitialized);
this.state = .closing;
_ = uv.uv_fs_close(uv.Loop.get(), &this.fs, this.file, onCloseComplete);
if (this.close_fd) {
this.state = .closing;
_ = uv.uv_fs_close(uv.Loop.get(), &this.fs, this.file, onCloseComplete);
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
} else {
// Caller owns the fd — free this struct without closing.
bun.default_allocator.destroy(this);
}
}

fn onCloseComplete(fs: *uv.fs_t) callconv(.c) void {
Expand Down Expand Up @@ -285,8 +299,12 @@ pub const Source = union(enum) {
log("openFile (fd = {f})", .{fd});
const file = bun.handleOom(bun.default_allocator.create(Source.File));

file.* = std.mem.zeroes(Source.File);
file.file = fd.uv();
file.* = .{
.fs = std.mem.zeroes(uv.fs_t),
.iov = std.mem.zeroes(uv.uv_buf_t),
.file = fd.uv(),
// state/close_after_operation/close_fd take their declared defaults
};
return file;
}

Expand Down
10 changes: 10 additions & 0 deletions src/runtime/webcore/FileReader.zig
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,11 @@ pub fn onStart(this: *FileReader) streams.Start {
this.waiting_for_onReaderDone = true;
_ = this.parent().incrementCount();
}
} else if (comptime Environment.isWindows) {
if (this.reader.source != null and !this.reader.isDone()) {
this.waiting_for_onReaderDone = true;
_ = this.parent().incrementCount();
}
}

if (comptime Environment.isPosix) {
Expand Down Expand Up @@ -622,6 +627,11 @@ pub fn onReaderError(this: *FileReader, err: bun.sys.Error) void {

this.pending.result = .{ .err = .{ .Error = err } };
this.pending.run();

if (this.waiting_for_onReaderDone) {
this.waiting_for_onReaderDone = false;
_ = this.parent().decrementCount();
}
}

pub fn setRawMode(this: *FileReader, flag: bool) bun.sys.Maybe(void) {
Expand Down
20 changes: 11 additions & 9 deletions src/runtime/webcore/ReadableStream.zig
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,6 @@ pub fn NewSource(
pending_err: ?Syscall.Error = null,
close_handler: ?*const fn (?*anyopaque) void = null,
close_ctx: ?*anyopaque = null,
close_jsvalue: jsc.Strong.Optional = .empty,
cancel_handler: ?*const fn (?*anyopaque) void = null,
cancel_ctx: ?*anyopaque = null,
globalThis: *JSGlobalObject = undefined,
Expand Down Expand Up @@ -517,7 +516,6 @@ pub fn NewSource(

this.ref_count -= 1;
if (this.ref_count == 0) {
this.close_jsvalue.deinit();
deinit_fn(&this.context);
return 0;
}
Expand Down Expand Up @@ -694,15 +692,15 @@ pub fn NewSource(
this.globalThis = globalObject;

if (value.isUndefined()) {
this.close_jsvalue.deinit();
if (this.this_jsvalue != .zero) js.onCloseCallbackSetCached(this.this_jsvalue, globalObject, .js_undefined);
return;
}

if (!value.isCallable()) {
return globalObject.throwInvalidArgumentType("ReadableStreamSource", "onclose", "function");
}
const cb = value.withAsyncContextIfNeeded(globalObject);
this.close_jsvalue.set(globalObject, cb);
if (this.this_jsvalue != .zero) js.onCloseCallbackSetCached(this.this_jsvalue, globalObject, cb);
}

pub fn setOnDrainFromJS(this: *ReadableStreamSourceType, globalObject: *jsc.JSGlobalObject, value: jsc.JSValue) bun.JSError!void {
Expand All @@ -726,7 +724,10 @@ pub fn NewSource(

jsc.markBinding(@src());

return this.close_jsvalue.get() orelse .js_undefined;
if (this.this_jsvalue != .zero) {
if (js.onCloseCallbackGetCached(this.this_jsvalue)) |val| return val;
}
return .js_undefined;
}

pub fn getOnDrainFromJS(this: *ReadableStreamSourceType, globalObject: *jsc.JSGlobalObject) jsc.JSValue {
Expand Down Expand Up @@ -754,11 +755,12 @@ pub fn NewSource(
fn onClose(ptr: ?*anyopaque) void {
jsc.markBinding(@src());
var this = bun.cast(*ReadableStreamSourceType, ptr.?);
if (this.close_jsvalue.trySwap()) |cb| {
this.globalThis.queueMicrotask(cb, &.{});
if (this.this_jsvalue != .zero) {
if (js.onCloseCallbackGetCached(this.this_jsvalue)) |cb| {
if (!cb.isUndefined()) this.globalThis.queueMicrotask(cb, &.{});
js.onCloseCallbackSetCached(this.this_jsvalue, this.globalThis, .js_undefined);
}
}

this.close_jsvalue.deinit();
}

pub fn finalize(this: *ReadableStreamSourceType) void {
Expand Down
Loading