Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions src/line_buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ pub struct LineBuffer {
next_line_start: u64,
/// Set once a file read has returned EOF.
eof: bool,
/// Whether input read so far contains a NUL byte. Only `read_line` keeps it up to date;
/// the chunked fast path scans each chunk itself.
has_nul: bool,
/// The line terminator is typically NUL or LF.
line_terminator: u8,
}
Expand All @@ -37,6 +40,7 @@ impl LineBuffer {

next_line_start: 0,
eof: false,
has_nul: false,
line_terminator,
}
}
Expand All @@ -48,13 +52,14 @@ impl LineBuffer {
self.end = 0;
self.next_line_start = 0;
self.eof = false;
self.has_nul = false;
}

/// Read the next line from the given reader.
/// Returns `Ok(None)` if the end of the reader is reached.
/// Otherwise, returns `Ok(Some((line, line_start)))`, where `line` is the line read (without the
/// Otherwise, returns `Ok(Some((line, line_start, self.has_nul)))`, where `line` is the line read (without the
/// `line_terminator`), and `line_start` is the absolute byte offset of the start of the line.
pub fn read_line(&mut self, file: &mut File) -> io::Result<Option<(&[u8], u64)>> {
pub fn read_line(&mut self, file: &mut File) -> io::Result<Option<(&[u8], u64, bool)>> {
if self.eof {
return Ok(None);
}
Expand All @@ -69,7 +74,7 @@ impl LineBuffer {
self.beg = end + 1;
self.scan = self.beg;
self.next_line_start += (self.beg - beg) as u64;
return Ok(Some((line, line_start)));
return Ok(Some((line, line_start, self.has_nul)));
}

// `buffer[pos..end]` has no terminator. Remember that for the next scan.
Expand Down Expand Up @@ -105,9 +110,15 @@ impl LineBuffer {
let line = &self.buffer[self.beg..self.end];
let line_start = self.next_line_start;
self.eof = true; // shortcut the next call to read_line()
Ok(Some((line, line_start)))
Ok(Some((line, line_start, self.has_nul)))
};
}
if self.line_terminator != 0
&& !self.has_nul
&& memchr(0, &self.buffer[self.end..self.end + n]).is_some()
{
self.has_nul = true;
}
self.end += n;
}
}
Expand Down
30 changes: 12 additions & 18 deletions src/searcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -444,26 +444,20 @@ impl<'a> Searcher<'a> {

'outer: while let Some((chunk, chunk_off)) = lb.read_chunk(reader)? {
let mut p = 0;
// NUL scanned up to here; terminators counted up to `nl_cursor`.
let mut nul_scanned = 0;
let mut nl_cursor = 0;
let mut nl_before = 0u64;

// A NUL in this block marks the file binary from here on.
if detect_binary && !binary && memchr(0, chunk).is_some() {
binary = true;
}

while p < chunk.len() {
let Some(rel) = leftmost_match(finders, &chunk[p..]) else {
break;
};
let (line_beg, line_end) = line_bounds(chunk, p + rel);

// A NUL anywhere up to this line marks the file binary, as does
// an invalid-UTF-8 matching line.
if detect_binary && !binary {
if memchr(0, &chunk[nul_scanned..line_end]).is_some() {
binary = true;
}
nul_scanned = line_end;
}

let line = &chunk[line_beg..line_end];
#[cfg(windows)]
let line = if self.config.strip_cr && line.last() == Some(&b'\r') {
Expand All @@ -472,6 +466,7 @@ impl<'a> Searcher<'a> {
line
};

// An invalid-UTF-8 matching line also marks the file binary.
if detect_binary && !binary && std::str::from_utf8(line).is_err() {
binary = true;
}
Expand Down Expand Up @@ -510,10 +505,7 @@ impl<'a> Searcher<'a> {
}
}

// Carry NUL detection and the line tally across the chunk boundary.
if detect_binary && !binary && memchr(0, &chunk[nul_scanned..]).is_some() {
binary = true;
}
// Carry the line tally across the chunk boundary.
if want_lineno {
base_lines += nl_before + count_terminators(&chunk[nl_cursor..]);
}
Expand Down Expand Up @@ -553,7 +545,7 @@ impl<'a> Searcher<'a> {
let mut read_error = None;

loop {
let (line, line_start) = match lb.read_line(reader) {
let (line, line_start, has_nul) = match lb.read_line(reader) {
Ok(Some(line)) => line,
Ok(None) => break,
Err(err) => {
Expand All @@ -575,8 +567,10 @@ impl<'a> Searcher<'a> {
line
};

// Any null byte flips us into binary mode.
if !self.session_mark_binary_if(|| memchr(0, line).is_some()) {
// A NUL in this input block flips us into binary mode.
if !self.session_mark_binary_if(|| {
has_nul || (self.config.null_data && memchr(0, line).is_some())
}) {
return Ok(false);
}

Expand Down
60 changes: 50 additions & 10 deletions tests/test_grep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,13 +233,13 @@ fn max_count_literal_stops_reading_open_pipe(#[case] args: &[&str], #[case] expe

#[test]
fn max_count_literal_still_detects_binary_in_read_chunk() {
// The chunk holding the N-th match is still scanned for NUL, so a NUL after
// it gives the binary notice, the same as without another match before it.
// The chunk holding the N-th match is scanned for NUL, so a NUL in it
// gives the binary notice and suppresses output in that block.
let (_s, mut c) = ucmd();
c.args(&["-m1", "word"])
.pipe_in("word\nword\nfoo\0\n")
.succeeds()
.stdout_is("word\n")
.no_stdout()
.stderr_contains("binary file matches");
}

Expand Down Expand Up @@ -2474,9 +2474,20 @@ fn slow_path_binary_handling() {
.succeeds()
.stdout_is_bytes(b"hit\0\n");

// A NUL after the matched line means binariness is discovered at EOF, so
// the line is printed first and the notice is emitted during finalization.
scene.fixtures.write_bytes("late", b"hit\nno\0\n");
// A NUL in the same block as a matched line suppresses the match.
scene.fixtures.write_bytes("same_block", b"hit\nno\0\n");
scene
.cmd(env!("CARGO_BIN_EXE_grep"))
.args(&["[h]it", "same_block"])
.succeeds()
.no_stdout()
.stderr_contains("binary file matches");

// A NUL in a later block allows earlier blocks to print their matches.
let mut late = b"hit\n".to_vec();
late.resize(150 * 1024, b'y');
late.extend(b"\nno\0\n");
scene.fixtures.write_bytes("late", &late);
scene
.cmd(env!("CARGO_BIN_EXE_grep"))
.args(&["[h]it", "late"])
Expand All @@ -2487,11 +2498,13 @@ fn slow_path_binary_handling() {

#[test]
fn fast_path_binary_detected_after_a_printed_line() {
// A NUL that appears only after the last match in the buffer marks the file
// binary on the fast path *after* an earlier match was already printed: the
// printed line stays and the trailing notice is still emitted.
// A NUL that appears in a subsequent block marks the file binary on the
// fast path *after* an earlier match was already printed from a prior block.
let (scene, _) = ucmd();
scene.fixtures.write_bytes("b", b"hit\nno\0\n");
let mut b = b"hit\n".to_vec();
b.resize(150 * 1024, b'y');
b.extend(b"\nno\0\n");
scene.fixtures.write_bytes("b", &b);
scene
.cmd(env!("CARGO_BIN_EXE_grep"))
.args(&["hit", "b"])
Expand All @@ -2500,6 +2513,33 @@ fn fast_path_binary_detected_after_a_printed_line() {
.stderr_contains("binary file matches");
}

#[test]
fn nul_in_earlier_block_without_match_hides_later_match() {
let (scene, _) = ucmd();
let mut data = b"x\0\n".to_vec();
data.resize(data.len() + 150 * 1024, b'y');
data.extend(b"\nhit\n");
scene.fixtures.write_bytes("b", &data);
scene
.cmd(env!("CARGO_BIN_EXE_grep"))
.args(&["hit", "b"])
.succeeds()
.no_stdout()
.stderr_contains("binary file matches");
}

#[test]
fn nul_later_in_small_file_hides_earlier_matches() {
for pattern in ["lime", "l.me", "lime|plum"] {
let (_s, mut c) = ucmd();
c.args(&["-E", pattern])
.pipe_in(&b"plum\nlime\nfig\x00\nlime\n"[..])
.succeeds()
.no_stdout()
.stderr_contains("binary file matches");
}
}

#[test]
fn only_matching_with_context() {
// `only_matching` should override any context arguments.
Expand Down
Loading