Skip to content

fix(process): mark inherited descriptors close-on-exec at startup like Node - #12

Merged
steipete merged 1 commit into
mainfrom
claude/posix-stdio-cloexec
Sep 27, 2026
Merged

steipete merged 1 commit into
mainfrom
claude/posix-stdio-cloexec

Conversation

@steipete

Copy link
Copy Markdown

Node marks every inherited file descriptor close-on-exec when the process starts: InitializeOncePerProcessInternal (nodejs/node v24.x src/node.cc L846-850) calls libuv's uv_disable_stdio_inheritance() (deps/uv/src/unix/core.c), and every exec/spawn path then opts descriptors back in explicitly. This fork already had the opt-back-in half everywhere (same-fd dup2 actions in bun-spawn.cpp, addinherit_np on macOS, the --watch reload hook, process.execve) and already called uv_disable_stdio_inheritance() on Windows, but on POSIX it only marked fds >= 4 on Linux and nothing on macOS/FreeBSD.

The gap is visible whenever native code spawns without explicit stdio actions. OpenClaw hit it with Gateway computer control on Bun: the CUA N-API driver posix_spawnps a desktop app from a helper whose stdio is the Gateway's protocol channel. On Bun the app inherited those sockets, so after the helper exited cleanly the Gateway never saw EOF until its 30 s cancel timer killed the orphaned app; on Node the app's fds 0-2 are closed at exec.

Change

  • bun_initialize_process() marks inherited descriptors close-on-exec after the existing /dev/null fixups on all POSIX platforms, stdio and IPC included: close_range(CLOSE_RANGE_CLOEXEC) where available, otherwise libuv's exact traversal. This replaces the Linux-only close_range(4, …) special case, whose --watch concern is already handled by on_before_reload_process_posix() re-enabling stdio and NODE_CHANNEL_FD.
  • Raw exec sites that relied on implicit inheritance now opt in explicitly: the macOS CLI sync helper (addinherit_np for 0-2), the Android fork/execvp fallback (child-side fcntl), and the crash reporter's stderr.
  • Audited and unchanged because they already pass explicit descriptors: common spawn file actions, process.execve, the reload hook, webview, bun upgrade, and the FFI SDK lookup.

Evidence

Linux x64 release builds (--profile=release --lto=off) of 9e3414b3 with and without this commit, same Blacksmith Testbox:

/proc/self/fdinfo/{0,1,2} flags OpenClaw Gateway computer execution close after launching an app
CI pin 1.4.3-canary.1+ddfce5d01 00 / 01 / 01 30037 ms
9e3414b3 baseline 00 / 01 / 01 30042 ms
9e3414b3 + this commit 02000000 / 02000001 / 02000001 132 ms
Node v24.19.0 (reference) 02000000 / 02000001 / 02000001 fast (no stall)

The OpenClaw live proof (managed XFCE desktop, no node on PATH or at fallback paths, zero paired nodes: screenshot, launch Mousepad, click, type, accessibility readback, generation fencing, joined shutdown) passed on all three Bun builds; only the patched build closes without waiting on the orphaned app.

Tests, added to test/js/bun/spawn/spawn.test.ts: inherited fds 0-3 report FD_CLOEXEC through bun:ffi fcntl; a native system("echo leaked-stdout") no longer writes into the parent's pipe while Bun's own output still arrives; the CLI sync helper still inherits stdout/stderr (hermetic bun init postinstall).

  • Linux release, baseline: the two descriptor regressions fail (leaked-stdout reaches the parent); nothing else fails.
  • Linux release, patched: spawn.test.ts 180 pass / 0 fail, process-execve.test.ts 11 pass, child-process-stdio.test.js 9 pass, watch.test.ts 16 pass, child-process-socket-inherit.test.ts skipped on this platform.
  • macOS arm64 debug: the regressions fail before and pass after; spawn/execve/process-args/child-process stdio/socket-inherit/watch 203 pass / 0 fail; broader child_process 118 pass with one failure (should allow us to set env) that reproduces identically on unmodified sources. bun run rust:check-all passes all 12 targets.

Not verified at runtime: FreeBSD and Android (compile-checked through rust:check-all).

…e Node

Match Node v24.x InitializeOncePerProcessInternal in src/node.cc, which
calls uv_disable_stdio_inheritance in deps/uv/src/unix/core.c. After Bun's
POSIX /dev/null fixups, include stdio and IPC in the CLOEXEC sweep. Use
close_range on Linux/FreeBSD when available and libuv's fcntl traversal
otherwise (probe 0..15 across gaps, then stop at the first failure).

This prevents native addons that exec or posix_spawn without explicit
stdio actions from leaking Bun's protocol pipes into long-lived children
and delaying EOF after Bun exits.

Explicitly retain stdio in the macOS sync helper with addinherit_np and
in the Android fork/execvp helper with fcntl. Keep the crash reporter's
stdin/stdout closed while explicitly inheriting stderr. Audited reload,
process.execve, common spawn actions, webview, upgrade, and FFI SDK lookup
paths; their existing explicit descriptor handling needs no changes.

Add descriptor-flag and native system() leak regressions plus hermetic
CLI-helper inheritance coverage in spawn.test.ts. The first two fail on
the unmodified debug build. Final spawn/process/stdio/watch coverage:
203 pass, 32 skip, 0 fail; rust:check-all: 12 targets pass, none skipped.
Broader child-process coverage: 118 pass, 12 skip, 5 todo, one existing
environment JSON parsing failure, reproduced on unmodified debug sources.
@steipete
steipete force-pushed the claude/posix-stdio-cloexec branch from 0bdc028 to 48aa043 Compare September 27, 2026 06:01
@steipete
steipete merged commit a70be26 into main Sep 27, 2026
9 checks passed
@steipete
steipete deleted the claude/posix-stdio-cloexec branch September 27, 2026 06:06
steipete added a commit to openclaw/openclaw that referenced this pull request Sep 27, 2026
…159462)

A Bun Gateway could not control its managed desktop without a separate
Node.js install: the computer host resolved a real Node from the desktop
PATH (#147275, then #151933 skipped Bun's node shim). Under Node that
owner already returned process.execPath; under Bun it demanded a second
runtime even though the helper and the CUA provider run on Bun.

Spawn the helper with process.execPath and resolveRuntimeWorkerArgv, the
contract other runtime workers use. Node keeps the same executable.

The runtime test now asserts the helper runs on the host's executable;
it fails under Bun with the previous code, which launched a PATH node.
The Linux live proof gains --runtime to start the built Gateway on
another executable with no node on PATH and to record every owned
process's executable. Docs drop the Node requirement and note that
Bun 1.4.2 lets launched desktop apps inherit the helper's streams until
Bun marks inherited descriptors close-on-exec like Node (openclaw/bun#12).
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 28, 2026
…penclaw#159462)

A Bun Gateway could not control its managed desktop without a separate
Node.js install: the computer host resolved a real Node from the desktop
PATH (openclaw#147275, then openclaw#151933 skipped Bun's node shim). Under Node that
owner already returned process.execPath; under Bun it demanded a second
runtime even though the helper and the CUA provider run on Bun.

Spawn the helper with process.execPath and resolveRuntimeWorkerArgv, the
contract other runtime workers use. Node keeps the same executable.

The runtime test now asserts the helper runs on the host's executable;
it fails under Bun with the previous code, which launched a PATH node.
The Linux live proof gains --runtime to start the built Gateway on
another executable with no node on PATH and to record every owned
process's executable. Docs drop the Node requirement and note that
Bun 1.4.2 lets launched desktop apps inherit the helper's streams until
Bun marks inherited descriptors close-on-exec like Node (openclaw/bun#12).
steipete added a commit that referenced this pull request Sep 29, 2026
On macOS, `bun --silent run` execs the command in place with
POSIX_SPAWN_SETEXEC. Since #12 marks inherited descriptors close-on-exec
at startup, Darwin closed the dup2 sources before applying the spawn's
file actions, posix_spawn failed with EBADF, and the command never ran,
so a child's terminating signal was lost (exit 1, signalCode null).

On the macOS SETEXEC path only, clear close-on-exec on the source
descriptors named by the dup2 file actions and register them with the
existing spawn cleanup guard so the flag is restored if preparation or
exec fails. #12's startup policy is otherwise unchanged.

The existing bun-run "exit signal works" --silent cases failed before and
pass now; full bun-run.test.ts is 297 pass, 0 fail.
steipete pushed a commit to fuller-stack-dev/bun that referenced this pull request Oct 20, 2026
…module-graph.test.ts (oven-sh#45674)

### What does this PR do?

Fixes the flaky "50 graphs alive at once, each with its own state, then
all exit and are collected" in
`test/js/bun/module-graph/module-graph.test.ts`. It failed in 2 of 31
builds of main, 125686 to 127114 (Ubuntu 25.04 x64, Windows 11 aarch64)
and passed on the retry.

The test registered one array, `graphs[25].big`, with a
`FinalizationRegistry` and failed if 100 collections did not finalize
it. It now tracks the array of every one of the 50 graphs with
`Lifetimes` from `module-graph-lifetimes.ts`, as
`module-graph-gc.test.ts` does. There, an object that is not finalized
counts as kept alive only if a root reaches it in the debugging heap
snapshot, and the failure message is the path from that root.

Two things change with the helper, and the first is what makes the runs
below pass:

1. **Where the collection runs.** The helper calls `Bun.gc(true)` from a
timer callback, main's `collected()` from the continuation of the async
test. The `runInternalMicrotask` frame that holds the stale word
(artifact 2) is not on the stack in a timer callback. In 240 of 240 runs
all 50 arrays were finalized by the first collection.
2. **What is asserted if one is left.** Not that it was finalized, but
that no root reaches it.

### Why it failed

On main one of the 50 graphs outlives the collections in almost every
run, and the test fails when that one is number 25. Whole file, CI's
environment, 840 runs:

| graphs left after the collections | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| runs | 2 | 802 | 3 | 33 |

12 of the 840 failed. In the failing runs looked at (9 heap snapshots,
12 stack dumps) nothing in the heap holds the one that is left, and one
word on the native stack points at it.

All of what follows is the Linux x64 binary that CI built for main at
7f3bc6a, with `BUN_GARBAGE_COLLECTOR_LEVEL=1
BUN_RUNTIME_TRANSPILER_CACHE_PATH=0` as in `scripts/runner.node.ts`. The
failure needs both that environment and the whole file: 0 of 240 without
the environment, 0 of 1600 with the test alone. I did not look at the
Windows failure.

<details><summary>Artifact 1: the heap snapshot</summary>

`generateHeapSnapshotForDebugging()` right after the 100 collections.
These are the array and every cell from which it can be reached:

```
snapshot: 27033 cells, 99750 edges, 586 roots; arrays named `big` still in it: 1
  cell   1532 Promise                0x34cf520fa40  incoming edges 0  in `roots` no  a root reaches it no
  cell   1555 ModuleRecord           0x34cf527e980  incoming edges 3  in `roots` no  a root reaches it no
  cell   1573 ModuleNamespaceObject  0x34cef51dd50  incoming edges 3  in `roots` no  a root reaches it no
  cell   1591 JSModuleEnvironment    0x34cf5278950  incoming edges 3  in `roots` no  a root reaches it no
  cell   1626 Array                  0x34cef3755a0  incoming edges 2  in `roots` no  a root reaches it no
  cell   1631 Function               0x34cef45a100  incoming edges 2  in `roots` no  a root reaches it no
  cell   1653 Function               0x34cef45a0e0  incoming edges 2  in `roots` no  a root reaches it no
```

The snapshots of 8 other failing runs have the same seven kinds of cell,
with the `Promise` (fulfilled with the `ModuleRecord`) as the only one
without an incoming edge.
</details>

<details><summary>Artifact 2: the stack word and the frame that owns it
(gdb, same run as artifact 1)</summary>

The test writes the snapshot and sends itself SIGUSR2, and gdb stops
there.

```
Thread 1 "bun-profile" received signal SIGUSR2, User defined signal 2.
(gdb) info registers rsp rbp
rsp            0x7fffffffa0c8
rbp            0x7fffffffa240

words in [rsp, end of stack) = [0x7fffffffa0c8, 0x7ffffffff000) that point into one of those cells: 1
  0x7fffffffa8a0 holds 0x34cf520fa40 = Promise+0; it lies in the frame with rbp 0x7fffffffa8f0, at rbp-0x50
(gdb) x/gx 0x7fffffffa8a0
0x7fffffffa8a0:	0x0000034cf520fa40
(gdb) info symbol 0x1bccee0        # where that frame's callee returns to
JSC::runInternalMicrotask(...) + 6976

rbp chain
  openclaw#3  rbp 0x7fffffffa540  Bun::Process_functionKill
  openclaw#4  rbp 0x7fffffffa550  (JIT code)
  openclaw#5  rbp 0x7fffffffa5d0  op_call_ignore_result_return_location
  openclaw#6  rbp 0x7fffffffa680  llint_call_javascript
  openclaw#7  rbp 0x7fffffffa7e0  JSC::asyncFunctionGeneratorBodyCall
  openclaw#8  rbp 0x7fffffffa8f0  JSC::runInternalMicrotask            <- owns 0x7fffffffa8a0
  openclaw#9  rbp 0x7fffffffab70  JSC::MicrotaskQueue::drainWithUseCallOnEachMicrotask
  openclaw#10 rbp 0x7fffffffac00  JSC::VM::drainMicrotasks
  openclaw#11 rbp 0x7fffffffac20  Zig::GlobalObject::drainMicrotasks
  openclaw#12 rbp 0x7fffffffac50  <bun_jsc::event_loop::EventLoop>::exit
  openclaw#13 rbp 0x7fffffffacf0  TimerObjectInternals::fire
```

12 failing runs that dumped their own stack from `/proc/self/mem` show
the same: one word, `Promise+0`, at `rbp-0x50` of
`runInternalMicrotask`. In the 5 of them where I looked for it, the
frame's callee returns to the same `0x1bccee0`, which is
`JSMicrotask.cpp:2053`.

**Who wrote it.** A hardware watchpoint on `0x7fffffffa8a0`, set at the
first line of the test, sees 10 writes. The last one is the `Promise`:
`pushq %r14` in the prologue of `JSC::ModuleGraphLoadingState::create`
(`ModuleGraphLoadingState.cpp:71`, rbp `0x7fffffffa8b0`), which saves a
register of its caller.

**Why it stays.** The 100 collections run in the continuation of an
async function, so each runs under a `runInternalMicrotask` frame at
that same address. In the disassembly the function has 9 stores to
`-0x50(%rbp)`. Following the jump table and every branch, only case 14
of the switch (resume an async function) reaches the call at
`JSMicrotask.cpp:2053`, and none of the 9 stores is on a way to it. The
slot is inside a live frame, so stack sanitizing does not cover it.

So the graph that is left is the one whose load called `create` last at
that depth.
</details>

### How did you verify your code works?

**Failure rate.** Whole file, 12 copies side by side, main and this PR
in alternating rounds:

| | main | this PR |
|---|---|---|
| runs that failed | 12 of 1200 (all this test) | 0 of 1200 |

**What the snapshot says about a survivor.** With this PR there was none
to ask about: in those 240 runs, with a logging copy of the helper, the
snapshot was never taken. So this is main's test as it is, followed by
the helper's `Heap` asked about the 50 addresses, 1080 runs. The old
assertion failed in 12 of them. In 11 the array was in the snapshot with
no root reaching it, in 1 it was gone by then, in 0 a root reached it.

In 7 of the 1080 runs a root did reach two other arrays. In the one run
whose paths were printed, both start at `root(JITWorkList)`, a
compilation that is still running. `stillAlive` goes on collecting while
a root reaches something.

**Real references must fail.** One line added before `graphs.length =
0`. All 9 fail, with these messages:

| graph 25 is held by | message |
|---|---|
| a global, the namespace | `root(ProtectedValues) GlobalObject
-Property:held-> ModuleNamespaceObject -> ModuleRecord ->
JSModuleEnvironment -> Array` |
| a global closure over `inc` | `root(ProtectedValues) GlobalObject
-Property:held-> Function -> JSLexicalEnvironment -Variable:inc->
Function(inc) -> JSModuleEnvironment -> Array` |
| a local of the suspended test | `root(Output) FunctionCodeBlock -> ...
-Variable:pendingHeap-> Promise -> AsyncFunctionGenerator -> ...` |
| `setInterval(inc)` | `root(StrongHandles) StrongRootBlock -> Timeout
-Property:callback-> Function(inc) -> JSModuleEnvironment
-Variable:big-> Array` |
| `process.on(..., inc)` | `root(ProtectedValues) GlobalObject ->
Process -> Function(inc) -> JSModuleEnvironment -Variable:big-> Array` |
| a reaction of a pending promise | `root(ProtectedValues) GlobalObject
-Property:held-> Promise -> Function(inc) -> JSModuleEnvironment
-Variable:big-> Array` |
| a `FinalizationRegistry` held value | `root(ProtectedValues)
GlobalObject -Property:held-> FinalizationRegistry -> Array` |
| a `WeakMap` value of a live key | `root(Output) Array` |
| an `AbortSignal` listener | `root(WeakSets) AbortSignal ->
Function(inc) -> JSModuleEnvironment -Variable:big-> Array` |

With `globalThis.held = graphs[7]` instead, main's test passes 5 of 5
and this PR's fails 5 of 5.

**Debug build**, default timeout: the test passes 6 of 6 alone and in 6
of 6 runs of the whole file.
steipete added a commit to steipete/bun that referenced this pull request Oct 24, 2026
Apply Node's startup descriptor-inheritance policy while preserving
explicit stdio inheritance in CLI helpers and the crash reporter.
For macOS SETEXEC, clear CLOEXEC on file-action sources and restore
changed flags through the spawn cleanup guard if execution fails.

Adapted from openclaw#12 and openclaw#24. Native before/after
regressions cover the descriptor leak on Linux and macOS, and the
startup-only Mac control confirms the silent runner needs both changes.
steipete added a commit to steipete/bun that referenced this pull request Nov 15, 2026
Apply Node's startup descriptor-inheritance policy while preserving
explicit stdio inheritance in CLI helpers and the crash reporter.
For macOS SETEXEC, clear CLOEXEC on file-action sources and restore
changed flags through the spawn cleanup guard if execution fails.

Adapted from openclaw#12 and openclaw#24. Native before/after
regressions cover the descriptor leak on Linux and macOS, and the
startup-only Mac control confirms the silent runner needs both changes.
steipete added a commit to steipete/bun that referenced this pull request Nov 21, 2026
Apply Node's startup descriptor-inheritance policy while preserving
explicit stdio inheritance in CLI helpers and the crash reporter.
For macOS SETEXEC, clear CLOEXEC on file-action sources and restore
changed flags through the spawn cleanup guard if execution fails.

Adapted from openclaw#12 and openclaw#24. Native before/after
regressions cover the descriptor leak on Linux and macOS, and the
startup-only Mac control confirms the silent runner needs both changes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant