Skip to content

$(cat FILE) on non-UTF-8 content yields an empty value plus a bogus "No such file"; ${x:off:len} fabricates PUA marker bytes; read -r strips a trailing CR #772

Closed

Description

@caomengxuan666

Summary

Three byte-exactness defects on the same theme: invalid UTF-8 is passed through the string/carrier layer instead of being treated as opaque bytes. The first one is the severe one — it silently yields an empty value for the most ordinary file-reading idiom there is.

All measured against master b5793580 (built 2026-10-17 14:25) with WSL GNU bash 5.3.0 as oracle; LF script files; stdout/stderr/rc captured separately; every probe repeated 3×, deterministic.

1. $(cat FILE) on non-UTF-8 content → empty value + a bogus "No such file"

printf '\xff' > h          # 1 byte, exists, is readable
cat h                      # prints the byte, rc 0   (fine outside a substitution)
x=$(cat h); echo "len=${#x}"
probe GNU bash 5.3.0 master b5793580
$(cat h) len=1 cat: 'h': No such file or directory, len=0
$(cat h 2>/dev/null) len=1 len=1 — works
$(cat g h) (g = ASCII) len=4 fails
$(cat < h) (operand → redirect) len=1 len=1
printf '\xff' | cat - (pipe) len=1 len=1
$(head -c1 h) len=1 len=1
$(cat g) (valid UTF-8) len=3 len=3
$(cat /dev/null) len=0 len=0

So the trigger is cat FILE… with the file passed as an operand, inside $( ), when the file's content is not valid UTF-8 — and it is disabled by redirecting stderr inside the substitution (2>/dev/null), which is the signature of a fast path that bails out when stderr is captured (the same stderr_capture.is_some() shape as src/executor/pipeline_exec.rs:2018). The error naming a file that plainly exists, plus the empty value, is what makes this the dangerous kind: a script that does data=$(cat file) gets "", prints a message about a missing file, and continues with a wrong value.

Hypothesis, not established: the operand is being handed to an in-process shortcut which routes the file's content through the string/carrier layer; on a decode failure the child is spawned with a corrupted operand. I could not read that path out of the source in the time I had, so please treat the mechanism as a guess — the behaviour table above is the part I verified.

2. ${x:off:len} fabricates PUA marker bytes for invalid UTF-8

x=$'\xff'
printf '%s' "${x:0:1}" | od -An -tx1
printf '%s' "${x:1}"   | od -An -tx1
y=$'a\xffb'; printf '%s' "${y:2}" | od -An -tx1
probe GNU master b5793580
${x:0:1} ff ee 80 80 (U+E000)
${x:1} (empty) ee 84 80 (U+E100)
${y:2} 62 ee 84 80 62

The fabricated bytes are in the marker registry's range, so a substring taken over a binary variable produces carrier characters — which is also why this is worth fixing even though the input is already "broken": it turns an invalid byte into a marker that other code is entitled to interpret. Related to #735 (user-typed PUA ignored/swallowed in the other direction) and to the registry inventory in #727/#728/#729.

3. IFS= read -r strips a trailing CR

printf 'a\r' > f1 ; IFS= read -r l < f1 ; printf '%s' "$l" | od -An -tx1
printf 'a\r\r\n' > f2 ; IFS= read -r m < f2 ; printf '%s' "$m" | od -An -tx1
probe GNU master b5793580
a\r (no LF) 61 0d (len 2) 61 (len 1)
a\r\r\n 61 0d 0d (len 3) 61 (len 1)

GNU strips only the record terminator; a CR that is content survives — including the second CR here. This is the shell-side twin of WinuxCmd #1204 (trailing CR stripped from file operands); both sides of the boundary drop it, so a CR-carrying file cannot be read byte-exactly through either.

Method

LF scripts; oracle WSL GNU bash 5.3.0; niu/rubash target/release/rubash.exe built from master b5793580; arms bounded; fixtures built inside each arm's own work dir; byte dumps via od -An -tx1 (verified to have the same output format on both sides). All three items are pinned as catalogue cases in #746.

Activity

  1. added
    bug
    P1-high
    area:carrier
    area:expansion
    on Oct 17, 2026
  2. caomengxuan666 commented on Oct 17, 2026

    @caomengxuan666
    MemberAuthor

    Verification-shape hint for whoever works this (learned the hard way on #714): the carrier encoding only exists inside one shell process. If you feed the case through an external pipe (printf … | rubash -c … from another shell) the bytes are decoded at the process boundary and the defect vanishes — three separate attempts to reproduce #714 that way produced false "master looks fine" negatives. The shape that shows it puts the whole pipeline inside one rubash -c:

    rubash -c 'printf "AB\033C" | { read -n3 c; printf %s "$c" | od -An -tx1; }'
    #   master: 41 42 ee 80 80   (carrier pair split)      fixed by #775: 41 42 1b

    Same likely applies here: make the producer that emits the non-UTF-8 bytes a builtin inside the same invocation (not an outside pipe), or the transport never sees a carrier at all.

  3. caomengxuan666 commented on Oct 17, 2026

    @caomengxuan666
    MemberAuthor

    Sharper repro from writing a regression test for this (PR #777)

    While turning item 1 into a Rust test I found the failure is not only "empty" — with more than one operand the invalid byte is silently dropped and the count is short, which is a quieter failure than an empty value:

    printf 'abc' > g ; printf '\xff' > f
    x=$(cat g f); echo "${#x}"
    arm ${#x} stderr
    GNU bash 5.3.0 4 —
    master b5793580 3 cat: 'f': No such file or directory

    So the operand f is dropped from the content entirely (3 of 4 bytes) rather than the substitution failing outright, while the single-operand case yields 0.

    And one case that is correct today, which is what localises the defect to the operand form inside a substitution:

    probe GNU master
    x=$(cat < f) (redirection) 1 1
    x=$(cat f 2>/dev/null) 1 1

    I had written the redirection form as a reproduction; it passed, so it is now a control in the test file. Both files also carry passing controls on purpose — a green reproduction is otherwise indistinguishable from a broken fixture.

    Tests: tests/issue772_comsub_non_utf8_file_regressions.rs (two reproductions #[ignore]d with the issue number, three controls passing), in PR #777.

  4. caomengxuan666 commented on Oct 17, 2026

    @caomengxuan666
    MemberAuthor

    Root cause located — it is not command substitution in general, it is an inlined cat shortcut

    Reading the current master source rather than guessing from behaviour, the diagnostic comes from a hard-coded cat emulation inside the command-substitution code path:

    // src/executor/command_substitution.rs, ~line 923
    match fs::read_to_string(crate::executor::path::windows_operand_file_path(
        shell_path_to_windows(&path, &self.shell_state.env_vars),
        &self.shell_state.env_vars,
    )) {
        Ok(value) => output.push_str(&value),
        Err(_) => {
            status = 1;
            eprintln!("cat: '{}': No such file or directory", path);   // <-- fabricated, and always ENOENT
        }
    }

    Two defects in six lines:

    1. fs::read_to_string — a UTF-8-only read on a path whose contract is byte-transparent. cat is a byte channel; a file containing 0xFF is not an error for it.
    2. Err(_) — every failure mode is collapsed into one fabricated message. It also means a successful read is impossible to distinguish from a wrong one at the call site.

    The whole trigger matrix falls out of that

    observation explanation
    operand form fails, $(cat < f) and cat - work this shortcut handles words[1..] operands; a redirection or - never reaches it and the real command runs
    content-dependent (ASCII fine, 0xFF fails) read_to_string → ErrorKind::InvalidData
    2>/dev/null makes it work upstream eligibility for the shortcut requires uncaptured stderr, so redirecting it runs the real command
    cat g f yields 3 of 4 bytes g is pushed, f's error sets status = 1 and pushes nothing — content silently short, exit 1
    no error for the single-operand case in GNU GNU has no error at all: the byte is simply copied

    The mis-mapping is systematic, not specific to invalid UTF-8

    X in $(cat X) GNU bash 5.3.0 master b5793580
    a directory cat: adir: Is a directory cat: 'adir': No such file or directory
    . cat: .: Is a directory cat: '.': No such file or directory
    file with 0xFF (no error, 1 byte) cat: 'bad.bin': No such file or directory, empty
    valid text 2 bytes 2 bytes
    genuinely missing file cat: nosuch: No such file or directory same — correct only by coincidence, which is why this has stayed hidden

    Suggested fix direction

    Either is small; the first is what the contract wants:

    • read bytes (fs::read) and push them into the capture losslessly — the capture is already byte-oriented (trim_capture_terminator() at the end of the same function treats it as bytes); or
    • keep a text read but map the error (InvalidData is not ENOENT) and, more importantly, fall through to real execution on any error rather than emitting a cat: diagnostic that the user never asked for — a shortcut should never invent a command's diagnostic.

    A regression test is in PR #777 (tests/issue772_comsub_non_utf8_file_regressions.rs), currently #[ignore]d with this issue number.

    One adjacent observation, deliberately not filed separately

    The same mis-mapping exists outside a substitution: cat adir reports No such file or directory where GNU reports Is a directory (exit status matches, so it is message-only). Same defect shape, different site — flagging it here so it is not lost, and so the same fix can consider both call sites rather than only the command-substitution one.

    Correction to my own earlier framing: I wrote "a fast path that declines when stderr is captured" and pointed at pipeline_exec.rs:2018. That shape is real (stderr_capture.is_some() bail-outs exist in four places in that file), but it is not this defect: the failing path is the $(cat …) inlining above. Behaviour measured; mechanism now read.

  5. caomengxuan666 commented on Oct 17, 2026

    @caomengxuan666
    MemberAuthor

    这三项在当前 master 上都已经不复现了,应该是 #781(b2dd10e "keep non-UTF-8 bytes opaque in $(cat) and ${x:off:len}")顺带修掉的。

    刚才用当前 master 逐条复验(GNU 5.2.21 对照):

    probe GNU 当前 master
    x=$(cat h)(h 是单字节 ff) len=1 len=1
    x=$(cat h 2>/dev/null) len=1 len=1
    ${x:0:1} / ${x:1} / ${y:2}(x=$'\xff', y=$'a\xffb') ff / 空 / 62 ff / 空 / 62
    IFS= read -r l < f1(a\r,无 LF) 61 0d 61 0d
    IFS= read -r m < f2(a\r\r\n) 61 0d 0d 61 0d 0d

    三项都对上了,没有残留的 PUA 伪造字节,CR 也不再被吞。这个 issue 按"已修复"关掉。

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    P1-higharea:carrierarea:expansionbug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions