From 5f256f91cdca65af8631412d66b522ce3fbca598 Mon Sep 17 00:00:00 2001 From: Anhad Singh Date: Fri, 2 Jan 2026 00:52:40 +1100 Subject: [PATCH] fix(string/memcmp): use `read_unaligned` where alignment is not guaranteed Signed-off-by: Anhad Singh --- src/header/string/mod.rs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/header/string/mod.rs b/src/header/string/mod.rs index ecd897015e..199cc57a97 100644 --- a/src/header/string/mod.rs +++ b/src/header/string/mod.rs @@ -66,13 +66,15 @@ pub unsafe extern "C" fn memchr( #[unsafe(no_mangle)] pub unsafe extern "C" fn memcmp(s1: *const c_void, s2: *const c_void, n: usize) -> c_int { let (div, rem) = (n / mem::size_of::(), n % mem::size_of::()); - let mut a = s1 as *const usize; - let mut b = s2 as *const usize; + let mut a = s1.cast::(); + let mut b = s2.cast::(); for _ in 0..div { - if *a != *b { + // SAFETY: `s1` and `s2` are `*const c_void`, which only guarantees byte + // alignment. Hence `a` and `b` may be unaligned. + if a.read_unaligned() != b.read_unaligned() { for i in 0..mem::size_of::() { - let c = *(a as *const u8).add(i); - let d = *(b as *const u8).add(i); + let c = *(a.cast::()).add(i); + let d = *(b.cast::()).add(i); if c != d { return c as c_int - d as c_int; } @@ -83,8 +85,8 @@ pub unsafe extern "C" fn memcmp(s1: *const c_void, s2: *const c_void, n: usize) b = b.offset(1); } - let mut a = a as *const u8; - let mut b = b as *const u8; + let mut a = a.cast::(); + let mut b = b.cast::(); for _ in 0..rem { if *a != *b { return *a as c_int - *b as c_int;