Skip to content

fix(executor,builtins): #773 fd table capped at 1014 with a bogus EINVAL — capacity now follows ulimit -n soft, exhaustion reports EMFILE - #870

Merged
caomengxuan666 merged 2 commits into
masterfrom
fix/773
Oct 19, 2026
Merged

caomengxuan666 merged 2 commits into
masterfrom
fix/773

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

Closes #773 (item 1: fd table caps at 1014 with a misleading errno). Items 2 (NUL bytes in read) and 3 (closed-fd-0 diagnostic) are separate faces of that issue and are NOT touched here.

Symptom (master b5793580, issue repro)

i=0; while [ $i -lt 1200 ]; do exec {fd}>>f || break; i=$((i+1)); done; echo "allocated=$i"
result stderr
GNU bash 5.3.0 (WSL oracle) allocated=1200 —
master 45f537ea allocated=1014 redirection error: cannot duplicate fd: Invalid argument
this branch allocated=1200 —

Root cause — three stacked defects in rubash's own layers

The OS/CRT was never the wall: the virtual fd table is a BTreeMap and each slot is one plain HANDLE. All three defects sit in the {var} allocation plumbing:

  1. Hardcoded ceiling — executor/fd_table.rs allocate_dynamic_with_limit scanned the fixed range (10..1024); 1024 - SHELL_FD_BASE(10) = exactly the 1014 slots the issue reports. The limit it was handed never widened the range.
  2. Dead limit parse — executor/trap_exec.rs open_files_limit ran parse::<u32>() over the whole stored cell, but builtins/ulimit.rs stores "<soft>:<hard>"; every parse failed and the allocator silently fell back to the same 1024 ceiling. ulimit -n never controlled the fd table at all.
  3. Dead key case — plat::set keyed the cell with the typed lowercase letter (__RUBASH_ULIMIT_n) while every consumer (open_files_limit, the compound_exec.rs spawn-inheritance whitelist) spells it uppercase (__RUBASH_ULIMIT_N). Same HashMap, different keys.

GNU anchors (third_party/bash + WSL GNU 5.3.0 probes, 2026-10-19)

  • redir.c:940-946 do_redirection_internal REDIR_VARASSIGN: {var} targets allocate with fcntl(fd, F_DUPFD, SHELL_FD_BASE) — lowest free fd >= 10 below the RLIMIT_NOFILE soft limit; GNU has no table cap of its own. general.c:681 move_to_high_fd is F_DUPFD-backed too, so the coproc and procsub fallbacks now route through the same limit-aware allocator.
  • Exhaustion below the soft limit is EMFILE ("Too many open files"): probe ulimit -Sn 12 → fds 10, 11 allocate, the third fails with redirection error: cannot duplicate fd: Too many open files. The oracle's default soft 10240 exhausts at ~10229 allocations.
  • Base-beyond-limit is EINVAL ("Invalid argument"): probe ulimit -Sn 6 then exec {v}</dev/null → v unset (the vredir6.sub shape). rubash now splits the two errnos the way the kernel does instead of hardcoding EINVAL — the old message sent EMFILE scripts debugging the wrong layer.
  • Heredoc {v}<<E exhausts through the same REDIR_VARASSIGN dup path (same two-line diagnostic), so the invented {name}: cannot allocate fd wording carries the GNU payload now.
  • Emulated Windows ulimit -n default now mirrors the oracle machine: soft 10240 / hard 1048576 (probed ulimit -Sn; ulimit -Hn on the WSL GNU 5.3.0 oracle), replacing the old stub's soft-1024 opinion that licensed the 1014 cap.

Changes

  • src/executor/fd_table.rs — allocate_dynamic_with_limit walks occupied slots in fd order and stops at the first gap (closed dynamic entries stay immediately reusable); ceiling = the soft limit, default 10240, unlimited 1048576. O(occupied) per allocation.
  • src/executor/trap_exec.rs — open_files_limit parses the "soft:hard" cell (u64::MAX/unlimited → no cap; absent key → default soft limit); fd_dup_error_payload picks EMFILE vs EINVAL text by where the limit bit the request; heredoc-carrier exhaustion carries the same payload.
  • src/builtins/ulimit.rs — cell keys normalized to the uppercase letter the consumers already spell; emulated n default raised to the oracle pair.
  • src/executor/compound_exec.rs, src/executor/external_setup.rs — coproc / procsub high-fd fallbacks route through the limit-aware allocator (GNU move_to_high_fd parity).

Verification

  • New tests/issue773_fd_table_capacity_regressions.rs (7 tests, all green): issue repro allocated=1200; default capacity past the old cap (2000); raised ulimit -n 4096 lifts the ceiling (3000); EMFILE wording at exhaustion; EINVAL wording at base-beyond-limit; dup shared-offset semantics (feat(repl): raw-console readline editing for the standalone interactive shell (rubash#419 readline leg) #482 surface) over a 1500-fd table; emulated ulimit defaults + soft-unlimited-over-finite-hard EINVAL.
  • Repro before/after on the pinned shapes: master allocated=1014 → branch allocated=1200; stress 10000 allocations succeeds (gate target was >=4096).
  • ulimit -n interplay: ulimit -Sn 12 blocks after 2 allocations exactly like the oracle; ulimit -Sn unlimited over a finite hard fails EINVAL like the oracle.
  • Perf A/B (debug builds, 900 same-file allocations): master 1.53s vs branch 1.29s — the ordered occupied-walk is no slower than the old fixed scan.
  • Full suite, --test-threads=1, bidirectional vs master e6a54457 (after merging it): 5606 passed / 34 machine-dependent failures identical to the master baseline's set; zero base-only failures; the single fix-only name (cat_dash_in_coproc_streams_interactively) is a CARGO_TARGET_DIR harness artifact of my shared-target build (the test resolves <manifest>/target/debug/rubash.exe) and passes 15/15 with the binary at the manifest-local path.
  • cargo fmt --check clean; RUSTFLAGS="-D warnings" cargo build clean.

…VAL — capacity now follows ulimit -n soft, exhaustion reports EMFILE

Symptom (issue #773, measured on master b579358): the issue repro
  i=0; while [ $i -lt 1200 ]; do exec {fd}>>f || break; i=$((i+1)); done
stopped at exactly allocated=1014 with
  'redirection error: cannot duplicate fd: Invalid argument'
while WSL GNU bash 5.3.0 allocates all 1200 (its own limit is far higher).

Root cause — three stacked defects in the {var} allocation plumbing, all
in rubash's own layers (the OS/CRT was never the wall; the virtual table
is a BTreeMap and each slot is one plain HANDLE):

1. executor/fd_table.rs allocate_dynamic_with_limit scanned the hardcoded
   range (10..1024) — 1024 - SHELL_FD_BASE = 1014 slots — regardless of
   the limit it was handed.
2. executor/trap_exec.rs open_files_limit ran parse::<u32>() over the
   whole stored cell, but builtins/ulimit.rs plat::set stores
   '"<soft>:<hard>"' — every parse failed, so the allocator silently
   fell back to that same 1024 ceiling. ulimit -n never controlled
   anything.
3. The plumbing was dead for a second reason: plat::set keyed the cell
   with the typed lowercase letter (__RUBASH_ULIMIT_n) while every
   consumer (open_files_limit, the compound_exec.rs spawn-inheritance
   whitelist) spells it uppercase (__RUBASH_ULIMIT_N).

GNU anchors (third_party/bash, WSL GNU 5.3.0 probes 2026-10-19):
- redir.c:940-946 do_redirection_internal REDIR_VARASSIGN: {var} targets
  allocate with fcntl(fd, F_DUPFD, SHELL_FD_BASE) — lowest free fd >= 10
  below the RLIMIT_NOFILE *soft* limit; no table cap of GNU's own
  (general.c:681 move_to_high_fd is F_DUPFD-backed too, hence the coproc
  and procsub fallbacks now route through the limit-aware allocator).
- Exhaustion below the soft limit fails EMFILE ('Too many open files':
  probe ulimit -Sn 12 -> fds 10,11 allocate, third fails; oracle default
  soft 10240 exhausts at ~10229 allocations); base-beyond-limit fails
  EINVAL ('Invalid argument': probe ulimit -Sn 6, the vredir6.sub shape).
  rubash now picks the errno text the same way instead of hardcoding
  EINVAL, which sent EMFILE scripts debugging the wrong layer.
- Heredoc {v}<<E exhausts through the same REDIR_VARASSIGN dup path
  (same two-line diagnostic), so the old invented '{name}: cannot
  allocate fd' wording carries the GNU payload now.
- The emulated Windows ulimit -n default mirrors the oracle machine
  (soft 10240 / hard 1048576, probed), replacing the old stub's
  soft-1024 opinion that licensed the 1014 cap.

Allocator shape: allocate_dynamic_with_limit walks the occupied slots in
fd order and stops at the first gap (closed dynamic entries stay
immediately reusable, vredir1/vredir6 semantics intact) — O(occupied)
per allocation, measurably no slower than the old fixed scan (A/B on the
issue shape: 900 allocations, master 1.53s vs fix 1.29s, debug build).

Verification: new tests/issue773_fd_table_capacity_regressions.rs
(7 tests: issue repro 1200, default capacity past the old cap, raised
ulimit -n 4096 lifts the ceiling, EMFILE wording at exhaustion, EINVAL
wording at base-beyond-limit, dup shared-offset semantics over a 1500-fd
table, emulated ulimit defaults + soft-unlimited-over-finite-hard
EINVAL). ulimit/coproc/procsub/redirection suites green; issue647's
spawn-path failure reproduces identically on master (hardcoded
winuxcmd install path, machine-dependent, pre-existing).

@caomengxuan666 caomengxuan666 left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent code review — verdict: APPROVE-WITH-NITS

Reviewed at head 941ccc66 against base e6a54457 in an isolated worktree. All three root-cause claims, the GNU anchors, and the verification matrix were independently re-derived (own WSL GNU 5.3.0 oracle probes, own vendored-source reads, own bidirectional suite runs) — not taken from the PR description.

Root causes — all three confirmed

  1. Hardcoded ceiling: base allocate_dynamic_with_limit scanned (10..1024) and ignored its limit argument. The fix walks occupied slots in fd order and stops at the first gap, with the ceiling now the soft limit. Closed dynamic entries stay immediately reusable (occupied() gate); a gap below the limit correctly wins over entries at/above it; limit <= 10 fails up front. Boundary audit vs the kernel: f_dupfd returns EINVAL iff arg >= RLIMIT_NOFILE soft, EMFILE when the table saturates below it — rubash's limit <= 10 → EINVAL split matches exactly.
  2. Dead parse: base ran parse::<u32>() over the whole "<soft>:<hard>" cell — always failed, silently falling back to 1024. The fix parses the soft side, maps u64::MAX (and a defensive literal "unlimited") to uncapped, and treats an absent key as the default soft limit rather than unlimited. Verified the only writer (plat::set) and the readers now agree.
  3. Dead key case: confirmed on base — plat::set wrote __RUBASH_ULIMIT_n while open_files_limit and the compound_exec spawn whitelist (_C/_F/_N, already uppercase at e6a5445) read __RUBASH_ULIMIT_N. The fix normalizes the writer to the consumers. Old-key residue: these cells are in-memory session state and were never whitelisted for child inheritance under the old lowercase key, so there is no cross-version contamination surface; a stale lowercase cell post-upgrade is ignored and falls back to the default soft limit — sane, session-scoped.

GNU anchors

  • redir.c:942 (fcntl(fd, F_DUPFD, SHELL_FD_BASE)) + :945 (sys_error("redirection error: cannot duplicate fd")) — verified verbatim in the vendored tree at the pinned submodule commit.
  • Own WSL oracle probes reproduce every pinned shape: defaults -Sn=10240 / -Hn=1048576; ulimit -Sn 12 → two {fd}>>f allocations then cannot duplicate fd: Too many open files with line 2 carrying the file name; ulimit -Sn 6 + exec {v}</dev/null → Invalid argument, v unset; ulimit -Sn 5000 → 3000 allocations; ulimit -Sn unlimited over finite hard → rc=1 EINVAL; issue repro → allocated=1200; procsub word lands on /dev/fd/63.
  • ulimit -n default 1024→10240/1048576 impact sweep: cli_tests.rs:156 (< 1024, still true), part_026 (updated), a1-ulimit.sh fixture and part_021/027 do not pin the defaults; no doc references to the old values; full bidirectional suite confirms.

Verification (independently rerun)

  • New file: 7/7 green.
  • #482 dup shared-offset surface: issue279 4/4, cli dup filter 5/5, new 1500-fd dup test green.
  • fd_redirects: 9 failures, name-identical set on base — pre-existing machine-dependent, not introduced here.
  • ulimit family (executor_tests part_026/027): 6/6 on both trees.
  • Full suite --no-fail-fast --test-threads=1 on both trees: branch 5607 passed / 34 unique failing names, all present in the base failure set (base: 36 names — the 2 extra are env noise in the branch's favor). Zero branch-only regressions. The PR's reported baseline identity reproduces; the cat_dash_in_coproc_streams_interactively artifact also does not appear with manifest-local target dirs, confirming their harness diagnosis.
  • Perf A/B (debug, 900 same-file allocations, 3 alternating rounds): base 1400/1400/1489 ms vs branch 1399/1341/1350 ms — the occupied-walk is not a regression.
  • cargo fmt --check clean; RUSTFLAGS="-D warnings" cargo build clean.
  • Piggyback scan: only the 5 src + 2 test files; no third_party/submodule/docs changes; no GPL source copied (line references only); new tests spawn no untracked processes.

Nits (non-blocking)

  1. general.c:681 move_to_high_fd is not F_DUPFD-backed — it scans down with fcntl(F_GETFD) (line 697) and moves with dup2 (line 700), capped by HIGH_FD_MAX=256 (coproc calls pass maxfd=64). The PR description and the comments at compound_exec.rs:311-314 and external_setup.rs:965-967 label it "another fcntl F_DUPFD consumer". The behavioral point (the fallback should share the fd budget) still stands, and note the fallback direction differs from GNU's high-down scan (pre-existing, low-first) — worth a one-line comment fix while the anchors are fresh.
  2. Heredoc line-2 wording: GNU prints the fixed sentinel file descriptor out of range: {errno} (redir.c:146/194) on (var)<<E exhaustion; rubash prints the variable name. The comment's "internal doc pointer" characterization is not what GNU prints — line-1 errno parity is correct, this is a documented stand-in, but the comment misdescribes the oracle.
  3. {v}<&9 exhaustion line 2 prints &9: ... where GNU prints 9: ... (the & rides along in target) — pre-existing shape, now carried into the errno-aware payload.
  4. The default pair is pinned twice (fd_table.rs consts and ulimit.rs default_for('n')) — drift risk; consider one source of truth or a debug assertion tying them.
  5. next_dynamic_fd is now write-only (already was on base) — vestigial.

No blockers. Merge at your discretion.

@caomengxuan666 caomengxuan666 left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test-probe-permissions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant