printf: Format String Parsing Overflow Causes Panic

Closes: https://github.com/uutils/coreutils/issues/9697
This commit is contained in:
Sylvestre Ledru 2025-12-18 10:42:59 +01:00
parent 2000af835a
commit 0b63ffca5c
2 changed files with 13 additions and 7 deletions

View file

@ -595,14 +595,10 @@ fn eat_number(rest: &mut &[u8], index: &mut usize) -> Option<usize> {
match rest[*index..].iter().position(|b| !b.is_ascii_digit()) {
None | Some(0) => None,
Some(i) => {
// TODO: This might need to handle errors better
// For example in case of overflow.
let parsed = std::str::from_utf8(&rest[*index..(*index + i)])
.unwrap()
.parse()
.unwrap();
// Handle large numbers that would cause overflow
let num_str = std::str::from_utf8(&rest[*index..(*index + i)]).unwrap();
*index += i;
Some(parsed)
Some(num_str.parse().unwrap_or(usize::MAX))
}
}
}

View file

@ -1482,3 +1482,13 @@ fn test_large_width_format() {
.stdout_is("");
}
}
#[test]
fn test_extreme_field_width_overflow() {
// Test the specific case that was causing panic due to integer overflow
// in the field width parsing.
new_ucmd!()
.args(&["%999999999999999999999999d", "1"])
.fails_with_code(1)
.stderr_only("printf: write error\n");
}