coreutils icon indicating copy to clipboard operation
coreutils copied to clipboard

tail: -c panics when requested bytes exceed file size

Open sylvestre opened this issue 10 months ago • 2 comments

tail -c panics when requested bytes exceed file size

Component

tail

Description

When using tail -c with a byte count larger than the file size, and the file is larger than 4096 bytes (blksize), tail panics with "Invalid argument" error instead of outputting the entire file content like GNU tail does.

The issue occurs in uutils tail's bounded_tail() function which is called for files larger than blksize_limit (typically 4096 bytes). When seeking to SeekFrom::End(-count) where count exceeds the file size, the seek operation fails because the resulting offset would be before the start of the file.

FilterMode::Bytes(Signum::Negative(count)) => {
    file.seek(SeekFrom::End(-(*count as i64))).unwrap();  // panics here
    limit = Some(*count);
}

The unwrap() call causes a panic when lseek() returns EINVAL because the negative offset exceeds the file size.

Test / Reproduction Steps

$ python3 -c "print('x'*5000)" > /tmp/test_file.txt           

$ tail -c 1M /tmp/test_file.txt | wc -c

$ coreutils tail -c 1M /tmp/test_file.txt
thread 'main' (1580010) panicked at src/uu/tail/src/tail.rs:427:56:
called `Result::unwrap()` on an `Err` value: Os { code: 22, kind: InvalidInput, message: "Invalid argument" }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Impact

Programs and scripts using tail -c with large byte counts on medium-sized files (> 4KB) will crash unexpectedly.

Recommendations

Handle the seek error gracefully by falling back to file start when the requested offset exceeds file size:

FilterMode::Bytes(Signum::Negative(count)) => {
    if file.seek(SeekFrom::End(-(*count as i64))).is_err() {
        file.seek(SeekFrom::Start(0)).unwrap();
    }
    limit = Some(*count);
}

sylvestre avatar Jan 11 '26 21:01 sylvestre

Hi, could I be assigned this issue if that's okay?

dhr412 avatar Jan 13 '26 07:01 dhr412

Please provide a pr instead We don't assign issues here

sylvestre avatar Jan 13 '26 07:01 sylvestre