From 58b407556607add3801b49eda7ae100ac208d5e2 Mon Sep 17 00:00:00 2001 From: Alex Jiang Date: Thu, 19 Apr 2018 21:20:23 +0800 Subject: [PATCH] hostname: bug fix for non-windows xgethostname and add test case Cstr::from_bytes_with_nul needs input bytes null terminated. Current version does not include the last null byte, hence Cstr::from_bytes_with_nul will panic with error 'FromBytesWithNulError { kind: NotNulTerminated }' --- src/hostname/hostname.rs | 7 +++---- tests/test_hostname.rs | 12 ++++++++++++ tests/tests.rs | 3 ++- 3 files changed, 17 insertions(+), 5 deletions(-) create mode 100644 tests/test_hostname.rs diff --git a/src/hostname/hostname.rs b/src/hostname/hostname.rs index 23ad3b4e9..80b60a699 100644 --- a/src/hostname/hostname.rs +++ b/src/hostname/hostname.rs @@ -157,13 +157,12 @@ fn xgethostname() -> io::Result { }; if err == 0 { - let mut last_char = name.iter().position(|byte| *byte == 0).unwrap_or(namelen); - if last_char == name.len() { + let null_pos = name.iter().position(|byte| *byte == 0).unwrap_or(namelen); + if null_pos == namelen { name.push(0); - last_char += 1; } - Ok(CStr::from_bytes_with_nul(&name[..last_char]) + Ok(CStr::from_bytes_with_nul(&name[..null_pos + 1]) .unwrap() .to_string_lossy() .into_owned()) diff --git a/tests/test_hostname.rs b/tests/test_hostname.rs new file mode 100644 index 000000000..8df10b166 --- /dev/null +++ b/tests/test_hostname.rs @@ -0,0 +1,12 @@ +use common::util::*; + +#[test] +fn test_hostname() { + let ls_default_res = new_ucmd!().succeeds(); + let ls_short_res = new_ucmd!().arg("-s").succeeds(); + let ls_domain_res = new_ucmd!().arg("-d").succeeds(); + + assert!(ls_default_res.stdout.len() >= ls_short_res.stdout.len()); + assert!(ls_default_res.stdout.len() >= ls_domain_res.stdout.len()); +} + diff --git a/tests/tests.rs b/tests/tests.rs index b1362dd0a..08552a4d5 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -91,6 +91,7 @@ generic! { "tsort", test_tsort; "unexpand", test_unexpand; "uniq", test_uniq; + "wc", test_wc; // Be aware of the trailing semicolon after the last item - "wc", test_wc + "hostname", test_hostname }