Fix UB in `siphash24`

The code in `siphash24` was obtaining the pointer in buffer at offset by
accessing an element at that offset instead of accessing a range or
simply computing the offset of the pointer from the start. This is UB
because one canot access past `T` even if the allocation is known to be
large enough. This change fixes it by using a range and also replaces
complicated code with simpler use of `from_le_bytes`.

It's quite likely that this can be improved further, possibly even
removing the `unsafe` without speed penalty but it's a larger task
that's not a priority right now.
This commit is contained in:
Martin Habovstiak 2024-09-08 12:08:13 +02:00
parent 2c26dc4e57
commit fb5971cc2b
1 changed files with 2 additions and 8 deletions

View File

@ -4,7 +4,7 @@
use core::ops::Index; use core::ops::Index;
use core::slice::SliceIndex; use core::slice::SliceIndex;
use core::{cmp, mem, ptr}; use core::{cmp, mem};
use crate::HashEngine as _; use crate::HashEngine as _;
@ -53,13 +53,7 @@ macro_rules! compress {
macro_rules! load_int_le { macro_rules! load_int_le {
($buf:expr, $i:expr, $int_ty:ident) => {{ ($buf:expr, $i:expr, $int_ty:ident) => {{
debug_assert!($i + mem::size_of::<$int_ty>() <= $buf.len()); debug_assert!($i + mem::size_of::<$int_ty>() <= $buf.len());
let mut data = 0 as $int_ty; $int_ty::from_le_bytes($buf.get_unchecked($i..($i + mem::size_of::<$int_ty>())).try_into().expect("len is correctly computed using size_of"))
ptr::copy_nonoverlapping(
$buf.get_unchecked($i),
&mut data as *mut _ as *mut u8,
mem::size_of::<$int_ty>(),
);
data.to_le()
}}; }};
} }