Skip to content

fix(executor): dup write-only fds onto <&N instead of failing the redirect (Refs #3792) - #3870

Merged
caomengxuan666 merged 5 commits into
masterfrom
fix/3792-dup-write-only-fd
Nov 17, 2026
Merged

caomengxuan666 merged 5 commits into
masterfrom
fix/3792-dup-write-only-fd

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

fix(executor): dup write-only fds onto <&N instead of failing the redirect (Refs #3792)

Root cause

cmd <&N where N is a write-only fd (exec 3>f1; cat <&3) must dup
the descriptor the way GNU's dup2 does: the child inherits the
write-only fd, its own reads fail EBADF, and the CHILD reports the
error with its own diagnostic and exit status. Rubash instead failed
the redirect itself ({fd}: Bad file descriptor, child never runs),
and its emulated cat read the underlying file's content as if the fd
were readable.

Both faces come from one defect: the <&N arms matched on the fd
table's read endpoint instead of dup'ing the raw descriptor.

GNU anchor

redir.c:1193 dup2 (redir_fd, redirector) in
do_redirection_internal — no access-mode check; the dup succeeds
for any open fd and the access-mode failure surfaces later, in the
child's own read (EBADF). The only gate is redir.c:1151
(redir_fd != redirector, self-dup). Verified against GNU bash
(script files): cat <&3 → cat: -: Bad file descriptor, rc 1
(single line); head -c 5 <&3 → head: error reading 'standard input': Bad file descriptor, rc 1; cat f1 <&3 → rc 0.

Fix (three places, one mechanism)

  1. src/executor/external_setup.rs — the fd-0 <&N arm in
    apply_external_stdin_redirect: when the fd has no read endpoint
    but a handle-backed write endpoint (File / CoprocStdin /
    Stdout / Stderr), dup that handle into the child's stdin
    (new dup_write_only_fd_for_stdin). Symbolic write endpoints
    (process substitution, /dev/full, pipe channel) keep the EBADF.
  2. src/executor/shell_options.rs — open_fd_read_endpoint_stream
    (the dup-model stream serve) no longer re-opens a write-only fd's
    stored path: no read endpoint now returns EBADF. The /dev/fd/63 redirect family on synthetic fds: double diagnostic, wrong shapes for < and <>, >> silently succeeds rc=0 #1963 alias
    re-open moved verbatim into open_fd_read_endpoint (the alias
    dispatch), so < /dev/fd/N still fresh-opens its target.
  3. src/executor/external_file_builtins.rs — the emulated cat
    cannot inherit a descriptor, so it synthesizes the child's EBADF
    exactly like the [bug] exec-installed permanent stdin redirect ignored inside pipeline components #1102 closed-stdin face: new predicate
    cat_stdin_write_only_dup_source (fd-0 winner is a <&N dup of a
    write-only fd) + single-line {prog}: -: Bad file descriptor
    report, applied in the no-operand tail and in the - operand drain
    (via the [bug] 目录作外部命令 stdin 时在 open 阶段误杀(GNU 为子进程 read 失败;不读 stdin 的命令应照常运行) #2101 fd_table.read_error path).

Regression nails

New tests/issue3792_dup_write_only_fd.rs (11 tests, seed R131-C):
bare cat (empty + content), cat -, cat -n, /usr/bin/cat,
command cat, in-pipeline cat, head -c 5, dd, grep -c .,
plus controls (read-only / read-write dups, read -u 3, writes to
read-only / write-only fds, cat f1 <&3, and the alias control
cat < /dev/fd/3 which must still read the file).

本 PR 删除了什么

Verification

UNVERIFIED-BY-CAPTAIN — no build/test leg ran this round: the
X299 tunnel is still down, the Simular box wallet is empty, and local
cargo builds are banned on this VM. Ran: rustfmt --check (clean),
git diff --check (clean), scripts/check-marker-literals.py
(OK), GNU oracle probes on the Linux host (match the issue's GNU
behavior). Still owed on the build chain: the new stem
(cargo test --locked --test issue3792_dup_write_only_fd), full lib
and base count alignment, and one
RUSTFLAGS="-D warnings" cargo check --locked --lib --bins pass.

caomengxuan666 and others added 4 commits November 17, 2026 16:59
…edirect (Refs #3792)

## Root cause

`cmd <&N` where N is a write-only fd (`exec 3>f1; cat <&3`) must dup
the descriptor the way GNU's dup2 does: the child inherits the
write-only fd, its own reads fail EBADF, and the CHILD reports the
error with its own diagnostic and exit status. Rubash instead failed
the redirect itself (`{fd}: Bad file descriptor`, child never runs),
and its emulated `cat` read the underlying file's content as if the fd
were readable.

Both faces come from one defect: the `<&N` arms matched on the fd
table's read endpoint instead of dup'ing the raw descriptor.

## GNU anchor

`redir.c:1193` `dup2 (redir_fd, redirector)` in
`do_redirection_internal` — no access-mode check; the dup succeeds
for any open fd and the access-mode failure surfaces later, in the
child's own read (EBADF). The only gate is `redir.c:1151`
(`redir_fd != redirector`, self-dup). Verified against GNU bash
(script files): `cat <&3` → `cat: -: Bad file descriptor`, rc 1
(single line); `head -c 5 <&3` → `head: error reading 'standard
input': Bad file descriptor`, rc 1; `cat f1 <&3` → rc 0.

## Fix (three places, one mechanism)

1. `src/executor/external_setup.rs` — the fd-0 `<&N` arm in
   `apply_external_stdin_redirect`: when the fd has no read endpoint
   but a handle-backed write endpoint (`File` / `CoprocStdin` /
   `Stdout` / `Stderr`), dup that handle into the child's stdin
   (new `dup_write_only_fd_for_stdin`). Symbolic write endpoints
   (process substitution, `/dev/full`, pipe channel) keep the EBADF.
2. `src/executor/shell_options.rs` — `open_fd_read_endpoint_stream`
   (the dup-model stream serve) no longer re-opens a write-only fd's
   stored path: no read endpoint now returns EBADF. The #1963 alias
   re-open moved verbatim into `open_fd_read_endpoint` (the alias
   dispatch), so `< /dev/fd/N` still fresh-opens its target.
3. `src/executor/external_file_builtins.rs` — the emulated `cat`
   cannot inherit a descriptor, so it synthesizes the child's EBADF
   exactly like the #1102 closed-stdin face: new predicate
   `cat_stdin_write_only_dup_source` (fd-0 winner is a `<&N` dup of a
   write-only fd) + single-line `{prog}: -: Bad file descriptor`
   report, applied in the no-operand tail and in the `-` operand drain
   (via the #2101 `fd_table.read_error` path).

## Regression nails

New `tests/issue3792_dup_write_only_fd.rs` (11 tests, seed R131-C):
bare `cat` (empty + content), `cat -`, `cat -n`, `/usr/bin/cat`,
`command cat`, in-pipeline `cat`, `head -c 5`, `dd`, `grep -c .`,
plus controls (read-only / read-write dups, `read -u 3`, writes to
read-only / write-only fds, `cat f1 <&3`, and the alias control
`cat < /dev/fd/3` which must still read the file).

## 本 PR 删除了什么

- 删除:`open_fd_read_endpoint_stream` 的 `_` 臂里内嵌的 #1963
  alias 重开回退(无读端点时按写端点存路径重开文件读出)。该行为
  已整体平移进 `open_fd_read_endpoint`(alias dispatch),alias 形
  的行为不变;删除的只是它在 **dup 形**下的误用。
- 未删除其他任何东西:无公开面改动,无测试删除,无行为删除
  (`4<&3`、in-list 源 `cmd 3>f1 <&3`、符号写端点等残差见工作区
  REPORT §6,留给后续单)。

## Verification

**UNVERIFIED-BY-CAPTAIN** — no build/test leg ran this round: the
X299 tunnel is still down, the Simular box wallet is empty, and local
cargo builds are banned on this VM. Ran: `rustfmt --check` (clean),
`git diff --check` (clean), `scripts/check-marker-literals.py`
(OK), GNU oracle probes on the Linux host (match the issue's GNU
behavior). Still owed on the build chain: the new stem
(`cargo test --locked --test issue3792_dup_write_only_fd`), full lib
and base count alignment, and one
`RUSTFLAGS="-D warnings" cargo check --locked --lib --bins` pass.
…the descriptor path (Refs #3792)

The inline pipeline slot arms (cat/head/grep/sed/wc/tr) apply no
redirections: they read the stage's text payload. A member whose fd-0
winner is a `<&N` dup of a write-only fd (`printf x | cat <&3` after
`exec 3>f`) was therefore fed the upstream pipe the dup had already
superseded — GNU applies the element's do_redirections after
do_piping (execute_cmd.c:2620 execute_pipeline), so the element's
fd 0 is the dup2'd write-only description (redir.c:1193) and the
element's own reads fail EBADF, reported by the element itself.

The text serve declines that dup by design (#2101), so adjudicate it
once at the stage dispatch, beside the existing fd-0 file-winner
gate: a non-builtin stage with a write-only dup winner
(fd0_write_only_dup_source, shell_options.rs) routes to the external
stage spawner, whose fd-0 adjudication (#2255) replays
apply_external_stdin_redirect — the round-1 arm there dups the write
endpoint's handle into the child, which reports EBADF with its own
diagnostic and status. Builtin stages keep the stage-subshell route.

Pins: the round-1 pipeline cat pin now routes through the descriptor
path; add oracle-verified (GNU bash 5.3.20) sibling pins for the head
and grep stage arms, the stage-0 position, and a readable-dup
control proving the route does not overreach.
@caomengxuan666

Copy link
Copy Markdown
Member Author

【WIN-AGENT-AUDIT】PR #3870 第2轮(l1 续作)— 修钉期望值
head: 0df6c36 → 新 head 7839e55
续作内容:钉自跑 head 0c9e54b 时 issue3792_dup_write_only_fd 13/15,两红均为钉期望值与 GNU 5.3.20(1)-release oracle 不符(实现输出与 GNU 逐字节一致):(a) dup_write_only_fd_grep — GNU grep -c 读 EBADF 前先输出 0 计数,期望应为 "0\nrc=2\n";(b) dup_write_only_fd_controls — exec 3>f1 的 > 截断 f1,cat f1 与 cat </dev/fd/3 均读空文件,期望串中两处 hello\n 多余。已按 oracle 修正(commit 7839e55),WSL 复跑全钉+fail-first 中。

The four pipeline pins (cat stage0/stage1, wc, tr) assert a GNU coreutils consumer's own EBADF behavior on top of rubash's fd delivery. The CI census runner's cat/wc/tr are uutils coreutils, which exits 0 silently on a write-only stdin (REPORT §10.4), so the consumer half cannot discriminate there. Probe each consumer's --version once: GNU keeps both contracts at full strength; non-GNU asserts only the shell-side delivery contract (the pipe payload must not be served) and notes the skip on stderr, without encoding the uutils rc/counts as expected behavior.
@caomengxuan666
caomengxuan666 marked this pull request as ready for review November 17, 2026 23:35
@caomengxuan666
caomengxuan666 merged commit 0863639 into master Nov 17, 2026
10 of 12 checks passed
caomengxuan666 added a commit that referenced this pull request Nov 17, 2026
Refs #3568

## Summary
- `tests/common/mod.rs` 的两个 `issue2197_wait_bounded_*` pin 原来依赖 `sleep` 经 PATH 解析;`sleep` 在 rubash 里只是 pipeline-stage 快路径,不是常规 builtin,`minimal_path()`(System32 + Git usr/bin)在无 Git 的 Windows 机器上解析不到 → 假子进程 127 / 孤儿管道不成立(X299 与本机同症复现)。
- Windows 面换成不依赖外部 sleep 的等价形状:孤儿 pin 用 System32 必有的 `ping -n 10 127.0.0.1 &`(约 9s 自行退出);never-exiting pin 用纯 builtin `while :; do :; done`(wait_bounded kill 时随进程消亡,无残留)。unix 面保持 `sleep 120` 原样。

## Test plan
- [x] `cargo test --test issue2883_read_prompt_carrier_regressions`:修复前 0/2(Some(0)/Some(127)),修复后 2/2 绿(Windows 本机,minimal_path 环境)
- [x] rustfmt --check tests/common/mod.rs 干净
- [ ] Linux CI 双侧回归(unix 分支未改,预期不变)

Generated with [Devin](https://devin.ai)

## Captain review (merge-shape adjudication, head 4ed241c)

The three red legs on the head are baseline/flake-class, none caused
by this change:

- Census (job 134335800180): 100 distinct FAIL, inside the era band;
  the issue2883 stem — the pins whose harness this PR touches — is
  9 PASS / 0 FAIL, and no 2883/2197 cell is red.
- Goldens (job 134335800873): exactly the two master-baseline names
  (case_9_declare_indexed_operand_binds_nothing,
  upstream_suite_slice_snapshots).
- CLI tests (job 134335800063): sole failure
  c_command_keeps_named_coproc_output_fds_distinct — a coproc fd
  test, green on other heads of the same era, and mechanically
  unreachable by this diff: both script changes are
  #[cfg(windows)]-gated and the #[cfg(not(windows))] strings are
  byte-identical to the originals, so the Linux test binary runs
  unchanged code.

Merge without update-branch under the zero-intersection rule:
merge-base a1f9718; the five files master gained since (PR #3870)
do not include tests/common/mod.rs, this PR's only file.

Test-only change; no deletion section required. The removed lines
are the two unconditional `sleep 120` script literals, replaced by
per-platform script selection (unix keeps the identical literals).
caomengxuan666 added a commit that referenced this pull request Nov 18, 2026
… the scan can own (Refs #3864)

## Summary

Refs #3864. PR #3855 added a `braced_name_is_bad_substitution(inner)` check to the `parameter_expansion_error_in_word_context` pre-scan so a bad substitution inside a ` :?` message word surfaces as the inner error (rubash#3502: `${v:?${-x}}` prints only `${-x}: bad substitution`). The check judges the whole `${...}` inner as a braced name and reports the scan's whole word with status 1 — but the scan may only emit that verdict when it coincides with what the real expansion would report. Where it does not, the scan pre-empts the correct diagnostic:

- Compound assignment values (issue3500, whole stem): GNU expands elements individually (`arrayfunc.c:557 expand_compound_array_assignment`) and the diagnostic names the element word (`\\[0\\]=${-x}`); the scan names the raw parenthesised value.
- `$'name'` extquote names (issue2650): `subst.c:7583 valid_brace_expansion_word` judges the extracted NAME; the real expansion decodes `$'x1'` to `x1` in a quoted context, where the gate on the raw literal misjudges it.
- POSIX fatal class (audit B4-F08): `subst.c:10285-10288` makes a bad substitution FORCE_EOF when POSIX + non-interactive + compat > 43; the scan's status 1 downgrades it to DISCARD.

The funsub faces (issue2763/issue2761/issue3092/issue3823, golden_funsub_valsub, the arithmetic-for CLI case) are already fixed by #3869, which exempts funsub bodies at the top of this same scan loop; this PR does not touch that exemption.

## Repair

The gate now fires only when the scan's verdict coincides with the real expansion's: it defers (returns nothing, letting the real expansion report) when any of these holds —

1. the scanned word is (or contains) a compound assignment value (parser compound marker, or a leading `(`): GNU's diagnostic is per-element, which the scan's whole-word display cannot name;
2. the span's name head is a `$'...'` literal that `resolve_dollar_quoted_parameter_name` decodes: the gate must judge the decoded name;
3. the POSIX-fatal predicate holds (POSIX mode, non-interactive, `compatibility_level > 43`, mirroring the fatal arm in `command_execute.rs`): the scan's status 1 cannot express FORCE_EOF.

Everything else is unchanged: the gate still fires for bare bad names (`${-x}`, `${}`, `${(M)y}`), still pre-empts a later `:?` error left-to-right, and still fires inside `:?`/`:-` operator-word recursions — so all seven #3502 pins and the #3869 funsub pins keep passing by construction.

## What this PR removes

Nothing from the product surface: the #3855 gate check stays; only its three over-broad firing slices are deferred to the real expansion. No new diagnostic text, no new error class.

## Validation

**UNVERIFIED-BY-CAPTAIN** — no build or test was executed in this lane: the build chain is down (X299 tunnel refused, Simular box wallet empty, local build banned: MemAvailable ~503M, below the 1.5G gate). `cargo test` / `cargo check` / lib+base alignment / `RUSTFLAGS="-D warnings"` check are all parked; the captain re-runs the head census after the chain recovers.

- New nails `tests/issue3864_parameter_errors_regression.rs` (11 tests): issue3500 element words (indexed/assoc/nested/valid guard), issue2650 extquote top-level + bare forms, POSIX fatal + compat43 guard, funsub-valsub shapes, #3502 inner-only + pin-7 ordering guards. Written fail-first, before the repair; fail-first is by code analysis, not execution (see above).
- GNU oracle probes (local `/bin/bash` 5.2.21; stems already carry 5.3.20 verification): `"[${$'x1'}]"` -> `[hello]`; `a=([0]=${-x})` -> `\\[0\\]=${-x}: bad substitution` rc 1; POSIX `echo ${}` -> fatal, no ALIVE, rc 1; `${v:?${-x}}` -> only `${-x}: bad substitution` rc 1.
- `rustfmt --check` clean on both touched files.
- Evaluation note: reverting #3855 outright was considered and rejected — it would reopen #3502 (7 pins). The scoped repair keeps #3502 green while clearing the mechanically attributable clusters. Three singles in #3864 (issue2029, issue2771, issue2761 x2) have no `${` span in their scripts that can trip the gate, so no `parameter_errors.rs` change can clear them; they are recorded in the lane REPORT as unattributed (likely census flakes / other-window commits) for the captain's census re-run to confirm.

## Captain review (PASS, merged)

Original head 19159b6, captain-extracted from its CI logs:
census total 79 (era baseline), issue3500 19/19, own pins
issue3864 11/11, goldens exactly the two baseline names; the
darwin leg was cancelled with zero steps (never ran, not a red).

Merge-shape head 0a73b4f (update-branch over master 0863639;
the only master-side touch of parameter_errors.rs since the
merge-base was PR #3871's +6/-2 arith-label hunk near line 1417,
~1000 lines from this PR's hunks), captain-extracted:
- issue3500 19/19 PASS, issue3864 11/11 PASS, issue2650 10/10,
  issue2763 6/6, issue201 2/2, issue2771 5/5, audit stems 40/40.
- Census total 81, goldens exactly the two baseline names.
- Two non-blocking cells, both adjudicated churn: the CLI leg's
  sole failure is c_command_keeps_named_coproc_output_fds_distinct
  (2 PASS / 2 FAIL across four era heads, uncorrelated with any
  diff), and census cell issue2029
  head_pipe_fold_leaves_the_remainder is FAIL here but PASS on
  both the original head and on PR #3870's head (which carries
  #3855 without this fix) — not owned by this change.

Fail-first basis (stated honestly): the lane's 11 pins were
written pre-fix but not executed pre-fix (no build route); their
fail-first rests on code analysis, corroborated by the tip census
showing the same shapes red before this PR and green after.

What this removes: the unscoped #3855 gate call in
parameter_expansion_error_in_word_context — the scan emitted
whole-word status-1 verdicts for compound values, $'...' name
heads and the POSIX-fatal class. It is replaced by the
deferral-aware gate; each deferral restores the pre-#3855
behavior for that slice. No other behavior is deleted.
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