Skip to content

spawn: give child a pipe for empty-buffer stdin, not the null device - #35286

Closed
robobun wants to merge 7 commits into
mainfrom
farm/b73669a9/spawn-empty-buffer-stdin-pipe
Closed

robobun wants to merge 7 commits into
mainfrom
farm/b73669a9/spawn-empty-buffer-stdin-pipe

Conversation

@robobun

@robobun robobun commented Jul 23, 2026 •

Copy link
Copy Markdown
Collaborator

Bun.spawn / Bun.spawnSync with an empty stdin buffer (and child_process.spawnSync with input: Buffer.alloc(0)) hand the child the null device (/dev/null on POSIX, NUL on Windows) instead of a pipe. A non-empty buffer uses a pipe; Node uses a pipe for both.

Repro

// probe.c
HANDLE h = GetStdHandle(STD_INPUT_HANDLE);
printf("GetFileType(stdin) = %lu\n", GetFileType(h));
$ bun -e 'Bun.spawnSync({cmd:["./probe.exe"], stdin: Buffer.alloc(0), stdout:"pipe"}).stdout.toString()'
GetFileType(stdin) = 2   // FILE_TYPE_CHAR (NUL)

$ bun -e 'Bun.spawnSync({cmd:["./probe.exe"], stdin: Buffer.from("x"), stdout:"pipe"}).stdout.toString()'
GetFileType(stdin) = 3   // FILE_TYPE_PIPE

$ node -e 'require("child_process").spawnSync("./probe.exe",[],{input:Buffer.alloc(0)}).stdout.toString()'
GetFileType(stdin) = 3   // FILE_TYPE_PIPE

Same on POSIX via fstat(0).isCharacterDevice(). The child's stdin fd type flips on whether the buffer happened to be empty, which trips tools that branch on S_ISFIFO/S_ISSOCK, and in a Windows AppContainer opening NUL fails with EPERM.

Cause

Stdio::extract short-circuits an empty ArrayBuffer at any slot to Stdio::Ignore:

if array_buffer.byte_slice().is_empty() {
    *out_stdio = Stdio::Ignore;   // /dev/null or NUL
    return Ok(());
}

This was #9557's "don't throw for empty ArrayBuffer", but Ignore gives a character device; the non-empty path gives a pipe.

Letting the empty buffer fall through to Stdio::ArrayBuffer alone would deadlock on macOS/Windows: StaticPipeWriter with a zero-byte source registers for write readiness (POSIX) or returns from write() (Windows) and never closes the pipe, so the child's read(0) blocks forever.

Fix

  • Stdio::extract: only downgrade an empty ArrayBuffer to Ignore at i != 0; at stdin let it become Stdio::ArrayBuffer like a non-empty one. stdout/stderr/extras are unchanged (no reader is wired for Stdio::ArrayBuffer at those slots).
  • StaticPipeWriter::start: after a successful start, if the source is empty, drive the on_write(0, Drained) path immediately so the write end closes and the child reads EOF. This is the same tail-call contract PosixPipeWriter::on_poll already documents ("don't touch self after the callback").

What the child sees on fd 0 for stdin: Buffer.alloc(0) after this change matches the non-empty case on each platform: a pipe on macOS/Windows, a memfd on Linux (can_use_memfd still converts the ArrayBuffer slot). subprocess.stdin stays undefined for buffer stdin (it is Writable::Buffer regardless of size).

Blob stdin (stdin: new Blob([])) still becomes Ignore; changing extract_blob would pull in the shell's Cmd::extract_blob callers. Only the ArrayBuffer path changes, which is what child_process.spawnSync input: uses.

Relation to #34477

#34477 removes the Stdio::Pipe -> Ignore remap for a bare stdin: "pipe" under spawnSync. That is the other half of the same symptom (the handoff that prompted this PR reported both); this PR addresses the empty-buffer path, which #34477 does not touch. The two changes are independent and compose.

Verification

New tests in test/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts cover Bun.spawnSync, Bun.spawn, and child_process.spawnSync with ArrayBuffer(0) / Uint8Array(0) / Buffer.alloc(0), asserting !isCharacterDevice() and 0 bytes to EOF.

USE_SYSTEM_BUN=1 bun test test/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts   # 7 fail
bun bd          test test/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts        # 10 pass

Same result on Windows x64. spawnSync.test.ts, the stdin subset of spawn.test.ts, and the child_process.spawnSync* node parallel tests pass on both platforms; rust:check-all is green across the target matrix.


[review] gate passed · iteration 1 · 4 files touched

fails on main (without fix)
ASAN without fix: 7 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts
bun test v1.4.0 (97ee042cf)

test/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts:
(pass) spawn with empty > ArrayBuffer for stdin [1436.51ms]
(pass) spawn with empty > Uint8Array for stdin [1420.17ms]
(pass) spawn with empty > Blob for stdin [1427.18ms]
45 |         stdout: "pipe",
46 |         stderr: "pipe",
47 |         env: bunEnv,
48 |       });
49 |       expect(r.stderr.toString()).toBe("");
50 |       expect(JSON.parse(r.stdout.toString())).toEqual({ chr: false, n: 0 });
                                                   ^
error: expect(received).toEqual(expected)

  {
-   "chr": false,
+   "chr": true,
    "n": 0,
  }

- Expected  - 1
+ Received  + 1

      at <anonymous> (/workspace/bun/test/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts:50:47)
(fail) empty buffer stdin is not the null device > Bun.spawnSync stdin: ArrayBuffer [1385.44ms]
59 |         stderr: "pipe",
60 |         env: bunEnv,
61 |       });
62 |       const [stdout, stderr, exitCode] = await Prom
... (truncated)

release without fix: all passed
bun test v1.4.0-canary.1 (6d334110a)

test/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts:
(pass) spawn with empty > ArrayBuffer for stdin [26.67ms]
(pass) spawn with empty > Uint8Array for stdin [25.82ms]
(pass) spawn with empty > Blob for stdin [26.05ms]
(pass) empty buffer stdin is not the null device > Bun.spawnSync stdin: ArrayBuffer [24.79ms]
(pass) empty buffer stdin is not the null device > Bun.spawn stdin: ArrayBuffer [25.19ms]
(pass) empty buffer stdin is not the null device > Bun.spawnSync stdin: Uint8Array [24.93ms]
(pass) empty buffer stdin is not the null device > Bun.spawn stdin: Uint8Array [24.73ms]
(pass) empty buffer stdin is not the null device > Bun.spawnSync stdin: Buffer [24.53ms]
(pass) empty buffer stdin is not the null device > Bun.spawn stdin: Buffer [24.37ms]
(pass) empty buffer stdin is not the null device > child_process.spawnSync input: Buffer.alloc(0) [25.39ms]

 10 pass
 0 fail
 33 expect() calls
Ran 10 tests across 1 file. [399.00ms]
__F:0:S:0
passes on PR (with fix)
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts
bun test v1.4.0 (97ee042cf)

test/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts:
(pass) spawn with empty > ArrayBuffer for stdin [1424.05ms]
(pass) spawn with empty > Uint8Array for stdin [1420.76ms]
(pass) spawn with empty > Blob for stdin [1397.43ms]
(pass) empty buffer stdin is not the null device > Bun.spawnSync stdin: ArrayBuffer [1367.34ms]
(pass) empty buffer stdin is not the null device > Bun.spawn stdin: ArrayBuffer [1369.77ms]
(pass) empty buffer stdin is not the null device > Bun.spawnSync stdin: Uint8Array [1355.79ms]
(pass) empty buffer stdin is not the null device > Bun.spawn stdin: Uint8Array [1361.83ms]
(pass) empty buffer stdin is not the null device > Bun.spawnSync stdin: Buffer [1369.23ms]
(pass) empty buffer stdin is not the null device > Bun.spawn stdin: Buffer [1382.23ms]
(pass) empty buffer stdin is not the null device > child_process.spawnSync input: Buffer.alloc(0) [1424.45ms]

 10 pass
 0 fail
 33 expect() calls
Ran 10 tests across 1 file. [16.01s]
__F:0:S:0

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 644ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/5] gen generated_host_exports.rs
generated_host_exports.rs: 91 exports (host=3, lazy=10, generic=78, rust=0); 237 extern-C blocks audited
[build] done
bun test v1.4.0-canary.1 (97ee042cf)

test/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts:
(pass) spawn with empty > ArrayBuffer for stdin [27.13ms]
(pass) spawn with empty > Uint8Array for stdin [25.66ms]
(pass) spawn with empty > Blob for stdin [25.87ms]
(pass) empty buffer stdin is not the null device > Bun.spawnSync stdin: ArrayBuffer [25.56ms]
(pass) empty buffer stdin is not the null device > Bun.spawn stdin: ArrayBuffer [25.51ms]
(pass) empty buffer stdin is not the null device > Bun.spawnSync stdin: Uint8Array [25.23ms]
(pass) empty buffer stdin is not the null device > Bun.spawn stdin: Uint8Array [24.65ms]
(pass) empty buffer stdin is not the null device > Bun.spawnSync stdin: Buffer [25.00ms]
(pass) empty buffer stdin is not the null device > Bun.spawn stdin: Buffer [25.10ms]
(pass) empty buffer stdin is not the null device > child_process.s
... (truncated)
diff hotspot
src/runtime/api/bun/spawn/stdio.rs                 | 17 ++++++--
 src/runtime/shell/states/Cmd.rs                    |  4 +-
 src/spawn/static_pipe_writer.rs                    | 28 ++++++++++++
 .../spawn/spawn-empty-arrayBufferOrBlob.test.ts    | 51 ++++++++++++++++++++++
 4 files changed, 96 insertions(+), 4 deletions(-)

gate history · 2 passed · 0 rejected · iteration 1

evidence per changed file
file                                                     reads  edits  tests
src/runtime/api/bun/spawn/stdio.rs                           2      3      0
src/runtime/shell/states/Cmd.rs                              1      1      0
src/spawn/static_pipe_writer.rs                              2      2      0
test/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts      3      4      0

@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Changes

Empty stdin ArrayBuffer values now use a real pipe, and empty pipe buffers immediately follow the drained path on Windows and POSIX. Tests verify zero bytes, non-device stdin, successful exits, and matching Node behavior.

Empty stdin pipe handling

Layer / File(s) Summary
Preserve and drain empty stdin
src/runtime/api/bun/spawn/stdio.rs, src/spawn/static_pipe_writer.rs, src/runtime/shell/states/Cmd.rs
Empty stdin ArrayBuffer input remains a pipe, and empty buffers trigger immediate drained handling on Windows and POSIX. Comments document the separate empty-blob and shell-redirection behavior.
Validate empty stdin behavior
test/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts
Tests verify empty ArrayBuffer-like inputs produce zero bytes through non-device stdin and exit successfully across Bun and Node spawn APIs.

Possibly related PRs

Suggested reviewers: jarred-sumner

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: empty-buffer stdin now uses a pipe instead of the null device.
Description check ✅ Passed The description explains the problem, fix, and verification, covering the template's required intent and test evidence.

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts`:
- Around line 40-51: Run the synchronous spawn tests sequentially by replacing
test.concurrent with test in both the Bun.spawnSync case at
test/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts lines 40-51 and the
child_process.spawnSync case at lines 69-74; make no other changes.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: b89cbaac-f9f4-4854-a6a6-d79d69cafce8

📥 Commits

Reviewing files that changed from the base of the PR and between 892b1da and bb7c2cc.

📒 Files selected for processing (3)
  • src/runtime/api/bun/spawn/stdio.rs
  • src/spawn/static_pipe_writer.rs
  • test/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts

Comment thread src/spawn/static_pipe_writer.rs Resolved
robobun added 3 commits July 23, 2026 14:36
on_write on Windows does not release start()'s +1 (the cfg(not(windows))
release_start_ref block), and on_close_io replaces stdin with Ignore so
take_pending_start_writer never matches afterwards. Inline the release
(started=false; writer.close; deref) so the empty path is balanced.

Also drop test.concurrent on the spawnSync cases (sync body).

@coderabbitai coderabbitai Bot left a comment

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/runtime/api/bun/spawn/stdio.rs (1)

555-560: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use platform-neutral wording for ArrayBuffer stdin.

Line 558 says the child “gets a pipe,” but Stdio::ArrayBuffer is explicitly eligible for use_memfd() on Linux, so this path can produce a memfd rather than a pipe. Describe this as pipe-like/data-backed stdin or document the platform-specific behavior.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/runtime/api/bun/spawn/stdio.rs` around lines 555 - 560, Update the
comment near Stdio::ArrayBuffer to avoid claiming stdin always uses a pipe;
describe it as pipe-like or data-backed stdin, or explicitly note that Linux may
use a memfd via use_memfd(), while preserving the existing behavior and
explanation for other slots.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/runtime/api/bun/spawn/stdio.rs`:
- Around line 555-560: Update the comment near Stdio::ArrayBuffer to avoid
claiming stdin always uses a pipe; describe it as pipe-like or data-backed
stdin, or explicitly note that Linux may use a memfd via use_memfd(), while
preserving the existing behavior and explanation for other slots.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: a8bd7e1e-0f94-4429-b645-693677242c6c

📥 Commits

Reviewing files that changed from the base of the PR and between bb7c2cc and 7418098.

📒 Files selected for processing (4)
  • src/runtime/api/bun/spawn/stdio.rs
  • src/runtime/shell/states/Cmd.rs
  • src/spawn/static_pipe_writer.rs
  • test/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts

@robobun

robobun commented Jul 23, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 11:09 AM PT - Jul 23rd, 2026

✅ @robobun, your commit 97ee042cfd1822c4b2ef15c82ec96af5bb0e94cc passed in Build #78733! 🎉


🧪   To try this PR locally:

bunx bun-pr 35286

That installs a local version of the PR into your bun-35286 executable, so you can run:

bun-35286 --bun

Comment thread src/runtime/api/bun/spawn/stdio.rs Resolved

@coderabbitai coderabbitai Bot left a comment

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/runtime/api/bun/spawn/stdio.rs (1)

645-650: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Correct the empty-Blob scope in the comment.

The preceding guard rejects Blob values at indices 1 and 2, so this branch cannot treat empty Blobs as Ignore for all fds 0–2. Limit the wording to stdin and extra slots.

Proposed wording
-        // (/dev/null at fds 0-2, left closed at extra slots). This diverges
+        // (stdin maps to /dev/null; extra slots remain closed). This diverges
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/runtime/api/bun/spawn/stdio.rs` around lines 645 - 650, Update the
comment above the empty-Blob handling in extract_blob to state that empty Blobs
are treated as “ignore” for stdin and extra slots only, excluding fds 1 and 2
because the preceding guard rejects them.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/runtime/api/bun/spawn/stdio.rs`:
- Around line 645-650: Update the comment above the empty-Blob handling in
extract_blob to state that empty Blobs are treated as “ignore” for stdin and
extra slots only, excluding fds 1 and 2 because the preceding guard rejects
them.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 3856b1af-eade-4f06-aa3f-e6b7c3d0e02b

📥 Commits

Reviewing files that changed from the base of the PR and between 7418098 and 97ee042.

📒 Files selected for processing (1)
  • src/runtime/api/bun/spawn/stdio.rs

@claude claude Bot left a comment

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.

The Windows refcount fix in 0698638 looks correct — I re-traced BaseWindowsPipeWriter::close() and the async on_pipe_close callback only frees the standalone Box<uv::Pipe>, so the trailing deref freeing StaticPipeWriter inside start() doesn't race it. All my prior findings are addressed. Deferring to a human for a final look since this adds a new "start() may synchronously free self" path on both platforms in intrusive-refcount code.

What was reviewed:

  • Windows empty branch: started=false → writer.close() (source taken, uv_close scheduled on the detached Pipe box, on_close_io swaps stdin→Ignore and derefs 2→1) → trailing deref 1→0; take_pending_start_writer can't re-release since stdin is Ignore.
  • POSIX empty branch: on_write(0, Drained) hits release_start_ref, same 2→1→0 sequence; poll is unregistered by writer.close() before self is freed.
  • Caller at js_bun_spawn_bindings.rs:1754 doesn't touch buffer after start() returns Ok; the later watch() at :1927 no longer matches (Writable::Ignore).
  • Shell (Cmd.rs) can't reach the new empty-writer path — its ArrayBuffer stdin arm still uses Stdio::Ignore and extract_blob is unchanged.
Extended reasoning...

Overview

Changes Stdio::extract so an empty ArrayBuffer at stdin falls through to Stdio::ArrayBuffer (pipe/memfd) instead of Stdio::Ignore (null device), matching Node's spawnSync({input: Buffer.alloc(0)}). To make that not deadlock, StaticPipeWriter::start() gains an if empty branch on both Windows and POSIX that closes the write end immediately so the child reads EOF. Comment-only updates in Cmd.rs and extract_blob document the intentional divergence for Blob/shell paths. New tests cover Bun.spawn/spawnSync/child_process.spawnSync × three empty-buffer types.

Security risks

None. No parsing of untrusted input, no auth/crypto/permissions.

Level of scrutiny

High — this is native intrusive-refcount code with platform-gated branches, the exact class REVIEW.md flags as most-blocked. My first pass found a Windows refcount leak; the fix (0698638) mirrors the POSIX release_start_ref sequence and I've re-verified the balance by reading through BaseWindowsPipeWriter::close() in PipeWriter.rs: the async on_pipe_close callback frees only the detached Box<uv::Pipe> (via heap::take(handle)), never the StaticPipeWriter, so freeing the writer at refcount 0 inside start() is safe. Drop for StaticPipeWriter runs writer.end() with source = None (no-op).

Other factors

  • Tests fail on main / pass with fix; ASan clean per PR evidence. robobun reports Windows x64 100-iteration RSS-flat verification.
  • All three prior review threads (Windows leak, stale Cmd.rs comment, test.concurrent on sync tests) are resolved in the current head.
  • The new contract that start() can synchronously free self and swap subprocess.stdin to Ignore is a lifetime change worth a human sanity check, even though I couldn't find a path where the caller touches the writer afterward.
  • Linux takes the memfd path (can_use_memfd matches Stdio::ArrayBuffer), so the new StaticPipeWriter empty branch is exercised only on macOS (POSIX arm) and Windows.

@robobun

robobun commented Jul 23, 2026

Copy link
Copy Markdown
Collaborator Author

CI status: the new test (spawn-empty-arrayBufferOrBlob.test.ts) passes on every lane across both builds (78729 and 78733). The remaining failures are unrelated and all passed on retry:

  • build 78729: worker-transfer-terminate-stress (JSC ExceptionScope assertion, reported to main-break triage) + 4 retry-green flakes (proxy, upgrade, fastutf8stream, express).
  • build 78733: 6 retry-green flakes (napi, child_process stdout-backpressure timeout, fetch-backpressure, spawn.test.ts kill/unref stress on win-aarch64, issue-20144, v8).

None of the flaky tests touch the Stdio::extract / StaticPipeWriter empty-source path this PR changes. Ready for review.

Jarred-Sumner pushed a commit that referenced this pull request Jul 24, 2026
…n write completes (#35297)

On Windows, `Bun.spawn`/`Bun.spawnSync` with a non-empty
`ArrayBuffer`/`Blob` `stdin` leaked one `StaticPipeWriter` allocation
per spawn.

## Cause

`StaticPipeWriter::start()` takes a `+1` and sets `started = true`.
#30875 added a `release_start_ref` block to `on_write()` that clears
`started` and derefs once the buffer drains, but gated it behind
`#[cfg(not(windows))]`:


https://github.com/oven-sh/bun/blob/892b1dabc6/src/spawn/static_pipe_writer.rs#L228-L241

On Windows, when the `uv_write` completes before the child exits (the
common ordering for a small buffer):

```
on_write_complete(status=0)
  -> Parent::on_write(Pending)             (release_start_ref gated out)
     -> writer.close()
        -> BaseWindowsPipeWriter::close -> on_close_source
           -> StaticPipeWriter::on_close -> Subprocess::on_close_io(Stdin)
              stdin <- Writable::Ignore; buffer.deref()   (create()'s +1)
  scopeguard deref                                         (write()'s +1)
```

Net: `started` is still `true` but `stdin` is `Writable::Ignore`, so the
other release site, `take_pending_start_writer` (called from
`on_process_exit` / `close_io`), matches nothing and start()'s `+1` is
stranded. The error arm of `on_write_complete` (e.g. `ERROR_BROKEN_PIPE`
when the child closes stdin without reading) reaches `on_close` via
`close()` without ever calling `Parent::on_write`, so start()'s `+1` is
stranded there the same way.

`ShellSubprocess` has the same leak for `cmd < ${buf}` stdin since its
`on_process_exit`/`close_io` never look at `started` at all and depend
entirely on `on_write`'s release.

## Fix

- `StaticPipeWriter::on_write`: drop the `cfg(not(windows))` gates so
`release_start_ref` runs on every platform. `WindowsBufferedWriter`
never passes `EndOfFile`, so the existing `status != EndOfFile` guard is
a no-op there and is left for the POSIX path
(`PosixBufferedWriter::_on_write` still touches `self` after the
callback on `EndOfFile`).
- `StaticPipeWriter::on_close` (Windows only): claim `started` and deref
after `on_close_io` for paths that reach `close()` without going through
`on_write` (the `on_write_complete` error arm). `write()`'s +1, held by
that callback's scopeguard, keeps `self` live past the release. This is
gated to Windows because on POSIX `drain_buffered_data` may call
`on_error()` -> `close()` -> `on_close` and then `on_write()` on the
same object with no extra ref held; #34697 changes that ordering and the
gate can go once it lands.
- `Subprocess::take_pending_start_writer`: clear `started` when it
claims the pointer. The three release sites are then mutually exclusive
via `started`, covering the ordering where `on_process_exit` closes the
pipe while a `uv_write` whose I/O already completed is still queued
(libuv delivers that callback with its real status after `uv_close`, not
`ECANCELED`).
- `WindowsBufferedWriter::on_write_complete`: `saturating_sub` for
`has_pending_data` so the late-success-after-close ordering does not
underflow in debug builds.

`SecurityScanSubprocess` already derefs and writes `started = false`
immediately after `start()`, so both new release sites see `started =
false`; no change in its refcount balance.

## Verification

Verified on Windows x64 by instrumenting `Drop` with a live counter and
spawning 400 children per mode: unfixed leaves 400 live writers after
each of the drain (64 B into `sort`) and reject (256 KB into `cmd /c
exit`) workloads; fixed returns to 0 on both, in release and debug
builds.

Also verified on Windows x64: `spawn.test.ts -t 'stdin|Uint8Array|Blob'`
(45/45), `spawnSync.test.ts` (6/6), `file-io.test.ts` (26/26),
`child_process.test.ts` (41/41), and on Linux: `bunshell.test.ts`
(414/414), `bun-security-scanner-workspaces.test.ts` (3/3).
`rust:check-all` is green across all 10 targets.

Found while working on #35286, which scopes its change to the
empty-buffer path and does not overlap.
@github-actions

Copy link
Copy Markdown
Contributor

Closing this PR because it has been inactive for more than 90 days.

@github-actions github-actions Bot closed this Oct 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant