Repository navigation
webcore: pin subprocess stdout FileReader while its pipe poll is live #32743
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
Merged
Jarred-Sumner
merged 10 commits into
main
from
farm/43ee931d/spawn-stdout-filereader-gc-uaf
Jun 26, 2026
Merged
Changes from 1 commit
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
6c7ccf2
webcore: pin subprocess stdout FileReader while its pipe poll is live
robobun c3fadfc
[autofix.ci] apply automated fixes
autofix-ci[bot] 171024a
test: bound the detached helper loop and drop strict stderr assertion
robobun 3bc0f4b
[autofix.ci] apply automated fixes
autofix-ci[bot] e3358d3
from_pipe: gate the across-read ref on !is_done() instead of has_pend…
robobun e1b573c
test: add afterSyncGC and grandchildrenStarted diagnostics
robobun 9a9a006
test: use a plain sleep grandchild and kill it by pid
robobun d7c5b0b
test: clear BUN_FEATURE_FLAG_NO_ORPHANS on the fixture
robobun 26383ab
test: have the direct child await its grandchild's pid file
robobun 38df0f7
ci: retrigger
robobun File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
119 changes: 119 additions & 0 deletions
119
test/js/bun/spawn/spawn-stdout-filereader-gc-uaf.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| import { expect, test } from "bun:test"; | ||
| import { bunEnv, bunExe, isWindows, tempDir } from "harness"; | ||
| import { join } from "node:path"; | ||
|
|
||
| // Accessing `proc.stdout` on a piped subprocess moves the already-registered | ||
| // pipe poll from the subprocess PipeReader into a freshly allocated | ||
| // NewSource<FileReader>. The across-read ref (which upgrades the wrapper's | ||
| // JsRef to Strong and pins the native box) used to be taken only in | ||
| // FileReader::on_start, the first time JS actually pulls from the stream. | ||
| // Between from_pipe and that first pull the poll's owner points into a box | ||
| // whose only ref is the JS wrapper's own Weak back-reference, so if the | ||
| // subprocess and its cached stdout become unreachable before anyone pulls, | ||
| // GC can sweep the wrapper and free the box while the poll is still armed. | ||
| // The next readability/EOF event then dispatches into freed memory | ||
| // (FileReader::on_reader_done reached from PosixBufferedReader::read_socket). | ||
| // | ||
| // This test asserts the lifetime invariant directly rather than racing for | ||
| // the crash: while a subprocess pipe's write end is still held open (by a | ||
| // detached grandchild that inherits it), the FileInternalReadableStreamSource | ||
| // wrapper must survive GC even though nothing in JS references it. Once the | ||
| // grandchild exits and the pipe reaches EOF, on_reader_done releases the ref | ||
| // and the wrapper becomes collectable (no leak). | ||
| // | ||
| // Windows uses libuv for pipe I/O; the from_pipe path under test is POSIX. | ||
| test.skipIf(isWindows)( | ||
| "subprocess stdout FileReader is pinned while its pipe poll is live, then collectable after EOF", | ||
| async () => { | ||
| using dir = tempDir("fr-gc-uaf", {}); | ||
| const flag = join(String(dir), "go"); | ||
|
|
||
| const script = /* js */ ` | ||
| const { heapStats } = require("bun:jsc"); | ||
| const { writeFileSync } = require("node:fs"); | ||
| const ITERS = 4; | ||
| const flag = ${JSON.stringify(flag)}; | ||
|
|
||
| // The direct child spawns a detached shell that inherits stdout and | ||
| // waits for a flag file, keeping the pipe's write end open past the | ||
| // child's exit so the FileReader's poll is still armed while we GC. | ||
| const childScript = | ||
| "const { spawn } = require('child_process');" + | ||
| "spawn('sh', ['-c', 'while [ ! -e " + JSON.stringify(flag) + " ]; do sleep 0.02; done; echo x']," + | ||
| " { stdio: ['ignore', 'inherit', 'ignore'], detached: true }).unref();"; | ||
|
Check warning on line 43 in test/js/bun/spawn/spawn-stdout-filereader-gc-uaf.test.ts
|
||
|
robobun marked this conversation as resolved.
Resolved
|
||
|
|
||
| const count = () => | ||
| heapStats().objectTypeCounts.FileInternalReadableStreamSource ?? 0; | ||
|
|
||
| async function once() { | ||
| const proc = Bun.spawn({ | ||
| cmd: [process.execPath, "-e", childScript], | ||
| env: process.env, | ||
| stdout: "pipe", | ||
| stderr: "ignore", | ||
| stdin: "ignore", | ||
| }); | ||
| // Materialize the ReadableStream so the live poll is re-parented | ||
| // into a NewSource<FileReader>, but never pull from it. | ||
| void proc.stdout; | ||
| await proc.exited; | ||
| } | ||
|
|
||
| // Warm up once so per-class lazy structure allocation is absorbed | ||
| // into the baseline and not counted against ITERS. | ||
| await once(); | ||
| for (let i = 0; i < 10; i++) { Bun.gc(true); await Bun.sleep(1); } | ||
| const base = count(); | ||
|
|
||
| await Promise.all(Array.from({ length: ITERS }, once)); | ||
|
|
||
| // Direct children have exited; grandchildren still hold the write end. | ||
| for (let i = 0; i < 20; i++) { Bun.gc(true); await Bun.sleep(1); } | ||
| const duringLivePipe = count() - base; | ||
|
|
||
| // Release the grandchildren (including the warmup one). | ||
| writeFileSync(flag, ""); | ||
|
|
||
| let afterEof = -1; | ||
| for (let i = 0; i < 100; i++) { | ||
| Bun.gc(true); | ||
| await Bun.sleep(10); | ||
| afterEof = count() - base; | ||
| if (afterEof <= 0) break; | ||
| } | ||
|
|
||
| console.log(JSON.stringify({ iters: ITERS, duringLivePipe, afterEof })); | ||
| `; | ||
|
|
||
| await using proc = Bun.spawn({ | ||
| cmd: [bunExe(), "--smol", "-e", script], | ||
| env: bunEnv, | ||
| stdout: "pipe", | ||
| stderr: "pipe", | ||
| }); | ||
|
|
||
| const [stdout, stderr, exitCode] = await Promise.all([ | ||
| proc.stdout.text(), | ||
| proc.stderr.text(), | ||
| proc.exited, | ||
| ]); | ||
|
|
||
| const stderrFiltered = stderr | ||
| .split("\n") | ||
| .filter(l => l && !l.startsWith("WARNING: ASAN interferes")) | ||
| .join("\n"); | ||
| expect(stderrFiltered).toBe(""); | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
| const { iters, duringLivePipe, afterEof } = JSON.parse(stdout.trim()); | ||
| // Invariant: every FileReader whose pipe poll is still armed must be | ||
| // pinned by its own Strong ref. Before the fix they were swept here | ||
| // (duringLivePipe ~ 0), which is exactly the UAF precondition. | ||
| expect(duringLivePipe).toBeGreaterThanOrEqual(iters); | ||
| // Once the pipe reaches EOF the ref is released and the wrappers become | ||
| // collectable. One may survive via a conservatively-rooted final | ||
| // Subprocess (same caveat as spawn-ipc-gc.test.ts). | ||
| expect(afterEof).toBeLessThanOrEqual(1); | ||
| expect(exitCode).toBe(0); | ||
| }, | ||
| 60_000, | ||
| ); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.