tr: fix high memory use, possible heap exhaustion

Read the input into a statically sized buffer - 8192, matching
GNU - instead of reading until the end of the line, as reading
until the end of the line in a file with no end of line would
result in reading the entire file into memory.

Confusingly, GNU tr seems to write the 8192 byte in two chunks
of 1024 and 7168 byte, but I can't figure out why it would do
that; I don't see any line buffering in GNU tr.

Bug-Ubuntu: https://launchpad.net/bugs/2119520
This commit is contained in:
Julian Andres Klode 2025-08-05 15:47:49 +02:00 committed by Nicolas Boichat
parent 69d0e93078
commit ef40c472a3

View file

@ -672,15 +672,17 @@ where
R: BufRead,
W: Write,
{
let mut buf = Vec::new();
let mut buf = [0; 8192];
let mut output_buf = Vec::new();
while let Ok(length) = input.read_until(b'\n', &mut buf) {
while let Ok(length) = input.read(&mut buf[..]) {
if length == 0 {
break; // EOF reached
}
let filtered = buf.iter().filter_map(|&c| translator.translate(c));
let filtered = buf[..length]
.iter()
.filter_map(|&c| translator.translate(c));
output_buf.extend(filtered);
#[cfg(not(target_os = "windows"))]
@ -698,7 +700,6 @@ where
}
}
buf.clear();
output_buf.clear();
}