Skip to content

fix(utf8): stop widening payload bytes in [[ =~ ]] RHS and compound xtrace - #124

Merged
caomengxuan666 merged 2 commits into
unixwin:masterfrom
daiaji:fix/utf8-hygiene-mojibake-sites
Sep 24, 2026
Merged

caomengxuan666 merged 2 commits into
unixwin:masterfrom
daiaji:fix/utf8-hygiene-mojibake-sites

Conversation

@daiaji

@daiaji daiaji commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

Summary

Two executor sites still widened payload bytes with byte as char — the exact failure class scripts/check-utf8-boundary-hygiene.sh documents (Latin-1-encoding multi-byte text, niubash#92). The guard has been red on master for these 12 sites; this PR fixes the 5 real-bug sites and allowlists the 7 reviewed-safe ones, making the guard green again.

Real bugs fixed

  1. conditional.rs regex_rhs_marked_chars — shell_text_to_raw_bytes output is the UTF-8 of the expanded text; widening each byte mojibaked the reassembled [[ =~ ]] RHS. [[ $s =~ "$pat" ]] with a non-ASCII pattern silently failed to match while the identical unquoted form matched. Now decoded with String::from_utf8_lossy so the marked stream carries the same chars as the no-raw-token path. (Invalid byte products degrade to U+FFFD — they could never match a char-mode subject before either.)

  2. prompt_expansion.rs compound_element_xtrace_text — iterated as_bytes(), so set -x traced arr=(中文) as arr=(中文) and the $'…' body handed decode_ansi_c_quoted mojibake. Now iterates chars(); the recognized metacharacters ($, ', ) are ASCII so scan semantics are unchanged.

Allowlisted (reviewed-safe, no behavior change)

  • 5 × is_shell_name_char/start(<wide byte> as char) (arithmetic/value.rs, declare_local.rs, conditional.rs ×2): the predicates are '_' || is_ascii_alphanumeric() — ASCII-only, so a widened ≥0x80 byte can never satisfy them. Same class as the already-listed arithmetic/{expression,factor,lvalue}.rs entries.
  • 2 × bre_substitute slices (alias_helpers.rs): the guard's check-3 flags &text[cursor..], but text is a Vec<char> there — element indexing, no UTF-8 boundary involved.

Tests

New tests/utf8_mojibake_regressions.rs (red before, green after): quoted/unquoted non-ASCII [[ =~ ]] pair + both xtrace shapes. cargo test --locked --lib 438/438; assignment/comsub/marker suites green; check-utf8-boundary-hygiene.sh reports clean.

Note for reviewers

Full --test executor_tests on Windows shows 133 pre-existing failures on master itself (env-sensitive: TZ/printf-time etc.); the failure set is byte-identical with this PR applied — no new failures introduced.

…trace

Two executor sites still widened payload bytes with `byte as char`,
Latin-1-encoding multi-byte text (the failure class behind niubash#92):

- conditional.rs regex_rhs_marked_chars: shell_text_to_raw_bytes output
  is the UTF-8 of the expanded text; widening each byte mojibaked the
  reassembled regex RHS, so `[[ $s =~ "$pat" ]]` with a non-ASCII
  pattern silently failed to match while the unquoted form matched.
  Decode with String::from_utf8_lossy so the marked stream carries the
  same chars as the no-raw-token path (invalid byte products degrade to
  U+FFFD, which could not match a char-mode subject before either).
- prompt_expansion.rs compound_element_xtrace_text: iterate chars()
  instead of bytes() so `set -x` traces arr=(中文) and the $'...'
  decode_ansi_c_quoted body keeps real characters (the recognized
  metacharacters are ASCII, so scan semantics are unchanged).

check-utf8-boundary-hygiene: allowlist the seven remaining reviewed-safe
sites — five is_shell_name_char/start(wide-byte) predicates (the
predicates are ASCII-only, so a widened >=0x80 byte can never satisfy
them; same class as the already-listed arithmetic entries) and two
bre_substitute slices that are Vec<char> indexing, not &str slicing.
The script now reports clean.

New tests/utf8_mojibake_regressions.rs pins the quoted/unquoted =~ pair
and both xtrace shapes (red before the fix, green after).
read_some_on_closed_pipe_returns_eof_shape borrowed the read end with
as_raw_fd and then close_handle'd it while r still owned the fd; the
OwnedFd drop at scope end closed it a second time and std aborts the
whole lib-test process with "fatal runtime error: IO Safety violation:
owned file descriptor already closed". into_raw_fd hands the fd to the
test so the trailing close_handle is the single owner-close.

Surfaced by unixwin#124 making the UTF-8 hygiene step green: with the guard
red on master, the lib-test step had not actually executed in CI.
@daiaji

daiaji commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

测试现在也清掉了。

@daiaji

daiaji commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up push 963dbf0: the CI log of the previous head showed the lib-test step aborting with fatal runtime error: IO Safety violation: owned file descriptor already closed at fd::unix::tests::read_some_on_closed_pipe_returns_eof_shape — a pre-existing double-close (the test borrowed the read end with as_raw_fd, then close_handle'd it while the std::io::pipe File still owned it, and its Drop closed it again at scope end). Latent until now because with the hygiene guard red, the lib-test step never actually executed in CI. Fixed by taking ownership with into_raw_fd so the trailing close_handle is the single owner-close.

With that, this run's Rust tests job is fully green (hygiene clean + lib tests + cross-target + shell functionality), so the PR should be a clean signal end to end.

@caomengxuan666
caomengxuan666 merged commit 5fdbd4c into unixwin:master Sep 24, 2026
4 checks passed
caomengxuan666 added a commit that referenced this pull request Oct 2, 2026
…eopened)

The reopened #124(a) report was `mktemp -p "$d"` failing with template
'""/x.XXXXXX', read as the engine argument translation emptying the -p
path. Byte-level probing established the real mechanism: GNU coreutils
mktemp 8.32 prints exactly `failed to create file via template '""/
x.XXXXXX'` when the -p VALUE arrives as two literal double-quote
characters (`mktemp -p '""' x.XXXXXX`, reproduced), i.e. a host->shell
argv boundary quote collapse upstream of the engine — the same Winuxsh
host-boundary artifact family as the C:// repair
(repair_windows_drive_slash_argument). On current master the engine
never empties or quote-leaks a path operand: a two-shell argv matrix
(target/issue-suites/results/issue-niubash124/) covering mktemp -p /
--tmpdir= / -p attached, tar -C/-o/--directory=, cp/mv operands x
existing/missing targets x POSIX/Windows/relative forms x comsub
round-trips shows every value arriving whole (installed niu 1.2.4, dev
build, and this worktree; no empty and no `"` byte at any child).

GNU hands argv verbatim to execve (execute_cmd.c:6126 shell_execve);
the Windows adaptation may translate path-shaped operands to drive form
but must never drop or quote-corrupt them. This pins that invariant for
the whole class so a regression to empty/quoted values fails loudly.
The matrix also records the known existence-gated half-translation
(existing target -> X:\ form, missing target -> POSIX passthrough),
which can hand one command a mixed-dialect argv — that is the #124(b)
design question (rubash#359) and is deliberately unchanged here.

cargo test --lib: 554/554; RUSTFLAGS=-D warnings build clean; fmt clean.

wt36/pathfix lane.
caomengxuan666 added a commit that referenced this pull request Oct 2, 2026
… B stage 1/2)

Option B per-child dialect model (MSYS model), owner-approved design from
the wt35/wt36 lanes (niubash#124(b), rubash#359). GNU never rewrites
argv: execute_cmd.c:6119-6127 shell_execve() hands execve the raw word
bytes and the ENOEXEC re-entry (execute_cmd.c:6240-6250) likewise hands
the child shell the words verbatim. On Windows the engine previously
translated path-shaped operands for EVERY external child, gated on
filesystem existence -- so one argv could arrive as D:\a + /d/b mixed
dialect (the #124(b) report class; A/B reproducer: `printf "<%s>\n"
/d/optb-probe /d/missing-probe` under a WinuxCmd-resolved printf prints
<D:\optb-probe> + </d/missing-probe> on 69f0934, both verbatim after
this change).

Stage 1 (this commit): a POSIX-aware child -- one that resolves the
shell's POSIX namespace itself -- now joins the verbatim-argv set
alongside command processors and shell-wrapped scripts. Detection
(posix_aware_child, path.rs):
  1. is_winuxcmd_dispatcher(program): the winuxcmd dispatcher route
     (PATH-miss names resolved through the `winuxcmd help NAME` probe).
  2. program under the env-configured WinuxCmd installation root:
     WINUXCMD_HOME (set by Executor::set_winuxcmd_path) or the root
     derived from find_winuxcmd_dispatcher via
     winuxcmd_installation_root_from_path; case/separator-insensitive
     component prefix match.
  3. under_winuxcmd_tree marker probe (memoized per path): derive the
     candidate root from the resolved program's own tree and confirm it
     with usr/bin/winuxcmd.exe or winuxcmd.exe -- covers WinuxCmd
     installations reached through PATH without env configuration.
     This classifies a program's dialect; it does NOT select a
     dispatcher (find_winuxcmd_dispatcher stays env-configured only).

Escape hatch: __RUBASH_ARGV_DIALECT=legacy restores the pre-Option-B
behavior for field rollback (argv_dialect_legacy); default is Option B.

Verification (WSL GNU Bash 5.3.0 = sole baseline):
- p124matrix class matrix (tools x existing/missing x POSIX/Windows/
  relative x comsub round-trip, both dialect lanes):
  target/issue-suites/results/issue-niubash124/optionb/ -- POSIX-aware
  lane 8/8 uniform, argv byte-verbatim (GNU oracle (case,form) triples
  identical, rubash prints /d/... verbatim in every case); native lane
  still shows the 3 known MIXED cases (existence-gated half-translation,
  stage 2's target).
- cargo test --lib 564/564 (4 new unit tests for the detection routes,
  escape hatch, marker probe); cli parity with master (same pre-existing
  env failures only: 3 bashdb + 1 shopt text, verified on main worktree).
- focused true-baseline suites byte-identical to the 69f0934 A ledger:
  builtins 0, coproc 6, errors 2, invocation 8, new-exp 4, read 2,
  redir 0, type 6.
caomengxuan666 added a commit that referenced this pull request Oct 4, 2026
…ing (niubash#177)

Root cause: after the wt60 root-map translation, an operand like
/usr/bin/seq reached children as the plain translated Windows path
(<WINUXSH_ROOT>\usr\bin\seq). The WinuxCmd tree stores applets as
seq.exe, so every FILE operand failed (head -1 /usr/bin/seq rc=1,
wc -l < /usr/bin/seq rc=1, cat /usr/bin/cat | wc -c -> 0,
ls /usr/bin/seq rc=2) while .exe-spelled forms worked and
`test -f /usr/bin/seq` answered YES — the internal lookup
(shell_path_to_windows_for_lookup -> executable_candidate) already
resolved the executable extension, so one namespace had two
contradictory views.

GNU is verbatim (execute_cmd.c:6128 shell_execve passes argv to
execve untouched; redir.c:675/702 redir_open opens the expanded
filename without rewriting). The .exe bridge is the Windows POSIX
layer's job: MSYS resolves an absent as-spelled name to the existing
<name>.exe at its Win32 boundary (live probe 2026-10-02: Git Bash's
MSYS head.exe opens D:\...\usr\bin\seq with only seq.exe on disk).
WinuxCmd applets have no such runtime layer, so the translation layer
must hand out the resolved spelling itself.

New windows_operand_file_path (src/executor/path.rs) applies the MSYS
open/exec order, existence-checked both ways:
1. as-spelled exists (file or directory): handed out verbatim — a
   directory is never swapped for a coincidental .exe sibling;
2. else the shell's own candidate set (executable_candidate, the same
   PATHEXT resolution test/hash/PATH lookup apply) picks the first
   existing spelling;
3. else the as-spelled form stands — never a blind append; children
   error on the original spelling exactly as before.

Wired at every read-side operand consumer so the namespace view is
one: the argv funnel (translated_virtual_system_root_argument), the
input-redirect funnel (open_input_redirect_impl), the in-process cat
readers (external_cat, pipeline cat stage, command-substitution cat
fast paths), the read builtin (read_io, read_redirected_fd, -t probe),
mapfile, and the compound fd-0 input opens/probes in
command_input_scope. Directory operands keep working with no suffix
appended; /dev/* stays verbatim (rubash#120), "/" stays operand
(niubash#153), drive forms stay per-child dialect (niubash#62/#124(b)),
__RUBASH_ARGV_DIALECT=legacy is unaffected.

Output-path FORM (ls -d /usr/bin prints the translated Windows path
where GNU prints /usr/bin) is a separate stdout display concern,
deliberately out of this change; noted as follow-up.

Tests: path.rs unit family (exe-resolve, dir-wins-over-exe,
missing-keeps-spelling, Option-B/legacy verbatim guards) + hermetic
CLI regressions tests/issue177_virtual_root_operand_exe_resolution.rs
(read redirect, comsub cat, argv funnel via cmd /c echo, test -f
consistency). Behavior matrix vs WSL GNU bash 5.3.0: 36 cells green,
artifacts under target/issue-suites/results/i177/ (matrix-gnu.out,
matrix-rub.out, matrix-diff.txt, rub-only.out); one wording-level
note (wc -c < dir: both rc=1, GNU's wc prints 0 after open-succeeds).
Gates: cargo build 0 warnings; cargo test --lib 584 green (baseline
581); RUSTFLAGS=-Dwarnings clean; cargo fmt --check clean; cli_tests
467 passed with only master's pre-existing 6 failures (5 bashdb,
1 shopt).
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