Skip to content

fix(read): empty-line rc, fd0 file-loop ownership, carrier domain, dup-stdin console reads, -t deadlines, stty builtin (#275 #276 #277 #279 #280 #282) - #567

Merged
caomengxuan666 merged 3 commits into
masterfrom
fix/read-builtin-trio
Oct 12, 2026
Merged

caomengxuan666 merged 3 commits into
masterfrom
fix/read-builtin-trio

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

Read builtin/console input batch — six issues, one path family. GNU anchors are vendored builtins/read.def + lib/sh; every fix cites behavior facts + coordinates, no GPL code.

Fixes

  • [bug] xtrace PS4 with $LINENO inside comsub bodies renders the outer line (GNU: body-local) #275 empty line returned rc=1 (GNU: rc=0). A delimiter-only record is a SERVED record (read.def:731-738 assigns, :949 only fails on true EOF). The inherited-stdin and coproc transports conflated output.is_empty() with EOF, so printf '\n' | read v exited 1 and while read silently skipped empty lines — worse, the consumed-but-discarded delimiter cascaded into swallowing the NEXT record. RED→GREEN: 3 tests (tests/issue275_read_empty_line_regressions.rs).
  • [bug] Backslash swallowed in comsub body: $(case z in z) printf 'z\n' ;; esac) stores zn (GNU: z) #276 <file loop poisoned fd 0 for later reads. After a while read; done < file loop reached file EOF, read_input_for_command fell through to the enclosing pipeline stage's FUNCTION_STDIN mirror and served its record INSIDE the loop, leaving the mirror consumed (offset 0→2) — the following read hit a false EOF. Fix: a file bound on fd 0 is a real open file description; read.def:294 reads ONE descriptor, so EOF on it is final. Repro (script shape, stable): f() { while read q; do :; done < f.txt; }; printf 'm\n' | { f; read w3; } — was rc=1 w3=[], now rc=0 w3=[m] (GNU parity), 3 tests.
  • [bug] printf suite residuals: %lc multibyte od dump, %q shapes, diagnostic rc (4 stdout lines vs GNU) #277 non-tty input re-encoded 0x1B/0x0C (ee 80 80 leak). Root cause located: NOT a UTF-16 conversion — the read value producers (inherited-stdin StdinCharDecoder, the FUNCTION_STDIN mirror) stored carrier bytes as LITERAL chars, while the shell's storage domain (assignment/ANSI-C words via push_ansi_c_byte, file/coproc transports via bytes_to_shell_text) encodes them as the E000 raw-byte marker pair, because 0x1B IS the lexer marker byte (QUOTED_WORD_PREFIX). Consequences: declare -p rendered the ESC invisible ($'[A\f' instead of $'\E[A\f'), case $key in $'\x1b[A') never matched (direction-key parsing broken), and a value crossing the assignment boundary again could emit the raw sentinel bytes. Fix: every served record is normalized at the single trim_read_input exit (idempotent tag_read_carrier_text); delimiter needles match both transport forms. Tests assert: eq/case MATCH, declare -p \E, od byte fidelity 1b 5b 41 0c, ${#v}, \f does not split read -a, -d $'\x1b' across transports, and ee 80 80 sentinel bytes absent from stdout/stderr. 7 tests (4 RED on master).
  • [bug] ble.sh --noattach source: rubash rc=0/empty vs GNU rc=1 'not an interactive session' (post-#255 residual) #279 exec 8<&0; read <&8 rc=1 + swallowed key on a real console. The <&N / -u N arms returned None for the inherited-stdin endpoint (flag-gated) while a plain fd 0 read fell through to the raw transports. POSIX dup shares the open file description, so a dup of stdin is now served from the same transports via read_dup_of_stdin (mirror → flag-armed inherited reader → raw byte-wise reader, with EOF/timeout flag backfill). fd 0's self-reference (read <&0) keeps its existing path — GNU's record boundary there differs and master parity held (verified: same output as master). ConPTY before/after: blocked → RC=0 LEN=1 K=[Q].
  • [cosmetic] mkdir with wildcard-named operand prints 'bash: line 1: Invalid argument' without the mkdir: cannot create directory prefix #280 read -rsn1 -t 0.05 blocked until input. Two layers: (1) read_stdin_until had no deadline check at all (read.def:659 check_read_timeout parity) — added deadline param + timed_out flag; (2) console readability: a winpty/ConPTY char-device stdin is always signaled for WaitForSingleObject and its queue holds records ReadFile never consumes, so wait_readable now polls PeekConsoleInputW for a key-down record on console handles — the exact event a cooked read consumes. Byte reads from a console switch to one-char mode (read.def:570-590 ttfd_onechar/cbreak) with manual echo when not -s, gated so plain reads keep canonical mode and -s alone only silences echo (read.def:603-621). ConPTY: blocked >5s → 142 in 0.41s (GNU 128+SIGALRM, read.def:553); -t 0 live-terminal now 142. 4 tests + ConPTY legs.
  • [bug] modernish bin/modernish init aborts in fatal.sh battery after #256/#257 (MSH_FTL_DEBUG produces no output, uncited) #282 console input line-buffered only. Covered with [cosmetic] mkdir with wildcard-named operand prints 'bash: line 1: Invalid argument' without the mkdir: cannot create directory prefix #280's one-char/echo work (single-key read -n1 without Enter, -s no echo — ConPTY-verified, typed key appears exactly once on screen), plus a new engine stty builtin: raw/-raw/cooked/sane/echo/-echo/size mapped onto GetConsoleMode/SetConsoleMode, left-to-right operands, coreutils diagnostics (non-terminal stdin, invalid argument). GNU bash runs an external stty; Windows has none, so TUI scripts' stty raw -echo died with command-not-found. Shell functions still shadow it; the name stays out of BUILTIN_NAMES (introspection reports external, rubash#154 rule). 4 tests.

Verification

Closes #275, closes #276, closes #277, closes #279, closes #280, closes #282.

rubash-batch added 3 commits October 12, 2026 13:07
…p-stdin console reads, -t deadlines

read builtin trio+duo, niubash#275/#276/#277/#279/#280:

- #275: a delimiter-only record is served, not EOF (read.def:731-738);
  inherited-stdin and coproc transports no longer conflate the empty
  line with EOF, so 'printf \n | read' exits 0 and while-read keeps
  the empty iteration.
- #276: EOF on a file bound to fd 0 is final (read.def:294 single
  descriptor); the read no longer spills into the FUNCTION_STDIN
  mirror of the enclosing pipeline stage after a 'done < file' loop,
  which consumed the stage's record and faked the next read's EOF.
- #277: read records are normalized into the assignment-carrier
  domain (E000 raw-byte pairs, like bytes_to_shell_text and $'..'
  words); literal 0x1b/0x0c used to collide with the lexer marker
  system - declare -p dropped the ESC, pattern comparison against
  $'\x1b[A' never matched, and marker bytes (ee 80 80) could reach
  consumers. Delimiter needles and the stage mirror match both forms.
- #279: a descriptor dup'd from stdin is served from the same
  transports as an fd 0 read (POSIX dup shares the open file
  description); 'exec 8<&0; read <&8' no longer collapses to rc=1
  with the keystroke lost on a real console.
- #280: read_stdin_until honors the -t deadline (read.def:659
  check_read_timeout parity); console handles wait through
  PeekConsoleInputW key-down records (a ConPTY console stays
  signaled and ReadFile blocks forever otherwise); byte reads switch
  the console to one-char mode (read.def:570-590) so single keys
  arrive without Enter; -t 0 on a live terminal returns 142.
  Fractional -t 0.05 now returns 142 in ~50ms.

GNU anchors: builtins/read.def:294,539-562,570-590,659,731-738,762-768,949.
Console/tty legs verified under ConPTY (scripts/smoke-read-tty-pty.py);
pipe legs in tests/issue275..280_*.rs.
…282

- stty is answered by the engine (raw/-raw/cooked/sane/echo/-echo/size
  mapped onto GetConsoleMode/SetConsoleMode; left-to-right operands;
  coreutils diagnostics for non-terminal stdin and invalid operands).
  GNU bash runs an external stty; on Windows none exists, so TUI
  scripts' 'stty raw -echo' died with command-not-found (niubash#282).
- The read builtin's console one-char mode is gated like GNU
  (read.def:570-590): only -n/-N counts or a non-newline delimiter
  switch out of canonical mode; -s alone silences the echo
  (read.def:603-621 ttfd_noecho), a plain read keeps the line
  discipline.
- 'read <&0' / 'read -u 0' keep the fd-0 self-reference path (GNU
  record boundary differs from a fresh dup; master parity held).
- Console legs verified under ConPTY (scripts/smoke-read-tty-pty.py):
  -s echo suppression, canonical line reads, one-char -n1; the stty
  legs SKIP on winpty-style bridges (no console-mode API) and are the
  real-console verification vehicle (真机待验).

GNU anchors: builtins/read.def:570-590,603-621; coreutils stty diagnostics.
…in still serves

Follow-up to the niubash#276 fix in 6176dae: the file-final rule for an
fd 0 file binding also caught the null device that async materialization
parks on fd 0. Unlike a 'done < file' binding, NUL is not a user-bound
descriptor and carries no records - the staged FUNCTION_STDIN mirror IS
the compound's own input in that state, so EOF on NUL must fall through
to the mirror. redir.tests redir11-adjacent heredoc loop: the first
'read line' reported EOF and the loop body never ran (snapshot red:
'ab cd cd' -> empty line; upstream_suite_slice_snapshots redir slice).

Discriminator: is_null_device on the bound path. NUL has no records, so
the fall-through cannot reintroduce the #276 mirror contamination - and
an explicit 'done < /dev/null' arms an empty mirror either way (master
parity held on both shapes; GNU anchors read.def:294 single-descriptor
read vs the async-default /dev/null dup2 which never rebinds the
parent's fd 0).

Verified: upstream_suite_slice_snapshots green (full tests/regression.rs
27/27), all six new issue test files green (27 tests).
@caomengxuan666

Copy link
Copy Markdown
Member Author

redir snapshot red reproduced, bisected, and fixed — f2c5f97 pushed.

Root cause (your #1 suspect confirmed, with one refinement): the #276 file-final rule made read_virtual_fd_stdin(0) EOF final for every File endpoint on fd 0. But not every File-on-fd-0 is a user binding — async materialization parks the null device there as the implicit default stdin (harness stdin is NUL; GNU's async jobs get /dev/null via dup2 in the child and never rebind the parent's fd 0). The redir.tests heredoc while read line; done <<EOF loop runs exactly in that state: fd 0 = File(NUL), FUNCTION_STDIN mirror armed with the heredoc at offset 0. Old #276 code: EOF on NUL → read reported EOF → loop body never ran → golden ab cd cd collapsed to one empty line.

Fix (read_io.rs): the file-final rule now exempts the null device — is_null_device on the bound path falls through to the staged mirror. Semantics of both worlds hold:

Verification:

  • cargo test --test regression — 27/27 including upstream_suite_slice_snapshots (redir slice byte-identical to golden).
  • All six new issue test files still green (27 tests; [bug] Backslash swallowed in comsub body: $(case z in z) printf 'z\n' ;; esac) stores zn (GNU: z) #276 tests included).
  • Full cargo test --no-fail-fast on the branch: 42 failing names, exactly the pre-existing master red set (the earlier 53-name baseline included 11 environment failures from the fresh worktree's missing third_party/bash submodule — upstream_suite itself plus 10 examples::* tests; with the submodule present they pass here).

Local note: the first local run needed third_party/bash (submodule) copied into the fresh worktree — CI has it, so no repo change needed for that.

@caomengxuan666

Copy link
Copy Markdown
Member Author

Follow-up record: the redir golden regression during this PR's CI — root cause, fix, four-probe GNU comparison

The PR body above was written before the follow-up that resolved a deterministic red this PR introduced in CI: upstream_suite_slice_snapshots went red on the redir slice (diff context redir11 bad 3; golden section ab cd cd produced an empty line). The fix shipped as the branch tip f2c5f97 ("read: a null-device fd 0 is not an explicit binding — staged stdin still serves") and is squash-merged into master as f9fe68c. Recording the analysis here so the archive is complete.

Root cause: POSIX async materialization's NUL misjudged as an explicit fd 0 binding

The #276 fix (6176dae) made a FILE binding on fd 0 final-at-EOF: once while read; done < file exhausts the file, read must not fall through to the enclosing pipeline stage's FUNCTION_STDIN mirror — GNU builtin_read reads exactly ONE descriptor, fd 0 as do_redirections bound it (read.def:294), and EOF there is terminal.

But the rule as written matched any FdReadEndpoint::File on fd 0. POSIX async semantics also park /dev/null on fd 0 of an async compound in the absence of an explicit input redirection (the redir.tests:143 shape: { read line ; echo $line ; } & inside a heredoc-fed loop). That /dev/null is an artifact of going async, not a user binding — and the async compound's real input is the staged FUNCTION_STDIN mirror carrying its heredoc record. The #276 rule classified the parked NUL as an explicit binding and terminated at its instant EOF, so the first read line returned EOF without consulting the mirror, the loop body never ran, and the following plain heredoc loop (whose golden section is ab\ncd\ncd, redir.snap:29-31) came out empty — the deterministic red.

Fix: is_null_device discriminator on the bound path

f2c5f97 narrows the final-EOF rule: an fd 0 FILE binding is final unless the bound path is the null device. NUL falls through to the staged mirror; explicit bindings (done < file, exec 0<file, and explicit done < /dev/null) keep terminal EOF. Two safety properties:

GNU anchors: read.def:294 (single-descriptor read for explicit bindings) vs the async-default /dev/null dup2, which never rebinds the parent's fd 0.

Four-probe GNU byte-for-byte comparison

Re-run 2026-10-12 against the f2c5f97 build vs WSL GNU bash 5.3.0 — all four identical on stdout+stderr+rc:

# Shape (anchor) rubash f2c5f97 GNU bash 5.3.0
1 Async compounds inheriting a heredoc loop's binding, NUL parked on fd 0 (redir.tests:143 — the regression shape) ab cd ef gh ij kl, rc=0 identical
2 Explicit done < file loop then piped read w (#276 — file EOF final, pipe record survives) [rec1] [rec2] w=[m], rc=0 identical
3 Explicit done < /dev/null loop then piped read w (explicit NUL binding, EOF final) w=[m], rc=0 identical
4 Top-level async cat & with no redirection, piped script stdin, then read w (redir.tests:159 — NUL in absence of redirection, parent fd 0 untouched) rc=0 w=[leak], rc=0 identical

Verification at merge (re-run 2026-10-12, post-merge)

  • cargo test --test regression upstream_suite_slice_snapshots: green (all 13 slices byte-identical to committed goldens, incl. redir; tests/regression.rs binary 0 failures — 27/27 with the named tests).
  • All six issue test files green: 27/27 (issue275/276/277/279/280/282).
  • Full cargo test --no-fail-fast, branch f2c5f97 vs fresh master f9fe68c: failure sets identical by name — the same 52 pre-existing master reds on both sides, zero introduced, zero fixed. (One apparent extra entry in the master-side run, upstream_suite_slice_snapshots, was environmental: the fresh worktree lacked the untracked vendored third_party/bash/tests inputs, so the slice test panicked on missing fixture files. With the same 622 vendored files in place the master snapshot test is green, redir slice included — verified directly.)

@caomengxuan666
caomengxuan666 deleted the fix/read-builtin-trio branch October 12, 2026 09:18
SpookyWaste pushed a commit to SpookyWaste/rubash that referenced this pull request Nov 12, 2026
…sh#2345)

GNU's ENOEXEC re-entry (execute_cmd.c:6237-6260) runs inside the
forked child: the parent only ever waits on a real process, so a
shebang-less child's self-addressed SIGKILL and the parent's
deferred traps behave exactly as for an exec'd child. rubash ran
the re-entry in-process (execute_enoexec_shell_script), giving
the ENOEXEC face the same unixwin#2345 defects: `./die.sh` with
`kill -KILL $$` killed the outer shell (137, whole tree), and a
USR1 trap armed in the parent was silently swallowed across a
shebang-less child's lifetime (handler output missing).

Two sites, one rule (Executor::enoexec_spawn_target — the
real_shell_children gate plus the extracted
enoexec_script_spelling, unixwin#2302/unixwin#2317's $0 name derivation):

- The foreground classification in execute_external_inner still
  refuses binaries/bad interpreters first, then RETARGETS its
  shared spawn tail at this binary with the script spelling as
  the lead argument: operand materialization, environment,
  redirects, and the wait (with its death notices) are the
  ordinary disk-command machinery. The spawn takes the
  find_shell shape (used_shell, script-keyed bookkeeping) so
  spawn_external_process's synthetic-ENOEXEC pre-empt and
  exec-format fallbacks stay about the script; the unixwin#567 route
  seam never sees the retarget.
- The spawn-failure fallback in spawn_external_process mirrors
  it: when a real execve refusal still reaches it, a rooted,
  opted-in executor spawns this binary on the script instead of
  entering in-process.

Library hosts and fork-copy clones keep the in-process re-entry
unchanged.

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