From 04cd36f022c0bace5bc825046597f8ced2615789 Mon Sep 17 00:00:00 2001 From: Andrew Liebenow Date: Sun, 1 Sep 2024 07:59:19 -0500 Subject: [PATCH] od: do not panic on empty address radix --- src/uu/od/src/od.rs | 31 +++++++++++++++++++------------ tests/by-util/test_od.rs | 16 ++++++++++++---- 2 files changed, 31 insertions(+), 16 deletions(-) diff --git a/src/uu/od/src/od.rs b/src/uu/od/src/od.rs index 854b4083e..6dd75d307 100644 --- a/src/uu/od/src/od.rs +++ b/src/uu/od/src/od.rs @@ -171,23 +171,30 @@ impl OdOptions { None => Radix::Octal, Some(s) => { // Other implementations of od only check the first character of this argument's value. - // This means executing "od -Anone" is equivalent to "od -An". + // This means executing `od -Anone` is equivalent to executing `od -An`. // Existing users of od rely on this behavior: // https://github.com/landley/toybox/blob/d50372cad35d5dd12e6391c3c7c901a96122dc67/scripts/make.sh#L239 // https://github.com/google/jsonnet/blob/913281d203578bb394995bacc792f2576371e06c/Makefile#L212 let st = s.as_bytes(); - let radix: char = *(st.first().expect("should be caught by clap")) as char; - match radix { - 'd' => Radix::Decimal, - 'x' => Radix::Hexadecimal, - 'o' => Radix::Octal, - 'n' => Radix::NoPrefix, - _ => { - return Err(USimpleError::new( - 1, - "Radix must be one of [d, o, n, x]".to_string(), - )) + if let Some(u) = st.first() { + match *u { + b'o' => Radix::Octal, + b'd' => Radix::Decimal, + b'x' => Radix::Hexadecimal, + b'n' => Radix::NoPrefix, + _ => { + return Err(USimpleError::new( + 1, + "Radix must be one of [o, d, x, n]".to_string(), + )); + } } + } else { + // Return an error instead of panicking when `od -A ''` is executed. + return Err(USimpleError::new( + 1, + "Radix cannot be empty, and must be one of [o, d, x, n]".to_string(), + )); } } }; diff --git a/tests/by-util/test_od.rs b/tests/by-util/test_od.rs index bce088c17..4e7153456 100644 --- a/tests/by-util/test_od.rs +++ b/tests/by-util/test_od.rs @@ -579,6 +579,15 @@ fn test_invalid_offset() { new_ucmd!().arg("-Ab").fails(); } +#[test] +fn test_empty_offset() { + new_ucmd!() + .arg("-A") + .arg("") + .fails() + .stderr_only("od: Radix cannot be empty, and must be one of [o, d, x, n]\n"); +} + #[test] fn test_offset_compatibility() { let input = [0u8; 4]; @@ -586,10 +595,9 @@ fn test_offset_compatibility() { new_ucmd!() .arg("-Anone") - .run_piped_stdin(input) - .no_stderr() - .success() - .stdout_is(expected_output); + .pipe_in(input) + .succeeds() + .stdout_only(expected_output); } #[test]