Repository navigation
fix(executor): count decoded bytes in the inline wc fast path (#383) - #695
Conversation
The inline `wc` pipeline stage measured TRANSPORT text instead of the payload. Carrier bytes (0x1B/0x0C/...) travel as U+E000+U+E0xx marker pairs, so `printf '\033' | wc -c` reported 6 instead of 1, and the issue report's `\033[31mX\033[0m` payload reported 20 instead of 10. - `-c` and the flagless byte field now decode via shell_text_to_raw_bytes, the same boundary the external wc child-stdin write uses. - `-w` and the flagless word field decode to visible text first, so a carrier-encoded whitespace byte (0x0C) still delimits words. - `-l` needs no decode: 0x0A is not a carrier byte. - The `$( ... | wc -c )` arm gets the same byte-count fix. Refs unixwin/niubash#383 (NOT unixwin/WinuxCmd#383, which is a `date` issue): WinuxCmd's external wc is correct; the defect is the shell's inline fast path.
c4051d8 to
b18a146
Compare
Map every rubash in-process fast path against its WinuxCmd fallback and GNU coreutils at the byte level, with a repeatable Python harness. Inventory: 12 pipeline-stage arms (pipeline_exec.rs), 8 command-substitution filter arms (command_substitution_values.rs), the documented sleep/dirname/ basename/uname/arch behaviours, and in-process env. Confirmed rubash fast-path divergences, filed as #707 (tr [:cntrl:]), #708 (head flag parsing), #709 (dirname/basename // and empty operand), #710 (command_substitution_values.rs arms unreachable); WinuxCmd#1196 (true, dirname ///). The wc carrier class is already tracked (niubash#383 / PR #695); the dirname /a/b -> A: translation is niubash#346 (fixed by rubash#649). Harness: scripts/fast-path-differential.py (180 cases, FAST vs absolute WinuxCmd vs GNU; exits non-zero on regression or a known case going green).
caomengxuan666
left a comment
There was a problem hiding this comment.
Independent adversarial review, detached worktree at b18a146f (merge-base/origin/master = 8f596779). Everything below was reproduced locally: cargo build --bin rubash in a clean worktree, GNU references D:/Git/usr/bin/wc.exe (coreutils 8.32) and WSL bash 5.3.0 (coreutils 9.4). I did not take the PR body on trust.
blocking — -w (and the flagless words field) now panics on a literal 0x11 byte
The new -w arm routes the payload through crate::locale::decode_to_visible_text(input). That function is a decoder for shell-internal text and asserts its post-condition that no internal carrier survives (src/locale.rs:545):
debug_assert!(!out.contains(CTLESC), "CTLESC leaked to output");A piped payload byte 0x11 decodes to U+0011, which is CTLESC (src/executor/markers.rs:69), so the assertion fires:
$ rubash -c "printf '\021' | wc -w"
thread 'rubash-main' panicked at src\locale.rs:545:9:
CTLESC leaked to output
...
2: rubash::locale::decode_to_visible_text
at .\src\executor\pipeline_exec.rs:3183
at .\src\executor\pipeline_exec.rs:2534
$ rubash -c "printf '\021' | wc" # same panic (words field)
$ rubash -c "printf '\021' | wc -c" # 1, unaffected
$ rubash -c "printf '\021' | command wc -w" # 1, external, no panic
This is introduced by this PR — origin/master used input.split_whitespace() on the transport and never called the decoder (git show origin/master:src/executor/pipeline_exec.rs → -w => input.split_whitespace().count()).
debug_assert! is compiled out under the release profile (no debug-assertions override in Cargo.toml), so a shipped binary does not panic — but it still counts 0x11 as a word where GNU 8.32 prints 0. Every debug build, cargo test, and debug-built niu panics on ordinary input (any 0x11/XON byte in a binary stream). The new test file does not cover 0x11. The -c/-l arms are fine; only the decoder chosen for -w is unsafe for bare payload bytes. Counting words over shell_text_to_raw_bytes(input) (or a payload-safe decoder) would avoid both the panic and the assertion at its source.
non-blocking — -w counts "any non-whitespace run"; GNU 8.32 counts "printable runs"
The PR marks -w "fixed". It is fixed for carrier-encoded whitespace (printf 'a\014b' | wc -w → 2, matches GNU), but a decoded split_whitespace() differs from the stated reference (wc.exe 8.32) whenever a run contains no printable character:
$ rubash -c "printf '\033' | wc -w" => 1 D:/Git/usr/bin/wc.exe -w => 0
$ rubash -c "printf '\001' | wc -w" => 1 GNU => 0
$ rubash -c "printf '\177' | wc -w" => 1 GNU => 0
$ rubash -c "printf '\033\033' | wc" => 0 1 2 GNU => 0 0 2
GNU ≤9.4 (iswprint/isprint gate in wc.c) counts 0 here; current GNU (9.11) source switched to the non-whitespace rule, so this may match newer GNU/POSIX — worth an explicit decision, but the "-w fixed" claim is broader than what it does. In kind this is pre-existing (master also printed 1) and the PR strictly improves it (the 0x0C/0x09 cases now match), so I would not block on it.
non-blocking — the $( … | wc -c ) arm that was changed is unreachable
command_substitution_pipeline_filter (whose -c arm was changed) is called only from command_substitution_pipeline_output, which is called only from timed_command_substitution_inner, which is called only from timed_command_substitution_output, which bails unless the first word is time — and all of these sit after the "trivial body" gate:
// command_substitution.rs:793, before the word-level dispatch
if !command_substitution_body_is_trivial(&word_source) || self.xtrace_enabled() { … return }
// command_substitution.rs:2217: rejects '|' (0x7C) and every quote/expansion byteAny body containing | is therefore non-trivial and goes to the real executor; the wc arm can never be reached. The new test command_substitution_byte_count ($(printf '\033' | wc -c)) passes via the inline pipeline arm, not the changed comsub arm, so it does not validate this hunk. The change is harmless and consistent, but the claim/test coverage is inaccurate. ($(time printf '\033' | wc -c) does exercise the file only under the time body; it returns 1.)
verified-ok — -c and the flagless bytes field count decoded bytes (matches GNU)
Differential sweep, rubash-inline vs GNU (via a Git-for-Windows driver so command wc = GNU 8.32): 258 payloads over {ESC, FF, TAB, LF, 'a', ' ', 0xCD, 'b'} × {-c, -l, default} produced zero mismatches in the -c/-l/default columns except the -w rule above. Single-byte sweep 0x01..0x1F,0x7F,0x80,0xCD,0xE9,0xFF all count 1 (od confirms). \033[31mX\033[0m → 10, \x1b[0m → 4, \033\033\033 → 3, all matching GNU. Multi-stage (printf … | cat | wc -c, … | tr a b | wc -c) → 10.
verified-ok — shell_text_to_raw_bytes is the right helper, and the stated reason for rejecting decode_to_visible_text for -c is real
decode_to_visible_text maps a raw-byte marker pair to char::from_u32(byte) (src/locale.rs:416), so 0xCD → U+00CD, UTF-8 = 2 bytes — exactly the reason given. shell_text_to_raw_bytes(input) is byte-identical to the child-stdin sink the external stage uses (pipeline_stages.rs:901 stdin.write_all(&payload)), so inline -c == external -c by construction. Line -l needs no decode (0x0A is not a carrier) and is byte-for-byte unchanged.
verified-ok — the "already correct" arms and the fallbacks
-m, -lc/-cl/-w -c, --bytes, -L and file operands all return through execute_external_pipeline_stage and match D:/Git/usr/bin/wc.exe byte-for-byte:
wc -m => 10 | gnu 10 wc -lc => 0 10 | gnu 0 10
wc -L => 8 | gnu 8 wc --bytes => 10 | gnu 10
wc -c FILE => 4 | gnu 4 wc FILE => 0 1 4 | gnu 0 1 4
verified-ok — no other fast path in the file has this defect
Only three "wc" arms exist (main.rs:1450 --internal-wc counts \n over real stdin bytes; the two changed here). Grepping the inline dispatch (pipeline_exec.rs:2900-3500) shows the only transport-length computations are in the wc arm. external_setup.rs:1170 input.len() is a Vec<u8> snapshot (input_snapshot_bytes). external_file_builtins.rs:1412/1661 are &[u8]. The inline cat identity is a pass-through by design.
fd-0 cursor sites — I disagree with the stated mechanism (but agree there is no carrier-specific repro)
I agree the three sites (pipeline_stages.rs:905, pipeline_exec.rs:1890/2262) are harmless in practice, but not for the stated reason. FUNCTION_STDIN_OFFSET is a transport-byte offset, not a raw-payload offset: read_function_stdin advances it by ch.len_utf8() over the transport slice (read_io.rs:751), and function_stdin_remaining slices transport bytes (shell_options.rs:870 input[offset..]). So input.len() is in the cursor's own units and correctly marks end-of-chunk; the real approximation is "an external child consumed the whole stage input", which is independent of carrier bytes. The shared-fd0 divergences I could find reproduce with pure-ASCII input and are a separate inline-consumption approximation, e.g.
$ printf 'abc\ndef\nghi\n' > f
$ rubash -c '{ head -n1; read -r x; echo "R=[$x]"; } < f' # R=[] GNU: R=[def]
tests / fmt
cargo fmt --check # clean (exit 0)
cargo test --test issue383_inline_wc_transport_bytes # 9 passed
cargo test --test issue166_tr_pipeline_options # 6 passed
cargo test --test issue165_cat_pipe_reader_options # 12 passed
cargo test --test issue177_virtual_root_operand_exe_resolution # 4 passed
cargo test --test issue158_pipeline_drain_deadlock # 5 passed
cargo test --test comsub_nonascii_span_regressions # 10 passed
cargo test --test decode_to_visible_text # 3 passed
cargo test --lib inline_tr_tests # 2 passed
Rebase is behaviour-neutral: single commit on top of 8f596779; the three preceding master commits touched only CHANGELOG.md and three test files, none of which this PR touches.
Recommendation: the -c fix is solid and thoroughly correct; the -w decoder choice is the problem. I would fix the -w/flagless arm to avoid decode_to_visible_text (panic in debug, miscount in release) before merging.
|
Fix for review R1, final state (commits 3362e53 + ad81e6f, note the intermediate push was incomplete):
|
…3) (#706) * docs(audit): fast-path differential catalogue and harness (niubash#383) Map every rubash in-process fast path against its WinuxCmd fallback and GNU coreutils at the byte level, with a repeatable Python harness. Inventory: 12 pipeline-stage arms (pipeline_exec.rs), 8 command-substitution filter arms (command_substitution_values.rs), the documented sleep/dirname/ basename/uname/arch behaviours, and in-process env. Confirmed rubash fast-path divergences, filed as #707 (tr [:cntrl:]), #708 (head flag parsing), #709 (dirname/basename // and empty operand), #710 (command_substitution_values.rs arms unreachable); WinuxCmd#1196 (true, dirname ///). The wc carrier class is already tracked (niubash#383 / PR #695); the dirname /a/b -> A: translation is niubash#346 (fixed by rubash#649). Harness: scripts/fast-path-differential.py (180 cases, FAST vs absolute WinuxCmd vs GNU; exits non-zero on regression or a known case going green). * fix(audit): per-process fixtures, toolchain preflight, locale pin (PR #706 review) B1: fixtures now live in a per-PID scratch dir created with mkdtemp, cleaned in a finally, with an integrity gate and a stderr-empty guard on the fixture-backed cat cases so a fixturing error can never be recorded as FAST/EXT agreement. B2: the comparison contract now reads stdout + exit status, with stderr compared only for the four diagnostic cases (stderr=True) and asserted empty for the fixture cases; Appendix A gains a stderr column. grep_utf8_i pins LC_ALL=C/LANG=C for all three legs, removing the console-locale nondeterminism (under C none of the installed legs fold). Cheap fixes: missing NIU/WX_BIN is a fatal exit-2 diagnostic (--no-ext opts out explicitly and is recorded in the run header); --only with no match exits 1; the duplicate dirname_letter case is removed. Totals re-synced: cases=179 pass=146 known=27 extbugs=2 info=4 regressions=0 fixed=0. --------- Co-authored-by: audit-bot <[email protected]>
The shared fd 0 cursor (FUNCTION_STDIN_OFFSET) is a byte index into the shell's transport text: read_function_stdin, function_stdin_remaining and select all slice the same buffer with it. The pipeline drivers therefore advance it by the transport length they handed the external child (pipeline_stages.rs `input.len()`, pipeline_exec.rs `stage0_input.len()`), never by shell_text_to_raw_bytes(..).len(): a raw delta under-advances by the carrier overhead and replays bytes the child already consumed. This is the unit-twin of #695 / unixwin/niubash#383. There a byte count handed to the user had to be raw; here an index into transport text must be transport, so the three audited sites are correct as written. Document the invariant and add regression tests that fail if a future sweep converts them to raw units.
Attribution
Fixes unixwin/niubash#383 —
Winuxcmd \wc -c` miscounts ESC (0x1B) on piped stdin`.This is not
unixwin/WinuxCmd#383. That WinuxCmd issue is adate(savannah#25406) issue. The issue you are reading is labelled
Winuxcmd-bugonly because the reporter watched the bundled coreutils; WinuxCmd's external
wcis correct —src/commands/wc.cppsets stdin to binary mode and countsgcount()verbatim. The defect is entirely in rubash's in-process inlinepipeline fast path, which hands
wcthe shell's transport text (carrierbytes such as 0x1B/0x0C are stored as
U+E000 + U+E0xxmarker pairs,locale.rs:352) and then measures that encoding.Verification of the blame split (
printf '\033[31mX\033[0m'is the report'spayload):
Typo note
The report's minimal repro (
printf '\x1b[0m') is a 4-byte payload, and9there is the buggy inline count (4 + 5), not the expected value. The\033[31mX\033[0mpayload used to describe the rule is 10 bytes, not 9;the inline path reported 20 (10 + 2×5) for it. The
+5 bytes per ESCruleitself is exact.
The fix
wcbyte counts must count the bytes the externalwcwould actuallyreceive; word counts must count words over visible text. The canonical
transport→payload boundary already exists:
substitution_metadata::shell_text_to_raw_bytes— the exact byte sink usedfor child stdin (
pipeline_stages.rs:901,command_substitution_values.rs).Used for byte counts.
locale::decode_to_visible_text— the sanctioned transport→visible decoder(
locale.rs:369). Used for word counts.I chose
shell_text_to_raw_bytes(...).len()for bytes rather thandecode_to_visible_text(...).len(): the latter maps a raw byte to acharvia
byte_char, so a high byte such as 0xCD becomes U+00CD and UTF-8-encodesto 2 bytes — wrong for
-c. There is no allocation-free length helpertoday, so the canonical decoder is the cheapest correct option.
Arms checked (inline
wc,pipeline_exec.rs)-c.len()bytes-c-wsplit_whitespace(); 0x0C is both a carrier and whitespacewords-w-l\ncounting is unaffectedlines-m-lc, combined flags--bytes,-L,--words, file operandsArms checked (
command_substitution_values.rs,$( ... | wc ... ))-c-l-l)None→ full execution pathBefore / after
command wc)printf '\033' | wc -cprintf '\033[31mX\033[0m' | wc -cprintf '\033[0m' | wc -cprintf '\033\033\033' | wc -cprintf '\033' | wc(default)0 1 60 1 10 1 1printf 'a\014b' | wc -wecho "$(printf '\033' | wc -c)"Sweep for the same mistake
Grepped the inline pipeline executor and the command-substitution arms for
input.as_bytes().len()/input.len()/ transport-text-as-payload. Honestinventory:
Fixed: the four arms above.
Not a bug —
external_setup.rs:1170input.len().to_string():inputthere is aVec<u8>raw snapshot, already bytes.Not a bug — inline
catidentity passthrough keeps transport textas-is by design (downstream stages decode); it does not measure a
payload length.
Not a bug found — inline
grep/sed/tr/head/tail/sort/uniqconsume transport text but do not compute a payload byte length; no
byte-count defect was demonstrable.
Unresolved, deliberately not fixed — the stdin-consumption cursor is
also set from transport length while the actual payload is raw bytes:
pipeline_stages.rs:905self.pipeline_stdin_consumed.set(Some(input.len()))(payload at 901 is
shell_text_to_raw_bytes(input));pipeline_exec.rs:1890and2262(base + stage0_input.len())forFUNCTION_STDIN_OFFSET(payload written viashell_text_to_raw_bytes).This is the same over-count class, but it only drifts rubash's internal
fd-0 cursor for a later
read/shared-stdin consumer; I could not constructa user-visible reproduction, and the brief says not to fix anything I cannot
demonstrate. Reporting it here instead of guessing. (
-c/-ware theuser-visible outputs; those are fixed.)
Tests
New:
tests/issue383_inline_wc_transport_bytes.rs(9 tests) — control-bytesweep (0..3 → 0..3), the
ESC [ 3 1 m X ESC [ 0 m→ 10 case, the issue's\x1b[0m→ 4 repro, flagless default, the$( ... | wc -c )arm, theform-feed word-count case,
-l, the-m/-lcexternal fallback pins, and anASCII no-regression case.
cargo fmt --checkclean.Left alone deliberately
wcis correct and its [bug] posix round-trip stickiness: 'set -o posix' enables inherit_errexit but 'set +o posix' never resets it (GNU 5.3 keeps it sticky; rubash never flips it at all) #383 is adateissue.
--helpgenerator (owned by the parallelfix/382-option-clusterwork).