Repository navigation
Description
Known: #9 (closed: fixed by #49, -I case only) — #9
In a UTF-8 locale, GNU grep withholds only the selected lines that are not valid UTF-8, keeps
printing the other matching lines, and prints binary file matches once at the end. The GNU
manual (--binary-files): "By default, TYPE is 'binary', and grep suppresses output after null
input binary data is discovered, and suppresses output lines that contain improperly encoded
data." uutils grep handles an invalid-UTF-8 line like a NUL byte: it stops printing at the
first such line, so every later match is lost. Exit status, -c, -l, -L and -q already
agree; only the printed lines differ.
(uutils currently checks UTF-8 regardless of the locale, see the TODO in the code; that is a
separate issue. Compare in a UTF-8 locale here.)
Reproduction
$ printf 'foo 1\nfoo \377 2\nfoo 3\n' > uRust (incorrect)
$ LC_ALL=C.UTF-8 ./target/release/grep -n foo u
grep: u: binary file matches
1:foo 1
# Exit code: 0GNU (correct)
$ LC_ALL=C.UTF-8 /usr/bin/grep -n foo u
1:foo 1
3:foo 3
/usr/bin/grep: u: binary file matches
# Exit code: 0The same happens with a regex ('fo.', line-at-a-time path) and with -F foo (literal fast
path). (The notice appearing before 1:foo 1 in the uutils output is only stderr/stdout
buffering.)
Root cause
Line-at-a-time path, src/searcher.rs:528-545: an invalid-UTF-8 selected line sets
session_binary_detected (the same flag a NUL sets), which suppresses all further output, and
the notice is emitted right away:
// TODO: GNU grep respects LANG. Here, I'm always checking for valid UTF-8.
if self.config.binary_mode != BinaryMode::WithoutMatch
&& !self.session_mark_binary_if(|| std::str::from_utf8(line).is_err())
{
return Ok(false);
}
...
if self.session_should_emit_binary_notice() {
self.writer.report_binary_match(path);
return Ok(true);
}Literal fast path, src/searcher.rs:435-444 (fast_print): an invalid-UTF-8 matching line
sets binary = true and break 'outer, ending the search.
Test
#[test]
fn invalid_utf8_line_withheld_but_later_matches_printed() {
let (scene, _) = ucmd();
scene.fixtures.write_bytes("u", b"foo 1\nfoo \xff 2\nfoo 3\n");
// Literal fast path and regex path.
for pattern in ["foo", "fo."] {
let mut c = scene.cmd(env!("CARGO_BIN_EXE_grep"));
c.env("LC_ALL", "C.UTF-8")
.args(&["-n", pattern, "u"])
.succeeds()
.stdout_is("1:foo 1\n3:foo 3\n")
.stderr_is("grep: u: binary file matches\n");
}
}Reported by Anthropic's OSS Scanner (ANT-2026-GX1KCR0Q).
Activity