Repository navigation
io: fix WindowsBufferedReader.deinit source handling + ReadableStreamSource Strong cycle #29440
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
29dfb7d
658ac62
bd69954
140cce2
43f6173
fab3241
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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) { | ||
|
|
@@ -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; | ||
| } | ||
|
|
||
|
|
@@ -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
|
||
|
Comment on lines
+1201
to
1203
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟣 🟣 Pre-existing (not touched by this PR): the parallel writer path in Extended reasoning...What the bug is This PR adds // 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
Why existing code doesn't free it — step-by-step proof
In neither case does any path reach Why this is pre-existing and unrelated to this PR
Impact A small ( 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();
}
Comment on lines
1198
to
1203
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟣 🟣 Pre-existing (not introduced here, just adjacent to fix #3): the Extended reasoning...What the bug is This PR's fix #3 threads The specific code path
When that pipe reaches 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: Step-by-step proof (EOF path, pre-PR and post-PR identical)
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 How to fix Apply the same gating to the |
||
| }, | ||
| .pipe => |pipe| { | ||
| pipe.data = pipe; | ||
|
|
||
There was a problem hiding this comment.
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_bufferbeforecloseImpl(false)runsfile.detach()/uv_cancel(), leaving a theoretical window where an in-flightuv_fs_readthread-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 earlierthis.source = nullassignment). All current callers that use file sources either assertremaining_fds == 0before deinit or callclose()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.filesources callsfile.detach()→file.stop()→uv_cancel(). The libuvuv_fs_readAPI uses a thread-pool worker that callsReadFiledirectly intofile.iov.base, which points into the already-freed_buffer.allocatedSlice(). If the thread-pool worker is actively writing whendeinit()frees the buffer, this is a write to freed memory (heap corruption / UAF).The specific code path that triggers it
For a
.fileor.sync_filesource with an in-flightuv_fs_read:deinit()this.buffer().deinit()→ frees_bufferheap allocationcloseImpl(false)→file.detach()→file.stop()→uv_cancel()uv_cancelreturnsUV_EBUSY(I/O already submitted to kernel), the OSReadFilecompletes and writes into the freed memory regiononFileReadfires, seesparent_ptr == null(detach setfs.data = null), and returns safely — but the buffer corruption already occurred at step 4Why existing code doesn't prevent it
uv_cancelis not guaranteed to succeed for I/O that is already in-flight with the kernel. Afteruv_cancelreturns, the thread-pool worker may still be in the middle ofReadFile, writing into the freed buffer memory.Why this is pre-existing and not introduced by this PR
Before this PR,
this.source = nullwas assigned BEFORE thecloseImplcall, makingcloseImpla complete no-op (it checksif (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,onFileReadwould fire with a non-nullparent_ptrpointing to potentially freed/reused struct memory — a UAF of the struct itself. The PR's fix makescloseImplactually run and addsfile.detach()which setsfs.data = nullsoonFileReadreturns early without touchingthis, 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
.pipesources on Windows (not.file) whenbuffer_outputis true, so theuv_fs_readpath is never taken. Additionally,resetPolls()assertsremaining_fds == 0before callingdeinit(), guaranteeing all reads have completed. Other callers either assert the source is closed/null beforedeinit, or callclose()first which properly defers cleanup via thedefer_done_callbackmechanism.How to fix it
Move
buffer().deinit()to aftercloseImpl()completes — or defer the_bufferfree to theonFileReadcallback after cancel completes (similar to howdefer_done_callbackdefers thedone()call). A simpler short-term fix is to document the ordering invariant: callers must ensure no in-flight reads exist before callingdeinit(), which is already enforced by the assertions in current callers.