diff --git a/src/uucore/src/lib/features/format/spec.rs b/src/uucore/src/lib/features/format/spec.rs index 467f09850..3bef0fbb1 100644 --- a/src/uucore/src/lib/features/format/spec.rs +++ b/src/uucore/src/lib/features/format/spec.rs @@ -595,14 +595,10 @@ fn eat_number(rest: &mut &[u8], index: &mut usize) -> Option { 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)) } } } diff --git a/tests/by-util/test_printf.rs b/tests/by-util/test_printf.rs index 6bfcecbb4..21e638f7c 100644 --- a/tests/by-util/test_printf.rs +++ b/tests/by-util/test_printf.rs @@ -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"); +}