From 29dfb7de06e299da62b3b580db0d5f1463875d2a Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Sat, 18 Apr 2026 02:50:06 -0700 Subject: [PATCH 1/6] io: don't null source before closeImpl in WindowsBufferedReader.deinit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit deinit() was setting `this.source = null` before calling closeImpl(false), but closeImpl reads `this.source` — so it became a no-op and the source (file/pipe/tty) was never detached or closed. For file sources this leaks the fd, the heap-allocated Source.File, and leaves any in-flight uv_fs_read uncanceled on the libuv threadpool. Restore the pre-#20198 ordering: call closeImpl first, then null the field (closeImpl already nulls it on the happy path; the trailing assignment covers the already-closed branch). --- src/io/PipeReader.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/io/PipeReader.zig b/src/io/PipeReader.zig index 96048a13f551..5f88a6e3b90b 100644 --- a/src/io/PipeReader.zig +++ b/src/io/PipeReader.zig @@ -980,11 +980,11 @@ pub const WindowsBufferedReader = struct { 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) { From 658ac624b33e9d48cf5141bc7770a7539ae8dcc3 Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Sat, 18 Apr 2026 13:41:01 -0700 Subject: [PATCH 2/6] install: only allocate stdio pipes when buffering on Windows The lifecycle script runner allocated zero-initialized uv.Pipe handles on Windows unconditionally, but only passed them to spawn (and thus uv_pipe_init) when output is buffered. In foreground/verbose/silent modes the uninitialized pipe sat in reader.source and was leaked by deinit. After the previous commit made deinit actually close the source, that leak became a uv_close() on a handle with type=0, which aborts inside libuv. Gate the allocation on the same condition that selects the .buffer stdio arm. --- src/install/lifecycle_script_runner.zig | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/install/lifecycle_script_runner.zig b/src/install/lifecycle_script_runner.zig index 5778eb3c0065..ad6b3e90ab7a 100644 --- a/src/install/lifecycle_script_runner.zig +++ b/src/install/lifecycle_script_runner.zig @@ -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)) }; } @@ -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 From bd69954ac61aa2d383d3410f973328577471b541 Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Sun, 19 Apr 2026 00:28:47 -0700 Subject: [PATCH 3/6] io: honor close_handle for .file sources in WindowsBufferedReader.closeImpl MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Posix reader checks `flags.close_handle` before closing the fd; the Windows path didn't — `closeImpl` for `.file` always called `file.detach()` -> `startClose()` -> `uv_fs_close(fd)`, regardless of ownership. FileResponseStream sets `close_handle = false` (it owns the fd via `auto_close` and closes it itself with `Closer.close`). After the deinit-reorder commit made `closeImpl` actually fire from `deinit`, the eof_task path (where the reader is paused with a live `.file` source at deinit time) double-closed: `reader.deinit()` → `uv_fs_close(fd)`, then `Closer.close(fd)` again. Both queue to the threadpool synchronously; with several responses in a row the loser runs after the next response has already reused the fd, closing the wrong file → cascading corruption. Thread `flags.close_handle` through to a new `Source.File.close_fd` flag; when false, `startClose()` frees the struct without `uv_fs_close`. --- src/io/PipeReader.zig | 2 ++ src/io/source.zig | 9 +++++++++ 2 files changed, 11 insertions(+) diff --git a/src/io/PipeReader.zig b/src/io/PipeReader.zig index 5f88a6e3b90b..b75e64dc0f54 100644 --- a/src/io/PipeReader.zig +++ b/src/io/PipeReader.zig @@ -1197,6 +1197,8 @@ pub const WindowsBufferedReader = struct { 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(); }, .pipe => |pipe| { diff --git a/src/io/source.zig b/src/io/source.zig index 85af95ec627a..ab384d0ac204 100644 --- a/src/io/source.zig +++ b/src/io/source.zig @@ -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, detach()/startClose() free 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); @@ -117,6 +121,11 @@ pub const Source = union(enum) { fn startClose(this: *File) void { bun.assert(this.state == .deinitialized); + if (!this.close_fd) { + // Caller owns the fd — free this struct without closing. + bun.default_allocator.destroy(this); + return; + } this.state = .closing; _ = uv.uv_fs_close(uv.Loop.get(), &this.fs, this.file, onCloseComplete); } From 140cce22ea46cd075cbb4e4f16d3a6b7cc9f3416 Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Sun, 19 Apr 2026 00:29:01 -0700 Subject: [PATCH 4/6] Reapply "webcore: fix ReadableStreamSource Strong cycle + Windows fromPipe ref (#29472)" This reverts commit bf2e2cecf27e800962b1e7f03d66278f9d5d2e79. --- src/runtime/webcore/FileReader.zig | 10 ++++++++++ src/runtime/webcore/ReadableStream.zig | 20 +++++++++++--------- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/src/runtime/webcore/FileReader.zig b/src/runtime/webcore/FileReader.zig index 0d26e3f3d2e2..9d53946923d9 100644 --- a/src/runtime/webcore/FileReader.zig +++ b/src/runtime/webcore/FileReader.zig @@ -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) { @@ -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) { diff --git a/src/runtime/webcore/ReadableStream.zig b/src/runtime/webcore/ReadableStream.zig index c084d9ebae17..cf29349dd973 100644 --- a/src/runtime/webcore/ReadableStream.zig +++ b/src/runtime/webcore/ReadableStream.zig @@ -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, @@ -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; } @@ -694,7 +692,7 @@ 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; } @@ -702,7 +700,7 @@ pub fn NewSource( 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 { @@ -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 { @@ -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 { From 43f6173a552b19a9b93ffd0d2677cba655deb9b1 Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Sun, 19 Apr 2026 00:38:26 -0700 Subject: [PATCH 5/6] io: openFile: use struct literal so close_fd defaults true; drop UAF assert MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review fixes for the close_handle commit: - openFile() initialized via std.mem.zeroes(Source.File), which zeroes close_fd (intended default true) → any caller that doesn't go through WindowsBufferedReader.closeImpl (e.g. PipeWriter with owns_fd=true) would skip uv_fs_close and leak the fd. Use a struct literal so the declared defaults apply. - onFileRead asserted `file.state == .closing` after `file.complete()` when detached, but with close_fd=false complete()→startClose() destroys the struct synchronously. Drop the assert; nothing else on that branch dereferences `file`. --- src/io/PipeReader.zig | 7 ++++--- src/io/source.zig | 8 ++++++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/io/PipeReader.zig b/src/io/PipeReader.zig index b75e64dc0f54..6406d5b83936 100644 --- a/src/io/PipeReader.zig +++ b/src/io/PipeReader.zig @@ -1053,12 +1053,13 @@ pub const WindowsBufferedReader = struct { // 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) and close_fd == false, + // complete() -> startClose() destroys `file` synchronously, so it 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; } diff --git a/src/io/source.zig b/src/io/source.zig index ab384d0ac204..683b2a292d4b 100644 --- a/src/io/source.zig +++ b/src/io/source.zig @@ -294,8 +294,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; } From fab3241eef3fef1443afd7568d6a97e5dc392a2e Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Sun, 19 Apr 2026 00:39:45 -0700 Subject: [PATCH 6/6] io: rename Source.File.startClose -> finalize, document lifetime MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit startClose() was the wrong name once it could destroy `this` synchronously when close_fd=false — callers expected `this` to remain valid until onCloseComplete. Rename to finalize() with an explicit "do not touch `this` after this returns" contract, and document on detach()/complete() that they may free. --- src/io/PipeReader.zig | 6 +++--- src/io/source.zig | 33 +++++++++++++++++++-------------- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/src/io/PipeReader.zig b/src/io/PipeReader.zig index 6406d5b83936..2568a21a822d 100644 --- a/src/io/PipeReader.zig +++ b/src/io/PipeReader.zig @@ -1054,9 +1054,9 @@ pub const WindowsBufferedReader = struct { const parent_ptr = fs.data; // ALWAYS complete the read first (cleans up fs_t, updates state). - // NOTE: when detached (parent_ptr == null) and close_fd == false, - // complete() -> startClose() destroys `file` synchronously, so it must - // not be dereferenced past this point on the detached branch. + // 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 (parent_ptr == null) { diff --git a/src/io/source.zig b/src/io/source.zig index 683b2a292d4b..f2cc85c836f6 100644 --- a/src/io/source.zig +++ b/src/io/source.zig @@ -53,8 +53,8 @@ pub const Source = union(enum) { /// When true, file will close itself when the current operation completes. close_after_operation: bool = false, - /// When false, detach()/startClose() free this struct without calling - /// uv_fs_close — the caller owns the fd. Mirrors BufferedReader.flags.close_handle. + /// 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. @@ -88,9 +88,9 @@ 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; @@ -98,12 +98,15 @@ pub const Source = union(enum) { 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) { @@ -115,19 +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); - if (!this.close_fd) { + if (this.close_fd) { + this.state = .closing; + _ = uv.uv_fs_close(uv.Loop.get(), &this.fs, this.file, onCloseComplete); + } else { // Caller owns the fd — free this struct without closing. bun.default_allocator.destroy(this); - return; } - this.state = .closing; - _ = uv.uv_fs_close(uv.Loop.get(), &this.fs, this.file, onCloseComplete); } fn onCloseComplete(fs: *uv.fs_t) callconv(.c) void {