Skip to content

fix(executor): count decoded bytes in the inline wc fast path (#383) - #695

Merged
caomengxuan666 merged 3 commits into
masterfrom
fix/383-inline-wc-transport-bytes
Oct 17, 2026
Merged

caomengxuan666 merged 3 commits into
masterfrom
fix/383-inline-wc-transport-bytes

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

Attribution

Fixes unixwin/niubash#383 — Winuxcmd \wc -c` miscounts ESC (0x1B) on piped stdin`.

This is not unixwin/WinuxCmd#383. That WinuxCmd issue is a date
(savannah#25406) issue. The issue you are reading is labelled Winuxcmd-bug
only because the reporter watched the bundled coreutils; WinuxCmd's external
wc is correct
— src/commands/wc.cpp sets stdin to binary mode and counts
gcount() verbatim. The defect is entirely in rubash's in-process inline
pipeline fast path, which hands wc the shell's transport text (carrier
bytes such as 0x1B/0x0C are stored as U+E000 + U+E0xx marker pairs,
locale.rs:352) and then measures that encoding.

Verification of the blame split (printf '\033[31mX\033[0m' is the report's
payload):

$ printf '\033[31mX\033[0m' | od -c
033 [ 3 1 m X 033 [ 0 m          # 10 bytes
$ printf '\033[31mX\033[0m' | wc.exe -c     # external WinuxCmd / GNU: 10
$ printf '\033[31mX\033[0m' | command wc -c # external: 10
$ printf '\033[31mX\033[0m' | wc -c         # inline fast path, before: 20

Typo note

The report's minimal repro (printf '\x1b[0m') is a 4-byte payload, and
9 there is the buggy inline count (4 + 5), not the expected value. The
\033[31mX\033[0m payload used to describe the rule is 10 bytes, not 9;
the inline path reported 20 (10 + 2×5) for it. The +5 bytes per ESC rule
itself is exact.

The fix

wc byte counts must count the bytes the external wc would actually
receive; 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 used
    for 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 than
decode_to_visible_text(...).len(): the latter maps a raw byte to a char
via byte_char, so a high byte such as 0xCD becomes U+00CD and UTF-8-encodes
to 2 bytes — wrong for -c. There is no allocation-free length helper
today, so the canonical decoder is the cheapest correct option.

Arms checked (inline wc, pipeline_exec.rs)

arm verdict reason
-c fixed decode to raw bytes before .len()
flagless bytes fixed same expression as -c
-w fixed decode to visible text before split_whitespace(); 0x0C is both a carrier and whitespace
flagless words fixed same as -w
-l correct already 0x0A is not a carrier byte, so \n counting is unaffected
flagless lines correct already same
-m correct already not an inline arm → external fallback
-lc, combined flags correct already not a single-flag form → external fallback
--bytes, -L, --words, file operands correct already external fallback

Arms checked (command_substitution_values.rs, $( ... | wc ... ))

arm verdict reason
-c fixed same transport-bytes bug
-l correct already 0x0A not a carrier
no arg (defaults to -l) correct already
any other flag correct already returns None → full execution path

Before / after

command inline before inline after external (command wc)
printf '\033' | wc -c 6 1 1
printf '\033[31mX\033[0m' | wc -c 20 10 10
printf '\033[0m' | wc -c 9 4 4
printf '\033\033\033' | wc -c 18 3 3
printf '\033' | wc (default) 0 1 6 0 1 1 0 1 1
printf 'a\014b' | wc -w 1 2 2
echo "$(printf '\033' | wc -c)" 6 1 1

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. Honest
inventory:

  • Fixed: the four arms above.

  • Not a bug — external_setup.rs:1170 input.len().to_string():
    input there is a Vec<u8> raw snapshot, already bytes.

  • Not a bug — inline cat identity passthrough keeps transport text
    as-is by design (downstream stages decode); it does not measure a
    payload length.

  • Not a bug found — inline grep/sed/tr/head/tail/sort/uniq
    consume 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:905 self.pipeline_stdin_consumed.set(Some(input.len()))
      (payload at 901 is shell_text_to_raw_bytes(input));
    • pipeline_exec.rs:1890 and 2262 (base + stage0_input.len()) for
      FUNCTION_STDIN_OFFSET (payload written via shell_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 construct
    a user-visible reproduction, and the brief says not to fix anything I cannot
    demonstrate. Reporting it here instead of guessing. (-c/-w are the
    user-visible outputs; those are fixed.)

Tests

New: tests/issue383_inline_wc_transport_bytes.rs (9 tests) — control-byte
sweep (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, the
form-feed word-count case, -l, the -m/-lc external fallback pins, and an
ASCII no-regression case.

cargo test --test issue383_inline_wc_transport_bytes --test issue166_tr_pipeline_options
   … issue166_tr_pipeline_options: 6 passed
   … issue383_inline_wc_transport_bytes: 9 passed

cargo test --lib inline_tr_tests
   … 2 passed (677 filtered out)

cargo test --test issue383_inline_wc_transport_bytes \
  --test issue166_tr_pipeline_options --test issue165_cat_pipe_reader_options \
  --test issue177_virtual_root_operand_exe_resolution \
  --test issue158_pipeline_drain_deadlock --test comsub_nonascii_span_regressions \
  --test decode_to_visible_text
   … comsub_nonascii_span_regressions: 10 passed
   … decode_to_visible_text:            3 passed
   … issue158_pipeline_drain_deadlock:  5 passed
   … issue165_cat_pipe_reader_options: 12 passed
   … issue166_tr_pipeline_options:      6 passed
   … issue177_virtual_root_operand_exe_resolution: 4 passed
   … issue383_inline_wc_transport_bytes: 9 passed

cargo fmt --check clean.

Left alone deliberately

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.
@caomengxuan666
caomengxuan666 force-pushed the fix/383-inline-wc-transport-bytes branch from c4051d8 to b18a146 Compare October 17, 2026 02:19
caomengxuan666 pushed a commit that referenced this pull request Oct 17, 2026
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 caomengxuan666 left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 byte

Any 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.

@caomengxuan666

Copy link
Copy Markdown
Member Author

Fix for review R1, final state (commits 3362e53 + ad81e6f, note the intermediate push was incomplete):

  • Both call sites — single -w and the flagless words field — now count over shell_text_to_raw_bytes with ASCII whitespace via the shared inline_wc_word_count helper; payload never touches decode_to_visible_text.
  • Review repro printf '\021' | wc -w -> 1 rc 0; no CTLESC postcondition trip in debug builds.
  • 3 new tests in tests/issue383_inline_wc_transport_bytes.rs (word_count_control_payload_no_panic, default_form_word_field_no_panic, word_count_payload_whitespace_mix); doc comment and test-file header no longer claim "decode to visible text first".
  • cargo test --test issue383_inline_wc_transport_bytes moment: 12 passed; cargo fmt --check clean.

@caomengxuan666
caomengxuan666 merged commit c5508eb into master Oct 17, 2026
6 checks passed
caomengxuan666 added a commit that referenced this pull request Oct 17, 2026
…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]>
caomengxuan666 added a commit that referenced this pull request Oct 17, 2026
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.
@caomengxuan666
caomengxuan666 deleted the fix/383-inline-wc-transport-bytes branch October 18, 2026 09:29
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.

1 participant