Skip to content

fix(comsub): keep fragment bytes byte-exact through field materialization (niubash#92 follow-up) - #104

Merged
caomengxuan666 merged 3 commits into
masterfrom
fix/issue-92-comsub-multibyte-fragments
Sep 15, 2026
Merged

caomengxuan666 merged 3 commits into
masterfrom
fix/issue-92-comsub-multibyte-fragments

Conversation

@caomengxuan666

@caomengxuan666 caomengxuan666 commented Sep 14, 2026 •

Copy link
Copy Markdown
Member

Summary

Follow-up to the substitution_metadata.rs char-boundary panic fix tracked in unixwin/niubash#92. The panic itself is already fixed on master (&raw[cursor + 1..] → &raw[chars[cursor].0 + inner.len_utf8()..]), but auditing the same byte/char-confusion class surfaced five live defects:

  1. split_expanded_fragments accumulated field text into a String via current.push(*byte as char), so a quoted multibyte literal adjacent to $(...) was Latin-1-widened into mojibake: echo "中文$(echo h)"$(echo x) printed 中文hx instead of 中文hx.
  2. The IFS-whitespace skip ignored fragment.splittable, so quoted literal text lost spaces whenever the word was split-eligible: echo "a b$(echo h)"$(echo x) printed abhx instead of a bhx.
  3. lexer/mod.rs scan_line_for_comsub_heredoc_headers widened each byte with bytes[i] as char, so a heredoc delimiter char whose UTF-8 contains a 0x85/0xa0 continuation byte (悠 = U+60A0, the U+E0A0 powerline glyph, ...) satisfied is_whitespace mid-char and &line[start..index] panicked — reachable via x=$(cat <<E悠F ... ). The \ escape skip and catch-all step also advanced raw bytes, so consumed could carry a mid-char offset into the caller's &logical_line[header_scan_from..] slice.
  4. main.rs read_unbuffered_line widened piped script source byte-wise (printf 'echo 中文' | rubash printed mojibake), and the read builtin's process-stdin paths (read_stdin_until, read_inherited_process_stdin) did the same — read -n1 returned a mangled lead byte and left the rest of the character unread, and -d could match a delimiter mid-sequence.
  5. arithmetic strip_arith_double_quotes rebuilt its &str via byte as char, mangling multibyte operand text in diagnostics ($(( "中" + 1 ))).

Changes:

  • split_expanded_fragments accumulates field text as raw bytes and materializes each field through bytes_to_shell_text — the same UTF-8/raw-byte-marker contract the NoSplit path already uses; the whitespace skip is gated on fragment.splittable.
  • The comsub heredoc header scan decodes the current char at each position (boundary-safe by construction); \ escapes step over the escaped char's full UTF-8 length, and consumed is always a char boundary.
  • New shared StdinCharDecoder (read_helpers) decodes byte-wise stdin reads into whole UTF-8 chars, keeps byte-read counts exact for fd-offset bookkeeping, and emits raw-byte markers for undecodable bytes so read round-trips e.g. a lone 0x80 like GNU.
  • read_unbuffered_line buffers line bytes and decodes once via bytes_to_shell_text, now exposed as rubash::executor::bytes_to_shell_text so embedders (niubash) can decode source bytes identically.
  • strip_arith_double_quotes walks chars() instead of bytes.
  • New scripts/check-utf8-boundary-hygiene.sh, wired into CI: fails on unreviewed X as char widenings, on widened bytes reaching non-ASCII-capable char predicates (is_whitespace/is_control/... — the continuation-byte false-positive behind defect 3), and on &str slices at char-position counters. Audited-safe sites (ASCII compares, drive letters, digit math, GNU-equivalent byte semantics) are pinned in an in-script allowlist keyed by file + line content; verified against reintroduced copies of all three bug shapes.
  • Regressions in tests/comsub_nonascii_span_regressions.rs (9 tests) and new tests/stdin_multibyte_regressions.rs (5 CLI-level tests piping multibyte/invalid bytes).

Test plan

  • cargo test --lib — 388/388; comsub_nonascii_span_regressions 9/9; stdin_multibyte_regressions 5/5
  • Issue-92 trigger matrix + assignment/export/local/nested/backtick/array/IFS variants byte-identical to WSL GNU bash 5.3.0
  • read/arith/arith-for true-baseline output byte-identical to the pre-change tree (all residual diffs pre-exist); heredoc 0 diffs; comsub* unchanged
  • Guard script clean on this tree; catches reintroduced as char widening, is_whitespace-on-widened-byte, and &s[cursor + 1..] patterns
  • niu -c on niubash pinned to this branch: full matrix exit 0 with correct UTF-8

Generated with Devin

…tion

Follow-up to the char-boundary panic fix (niubash#92): on the
literal+substitution fragment path, split_expanded_fragments still
widened every fragment byte with `byte as char`, so a quoted CJK
literal followed by another $(...) printed Latin-1 mojibake
("中文$(echo h)"$(echo x) -> 中文hx instead of 中文hx), and
IFS whitespace inside non-splittable literal fragments was dropped
("a b$(echo h)"$(echo x) -> abhx instead of a bhx).

- accumulate field text as raw bytes and materialize through
  bytes_to_shell_text at each field boundary (UTF-8 decode + raw-byte
  marker encoding, same contract as the NoSplit path)
- gate the IFS-whitespace skip on fragment.splittable so literal text
  keeps its bytes verbatim; only expansion output is field-split
- regression tests: CJK adjacent to $( in the same word (panic
  matrix), quoted-fragment byte fidelity, quoted whitespace survival

Verified against WSL GNU bash 5.3.0 script-file probes; comsub*
true-baseline diff counts unchanged (39/72/15/0 before and after).
Same byte/char-boundary class as the substitution_metadata panic, one
subsystem over: scan_line_for_comsub_heredoc_headers widened each byte
with `bytes[i] as char`, so a continuation byte 0x85/0xa0 inside a
multibyte delimiter char (悠 = U+60A0, U+E0A0 powerline glyphs, ...)
satisfied char::is_whitespace, ended the delimiter word mid-char, and
`&line[start..index]` panicked. The `\` escape skip and the
catch-all step also advanced raw bytes, so `consumed` could carry a
mid-char offset into the caller's `&logical_line[header_scan_from..]`.

Probe: `x=$(cat <<E悠F\nhi\nE悠F\n); echo "$x"` panicked with
"end byte index 13 is not a char boundary; it is inside '悠'" and now
prints hi, matching WSL GNU bash 5.3.0. Escaped delimiter chars
(`<<E\悠F`) step over the whole char as well.

- decode the current char via char_indices-equivalent slicing; every
  scan position stays a char boundary
- escape steps skip the escaped char's full UTF-8 length
- catch-all advances by char len so `consumed` stays a byte boundary
- regressions: multibyte / 0xa0-continuation / escaped-multibyte
  heredoc delimiters inside $(...)

Verified: heredoc suite 0 diff lines vs GNU 5.3.0 (true-baseline.sh);
comsub* diff counts unchanged; lexer_tests/operator/comment suites
unchanged (3 lexer_quote_tests failures are pre-existing on master).
caomengxuan666 pushed a commit to unixwin/niubash that referenced this pull request Sep 14, 2026
rubash 0e9d2e5d (unixwin/rubash#104, second commit) fixes the same
char-boundary class in the lexer's comsub heredoc header scan: a
multibyte delimiter char whose UTF-8 contains a 0x85/0xa0 continuation
byte (e.g. U+60A0 悠) panicked at lexer/mod.rs when the heredoc sat
inside $(...).

Verified: niu -c 'echo "中文$(echo h)"$(echo x)' -> 中文hx;
x=$(cat <<E悠F..) prints hi.
…ne guard

Extends the niubash#92 fix to the remaining byte/char boundary hazards of
the same class found while auditing every `as char` site in src/:

- main.rs read_unbuffered_line accumulated script-source bytes into a
  String via `bytes[0] as char`, Latin-1-mangling multibyte input piped to
  `rubash` (`printf 'echo 中文' | rubash` printed mojibake). It now buffers
  the line as bytes and decodes through executor::bytes_to_shell_text, the
  same raw-byte-marker contract used by substitution materialization; that
  helper is now exposed as rubash::executor::bytes_to_shell_text so
  embedders (niubash) can decode source bytes identically.
- read builtin stdin paths (read_stdin_until, read_inherited_process_stdin)
  widened each byte with `as char`, so `read -n1` returned a mangled lead
  byte and left the rest of the character unread, and -d could match a
  delimiter mid-sequence. A shared StdinCharDecoder now decodes complete
  UTF-8 characters, keeps byte-read counts exact for fd offsets, counts
  units per character or raw byte, and emits raw-byte markers for invalid
  input so `read` round-trips lone bytes like 0x80.
- arithmetic strip_arith_double_quotes rebuilt its &str via `as char`,
  mangling multibyte operand text in diagnostics; it now walks chars().

Also adds scripts/check-utf8-boundary-hygiene.sh, wired into CI: a source
audit that fails on unreviewed `as char` widenings, on widened bytes
reaching non-ASCII-capable char predicates (is_whitespace & friends — the
continuation-byte false-positive mechanism behind the lexer panic), and on
&str slices at char-position counters. Audited-safe sites are pinned in an
in-script allowlist keyed by file plus line content.

Verification: lib tests 388/388, comsub_nonascii 9/9, new
stdin_multibyte_regressions 5/5; read/arith/arith-for GNU baseline output
byte-identical to the pre-change tree (all residual diffs pre-exist);
guard script verified against reintroduced copies of all three bug shapes.
@caomengxuan666
caomengxuan666 merged commit be55da1 into master Sep 15, 2026
2 of 3 checks passed
@caomengxuan666
caomengxuan666 deleted the fix/issue-92-comsub-multibyte-fragments branch September 16, 2026 03:47
arookieofc pushed a commit to arookieofc/winuxsh that referenced this pull request Sep 22, 2026
Fixes unixwin#92: multibyte characters adjacent to $( in the
same word (echo "中文$(echo h)") panicked in rubash 1.1.0's
scan_substitution_spans (`&raw[cursor + 1..]` used a char index as a
byte offset) and exited 127. The panic fix already landed on rubash
master, and the existing unixwin#94 pin (5e08f5dc) carries it, but the same
fragment path still Latin-1-widened literal bytes into mojibake
("中文$(echo h)"$(echo x) -> 中文hx) and dropped IFS whitespace
inside quoted literals ("a b$(echo h)"$(echo x) -> abhx).

Bump the [patch.crates-io] pin to rubash b9d641ae (unixwin/rubash#104),
which makes split_expanded_fragments accumulate field text as bytes and
materialize through bytes_to_shell_text, and restricts the whitespace
skip to splittable expansion output.

Verified: issue trigger matrix on target/debug/niu.exe -c -- every case
exits 0 with correct UTF-8 output; cargo test --workspace --locked and
cargo fmt --check -p niubash pass.
arookieofc pushed a commit to arookieofc/winuxsh that referenced this pull request Sep 22, 2026
… pin

run_stdin_script's byte-wise read_unbuffered_line pushed each byte into a
String via `bytes[0] as char`, Latin-1-widening any multibyte script text
(`printf 'echo 中文' | niu` printed mojibake) — the same bug class as
unixwin#92, host side. It now buffers the line as bytes and decodes
through rubash::executor::bytes_to_shell_text, the raw-byte-marker contract
exposed by unixwin/rubash#104. print_locale_strings (-D/--dump-strings)
had the same widening when collecting $"..." contents; it now walks chars.

Also bumps the temporary rubash pin to rubash#104 head fe165786, which
carries the matching rubash-side stdin/read fixes (read -n now consumes a
whole UTF-8 char from process stdin; rubash's own read_unbuffered_line and
strip_arith_double_quotes no longer widen bytes).
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.

2 participants