From 332ae13af5d28cd46859a145c3b7353b9fa79321 Mon Sep 17 00:00:00 2001 From: Alex Lyon <arcterus@mail.com> Date: Thu, 8 Mar 2018 17:06:09 -0800 Subject: [PATCH] string: fix out of bounds bug in strncmp --- src/string/src/lib.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/string/src/lib.rs b/src/string/src/lib.rs index 8252dbf6..c272d921 100644 --- a/src/string/src/lib.rs +++ b/src/string/src/lib.rs @@ -159,14 +159,22 @@ pub unsafe extern "C" fn strncmp(s1: *const c_char, s2: *const c_char, n: usize) let s1 = platform::c_str_n(s1, n); let s2 = platform::c_str_n(s2, n); - for i in 0..n { + let min_len = n.min(s1.len()).min(s2.len()); + for i in 0..min_len { let val = s1[i] - s2[i]; - if val != 0 || s1[i] == 0 { + if val != 0 { return val as c_int; } } - 0 + // we can't just check for the NUL byte in the loop as c_str_n() removes it + if s1.len() > s2.len() { + s1[min_len] as c_int + } else if s1.len() < s2.len() { + -(s2[min_len] as c_int) + } else { + 0 + } } #[no_mangle] -- GitLab