Skip to content

fix(executor): coproc honors dup output redirects like >&2 (rubash#1644, #1655) - #1695

Closed
arookieofc wants to merge 1 commit into
masterfrom
fix-1644-coproc-dup-stderr
Closed

arookieofc wants to merge 1 commit into
masterfrom
fix-1644-coproc-dup-stderr

Conversation

@arookieofc

Copy link
Copy Markdown
Member

Fixes #1644, fixes #1655 (same root cause, one fix).

GNU redir.c do_redirections runs in the forked coproc child after the coproc pipes are dup'd, so a trailing >&2 rebinds the child's stdout to the shell's stderr. Rubash's spawn path only handled the single-field file redirects and dropped every dup: a simple command's output landed in the coproc pipe instead of the shell's stderr (#1644), and a named group's output sat in the pipe unread — lost entirely (#1655).

The fix applies the coproc command's output redirects to the child in list order (GNU's left-to-right semantics, so >file 2>&1 and 2>&1 >file differ as they should), replacing the field blocks — which additionally misread >file 2>&1 (the 2>&1 arrived as a bogus Append field). A cloneable spec per fd makes dups copy the current binding: >&2 dups the parent's process fd 2 (or the stderr forwarder's target: fd 1 for 2>&1, append-open for 2>file, null for 2>&-), >&word/1>&word is r_err_and_out (one open for both fds, redir.c:832-838), 2>&word is an ambiguous redirect (diagnostic once, no coproc created, status 1 per the #846 coproc-failure convention), and move forms (>&2-) close the source in the child after the dup (self-moves excepted, rubash#1236).

Verification (local, master 499a5e2 + this fix, vs GNU bash 5.3.20): >&2, named-group >&2, 2>&1, >file, >>file, >file 2>&1, 2>&1 >file, &>file, >&word, >&-, 2>&-, >&2-, exec 2>file + >&2, exec 2>&1 + >&2, and plain coprocs all match GNU.

Known pre-existing divergences, unchanged here:

  • A truly closed stdout/stderr (>&-, move forms) is approximated with /dev/null, as the old field code and the external-redirect Null slot already did — so a child's write-error diagnostic ('echo: write error: Bad file descriptor') stays silent.
  • A coproc redirect failure reports status 1 in rubash vs 0 in GNU (the deliberate 顶层 ! { :; } > /bad rc 分歧:GNU rc=1 vs rubash rc=0(子壳形一致)——#842 CR N2 #846 convention, same as the existing file-open case).
  • Dup sources on fd >= 3 are left unchanged: the spawned child inherits no extra fds in rubash's spawn model.

Regression tests: tests/issue1644_1655_coproc_dup_stderr_regressions.rs, 7/7 passed; existing coproc suites (parser_coproc_tests, issue352, issue387, issue1528) still pass.

Note: this touches apply_coproc_redirects, the same function PR #1694 (#1651) touches — whoever merges second will need to reconcile the stdin side (body pipe) with this output loop.

…44, #1655)

GNU redir.c do_redirections runs in the forked coproc
child after the coproc pipes are dup'd, so a trailing
'>&2' rebinds the child's stdout to the shell's stderr.
Rubash's spawn path only handled the single-field file
redirects and dropped every dup: a simple command's
output landed in the coproc pipe instead of the shell's
stderr (#1644), and a named group's output sat in the
pipe unread — lost entirely (#1655).

The fix applies the coproc command's output redirects
to the child in list order (GNU's left-to-right
semantics, so '>file 2>&1' and '2>&1 >file' differ as
they should), replacing the field blocks — which
additionally misread '>file 2>&1' (the '2>&1' arrived
as a bogus Append field). A cloneable spec per fd makes
dups copy the current binding: '>&2' dups the parent's
process fd 2 (or the stderr forwarder's target: fd 1
for 2>&1, append-open for 2>file, null for 2>&-),
'>&word'/'1>&word' is r_err_and_out (one open for
both fds, redir.c:832-838), '2>&word' is an ambiguous
redirect (diagnostic once, no coproc created, status 1
per the #846 coproc-failure convention), and move
forms ('>&2-') close the source in the child after
the dup (self-moves excepted, rubash#1236).

Regression tests:
tests/issue1644_1655_coproc_dup_stderr_regressions.rs (7 tests:
#1644 pipe-EOF + stderr, #1655 named group, 2>&1 alone,
order both ways, rebound parent stderr, word target +
ambiguous, plain file cases unchanged).
@caomengxuan666

Copy link
Copy Markdown
Member

Verification status from our side (your tree cherry-picked onto master 160e792, probes against the GNU bash 5.3.20 oracle): your tests pass (7/7, parser 31/31) and probe shapes d1/d2/d3/d6 match GNU exactly. One measured divergence is holding the merge:

d5 shape: the diagnostic text matches GNU byte-for-byte, but your tree exits rc=1 and leaves CPID unset, where GNU exits rc=0 and sets CPID.

Two further shapes (d4 shared >&word open, d7 fd≥3 dup) could not be adjudicated yet — the scratch fixture was wiped by a machine restart mid-run; our supplement probes for those two are queued and we will update this comment when they land.

If the d5 behaviour is straightforward to align (coproc registered + success status when GNU does so despite the diagnostic), a fix plus a regression pin for that shape would clear the way; if you read the shape differently, the probe scripts are the ones in our verify-coproc6 run (d5) — happy to compare notes here.

caomengxuan666 added a commit that referenced this pull request Oct 27, 2026
…c pipe

`coproc RC { cat; } >file` broke the coproc: apply_coproc_redirects
replaced the child's stdout Stdio and dropped the pipe writer
before the spawn, so the pipe's only write end vanished and the
parent's read end reported immediate EOF (rc 1); the file check
then raced the never-fed child.

GNU applies the redirect in the forked child (execute_cmd.c),
where the displaced pipe end survives in a redirect save slot for
the child's whole life: the read end sees no EOF while the coproc
lives (read -t 1 times out, rc 142) and the data lands in the
file. apply_coproc_redirects now hands the displaced writer back
instead of dropping it: on Unix it rides into the child via
pre_exec (dup to the first free fd in the save-slot range
10..64; dup2 clears CLOEXEC so it survives the exec); elsewhere
the parent holds it in coproc_displaced_stdout_writers until
retire_completed_coproc drops it. Dup targets (`>&2`) displace
nothing and keep the old path — that seam is #1695's, untouched.

GNU bash 5.3.20 oracle: seed gives `read rc=142`, `file: abc`
for both `>` and `>>`. Pins:
tests/issue1632_coproc_redirected_stdout_regressions.rs.

Fixes #1632
caomengxuan666 added a commit that referenced this pull request Oct 27, 2026
* fix(read): coproc `read -u` no longer reports EOF after a full line

The `-u N` coproc serve in read_input_for_command_inner re-derived
the read.def:949 EOF flag from the TRIMMED record text
(`!record_contains_delimiter(output, ...)`). trim_read_input has
already removed the delimiter, so every successful record — and
every -n/-N limit stop — scored as EOF-without-delimiter and the
builtin returned 1 despite serving the line.

read_coproc_stdout owns that accounting itself: it sets
read_eof_no_delimiter only when the pipe ends before the delimiter
arrives. Drop the caller's re-derivation (the `<&N` alias call site
already returns the record directly).

GNU bash 5.3.20 oracle (script-file probes): `read rc=0 line=[hello]`,
`read -n 3` rc=0. Regression pins: tests/issue1623_coproc_read_eof_regressions.rs.

Fixes #1623

* fix(coproc): retire the variable family by registry, not by live fd endpoints

Two coupled defects kept a dead coproc's NAME array and NAME_PID
bound forever (`fds=[63 -1] pid=[<dead pid>]`):

1. retire_completed_coproc recognized a reaped pid as a coproc
   only when a CoprocStdout/CoprocStdin endpoint was still in the
   fd table. GNU coproc_reap (execute_cmd.c) walks the coproc list
   and runs coproc_unsetvars (execute_cmd.c:2450) unconditionally;
   rubash's registry is coproc_names, so recognition is now keyed
   on it, with the endpoint scan kept as a fallback. The leak
   triggered whenever both ends had left the table before the
   reap: the write end closed by `exec {NAME[1]}>&-` and the read
   end closed by an EOF read's endpoint close.

2. read_coproc_stdout closed the read endpoint on ANY loop exit
   (`ended`), including a deadline break and a SIGINT abort. Only
   a true pipe EOF (empty read or read error) may close it — GNU
   keeps the descriptor across builtin calls, so a timed-out
   `read -t` (rc 142) leaves the coproc fully usable.

GNU bash 5.3.20 oracle: issue seed settles to `fds=[] pid=[]` and
the re-read fails as `invalid file descriptor specification`;
timeout-then-reuse round-trips. Pins:
tests/issue1624_coproc_family_retire_regressions.rs.

Fixes #1624

* fix(parser): `coproc NAME { ...; }` inside a brace group or function body parses

The seed forms were a whole-script syntax error (rc 2, `syntax
error near unexpected token '}'`) although the identical coproc
works at top level. matching_brace_group_end's
word_command_open_brace validates a `coproc NAME {` opener by
walking left over the prefix chain, but any KEYWORD predecessor
outside the four prefix keywords returned false — including the
enclosing group's own `{`, which is exactly the command-position
boundary that proves the coproc starts a command. The coproc's
`}` then closed the OUTER group in the depth scan and the rest
of the line was garbage.

The falsifying predecessor is a WORD (`echo coproc a {` keeps
`{` a plain argument — that arm is unchanged); a keyword
predecessor after a consumed prefix chain (`{`, `then`, `do`,
`else`, ...) confirms command position. The walk now returns
what it accumulated (parse.y:1125-1175 coproc productions).

GNU bash 5.3.20 oracle: seed prints grouped-ok/func-ok, rc 0;
a coproc spawned inside a group round-trips under its name.
Pins: tests/issue1625_coproc_nested_brace_regressions.rs.

Fixes #1625

* fix(coproc): a coproc-level stdout redirect no longer kills the coproc pipe

`coproc RC { cat; } >file` broke the coproc: apply_coproc_redirects
replaced the child's stdout Stdio and dropped the pipe writer
before the spawn, so the pipe's only write end vanished and the
parent's read end reported immediate EOF (rc 1); the file check
then raced the never-fed child.

GNU applies the redirect in the forked child (execute_cmd.c),
where the displaced pipe end survives in a redirect save slot for
the child's whole life: the read end sees no EOF while the coproc
lives (read -t 1 times out, rc 142) and the data lands in the
file. apply_coproc_redirects now hands the displaced writer back
instead of dropping it: on Unix it rides into the child via
pre_exec (dup to the first free fd in the save-slot range
10..64; dup2 clears CLOEXEC so it survives the exec); elsewhere
the parent holds it in coproc_displaced_stdout_writers until
retire_completed_coproc drops it. Dup targets (`>&2`) displace
nothing and keep the old path — that seam is #1695's, untouched.

GNU bash 5.3.20 oracle: seed gives `read rc=142`, `file: abc`
for both `>` and `>>`. Pins:
tests/issue1632_coproc_redirected_stdout_regressions.rs.

Fixes #1632

* fix(parser): procsub source reprint keeps `;` before closers and at body end

The #1024 newline fold in process_substitution_source fired for
EVERY mid-body line-break semicolon, rewriting the two canonical
reprints the #373/#381/#390 adjudication pins own:
`case esac in ; esac` became "case esac in\nesac" and a trailing
separator in `echo bye ;` became a newline — the two parser_tests
reds of #1859.

The fold is owed only between two commands (its purpose is body
diagnostic line numbering). A break before a closer/continuation
keyword (esac/fi/done/then/else/elif/do/}/)) or at the body's end
separates nothing, so it now falls through to the generic `;`
spelling; Branch A's after-`;` newline push is gated the same
way. `in` is deliberately NOT in the set: `case x ; in` is a GNU
syntax error (oracle-verified), so a break before `in` keeps the
verbatim newline. `(echo a ; )` is oracle-valid, so `)` is safe
in the set.

Regression pins (pre-existing, were red):
test_process_substitution_keeps_case_pattern_starting_with_esac,
test_process_substitution_keeps_command_after_heredoc_body
(tests/parser_redirection_tests.rs).

Fixes #1859

* test(coproc): pin the #1790 stale-fd adjudication (recon only)

Re-measured on baseline master f78396f in the deterministic
shape (fd saved before the child ends, settle delay): both of
#1790's claims fail to reproduce — the second read DOES print
`read: 63: invalid file descriptor: Bad file descriptor` and the
target variable keeps its value, byte-identical to GNU bash
5.3.20, 3/3 on both sides. The shape's only real divergence was
the first read's status, which is #1623. The un-saved-fd form is
racy in GNU itself. Pin locks the GNU behavior; see the cluster
REPORT.md for the full evidence table.

Refs #1790

* fix(coproc): complete the #1632 build — fork-copy field and writer handoff

The Executor fork-copy literal in command_substitution.rs
enumerates every field and needed the new
coproc_displaced_stdout_writers entry (E0063), and
apply_coproc_redirects' displaced-writer return tripped a
conditional-move error (E0382): the writer now leaves through a
single if/else handoff into the return value.

Refs #1632

* fix(lexer): brace-group fold counts `coproc NAME {` as a nested opener

The token-level root of #1625: tokenize() of the seed line folded
the OUTER group as the single keyword token "{ coproc FC2 { cat; }"
— skip_brace's depth scan treated the coproc body's `{` as word
text (its predecessor word FC2 is not close-acceptable) while the
body's `}` still counted as a closer, so the fold ended one brace
early and the enclosing group's real `}` was left stray.

skip_brace already carries a `function NAME` chain for the
identical grammar shape (parse.y:1056 function_def, rubash#465);
the coproc productions (parse.y:1125-1175 `COPROC [WORD]
shell_command`) had no mirror. Add coproc_chain (0/1/2) plus
word_began_acceptable: stage 1 arms only when the `coproc` word
began at a close-acceptable (command) position, because GNU
produces COPROC only where a reserved word is acceptable
(parse.y:5899) — `echo coproc FC2 {` keeps `{` as word text and
still errors exactly like GNU. The chain rides the same reset
points as function_chain and is carried through the brace-scan
resume cache.

The companion parser-scan change (word_command_open_brace) from
the previous #1625 commit covers the unfolded token route with
the same invariant.

GNU bash 5.3.20 oracle: seed prints grouped-ok/func-ok rc 0;
guard shapes (echo function/coproc forms) unchanged. Pins:
tests/issue1625_coproc_nested_brace_regressions.rs.

Fixes #1625

* style(lexer): rustfmt the coproc_chain stage-1 condition (#1625)

---------

Co-authored-by: 曹梦轩 <[email protected]>
caomengxuan666 added a commit that referenced this pull request Oct 28, 2026
WIP: fix(executor): coproc honors dup output redirects like >&2 (transplant of #1695)
@caomengxuan666

Copy link
Copy Markdown
Member

本 PR 的实现已采纳并合入 master——经移植 PR #1985(merge 3fd1dbb),本帖在此关闭,谢谢你的实现与测试。

为什么是移植而非直接合并:你的分支与 master 在 compound_exec.rs 冲突一文件——master 的同一函数此间已被 #1694(stdin body)与 #1632 对账(displaced writer 交还)改形。移植把你的有序重定向状态机(CoprocFdSpec 三态 + cmd.redirects 有序循环 + word/ambiguous 处理)接到现行函数形状上,保留现行 stdin-body 与移位写端语义;对接点四处、逐条记录在移植报告里,其中一处是你基线没有的必要适配(fd-1 spec 被替换时管道写端回交 displaced 槽,否则读端提前 EOF)。一处自觉偏离已在 PR 正文标注:自 dup N>&N 按 GNU 语义跳过为 no-op(你的原文走克隆往返)。dup 源 fd≥3 的限制按你的原文原样保留并在 PR 正文如实标注。

归属:合入 commit 的 message 明示 implementation by a-rookie-of-C-language 并带你的 Co-authored-by;你的 7 条回归钉整取入仓,另吸收了我方 #1712 唯一未覆盖的 1>&2 显式拼写钉,合为 8/8 全绿。

证据链(裁定报告 ~/workspace/coproc-adjudication/REPORT.md §四):你的 PR 时间戳为同题最早(2026-10-25 21:06);在你自身基线 7/7 过;在当前 master 上你的测试判别干净(dup 语义五条全红、两条对照钉绿);移植后 lib/regression 与 pristine A/B 逐名全等、diffcorpus 无新失败、Windows goldens 通过。#1644/#1655 已由 #1985 的 Fixes 关单。

SpookyWaste pushed a commit to SpookyWaste/rubash that referenced this pull request Oct 29, 2026
…44, unixwin#1655)

Transplant of PR unixwin#1695 (a-rookie-of-C-language, commit 1bcffe8,
2026-10-26 05:06 +0800) onto current master, per the coproc-line
adjudication: unixwin#1695's ordered state machine is the widest of the
two competing fixes (unixwin#1712's own body concedes this), passes 7/7
on its own base, and discriminates cleanly on master (all five
dup-semantics pins red, both control pins green).

GNU redir.c do_redirections runs in the forked coproc child after
the coproc pipes are dup'd, so a trailing '>&2' rebinds the child's
stdout to the shell's stderr. Rubash's spawn path only handled the
single-field file redirects and dropped every dup: a simple
command's output landed in the coproc pipe instead of the shell's
stderr (unixwin#1644), and a named group's output sat in the pipe unread
— lost entirely (unixwin#1655).

The fix applies the coproc command's output redirects to the child
in list order (GNU's left-to-right semantics, so '>file 2>&1' and
'2>&1 >file' differ as they should), replacing the field blocks —
which additionally misread '>file 2>&1' (the '2>&1' arrived as a
bogus Append field). A cloneable spec per fd makes dups copy the
current binding: '>&2' dups the shell's current fd-2 endpoint (the
unixwin#1882 direct plan's resolved endpoint, or the stderr forwarder's
target), '>&word'/'1>&word' is r_err_and_out (one open for both
fds, redir.c:832-838), '2>&word' is an ambiguous redirect
(diagnostic once, no coproc created, status 1 per the unixwin#846
coproc-failure convention), and move forms ('>&2-') close the
source in the child after the dup (self-moves excepted,
rubash#1236).

Transplant deltas vs 1bcffe8 (master moved under the PR):
- apply_coproc_redirects keeps master's rubash#1651 stdin-body /
  redirect_in head verbatim and gains the caller's stderr_forward
  target; the return becomes CoprocRedirectOutcome — Proceed
  carries the rubash#1632 displaced pipe writer, Declined is the
  ambiguous arm — so the unixwin#1632 save-slot hand-back and the unixwin#1882
  stderr plan keep their exact semantics: replacing the fd-1 spec
  hands the pipe writer back instead of dropping it, and the fd-2
  dup seed resolves from the same fd-2 endpoint the plan used.
- The append arm keeps master's session_path conversion.
- A self-dup ('1>&1', including the move spelling) is skipped as
  the no-op GNU makes it, instead of round-tripping through a
  spec clone, so the pipe writer is never displaced by a redirect
  that changes nothing.

Known limitation kept from unixwin#1695: a dup whose source is fd >= 3
is left unchanged (the spawn model inherits no extra fds).

Regression tests: tests/issue1644_1655_coproc_dup_stderr_regressions.rs
— PR unixwin#1695's seven pins taken verbatim, plus the '1>&2'
explicit-spelling pin absorbed from PR unixwin#1712 (commit 331c743).

Implementation by a-rookie-of-C-language (PR unixwin#1695), transplanted
onto current master.

Co-authored-by: a-rookie-of-C-language <[email protected]>
@caomengxuan666
caomengxuan666 deleted the fix-1644-coproc-dup-stderr branch October 30, 2026 01:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants