Add checks to make sure that ram has a size that is a multiple of 8

This commit is contained in:
2025-12-27 20:52:32 +01:00
parent 6a3920895b
commit 970c1adcb0

View File

@@ -194,6 +194,9 @@ compile_error!("Current RAM implementation requires a little-endian host.");
impl Ram { impl Ram {
pub fn try_new(size: usize) -> Result<Self, std::io::Error> { pub fn try_new(size: usize) -> Result<Self, std::io::Error> {
if !size.is_multiple_of(8) {
return Err(std::io::Error::other("ram size must be a multiple of 8"));
}
Ok(Self { Ok(Self {
buf: MmapMut::map_anon(size)?, buf: MmapMut::map_anon(size)?,
}) })
@@ -204,9 +207,13 @@ impl Ram {
} }
/// # Safety /// # Safety
/// Safe if T has a size divisible by page size (4kb) (or is known to have a size divisible by the full ram size) and you know that the RAM is made up of valid naturally aligned values of T /// Safe if the size of the memory in bytes is divisible by the size of T
/// Assuming try_new is used, RAM size is guaranteed to be a multiple of 8
/// meaning anything with size 1, 2, 4, or 8 bytes is valid.
/// It must also be known that the contents of RAM are made up of naturally
/// aligned valid instances of T.
#[inline] #[inline]
pub unsafe fn buf_transmuted<T>(&self) -> &[T] { unsafe fn buf_transmuted<T>(&self) -> &[T] {
debug_assert!(self.buf.len().is_multiple_of(std::mem::size_of::<T>())); debug_assert!(self.buf.len().is_multiple_of(std::mem::size_of::<T>()));
unsafe { unsafe {
std::slice::from_raw_parts( std::slice::from_raw_parts(