aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / vendor / uefi / src / mem / memory_map / impl_.rs
| 1 | // SPDX-License-Identifier: MIT OR Apache-2.0 |
| 2 | |
| 3 | //! Module for [`MemoryMapOwned`], [`MemoryMapRef`], and [`MemoryMapRefMut`], |
| 4 | //! as well as relevant helper types, such as [`MemoryMapBackingMemory`]. |
| 5 | |
| 6 | use super::*; |
| 7 | use crate::boot; |
| 8 | use core::fmt::{self, Debug, Display, Formatter}; |
| 9 | use core::ops::{Index, IndexMut}; |
| 10 | use core::ptr::NonNull; |
| 11 | use core::{error, ptr}; |
| 12 | use uefi_raw::PhysicalAddress; |
| 13 | |
| 14 | const fn validate_meta(meta: MemoryMapMeta) -> Result<usize, MemoryMapError> { |
| 15 | if meta.desc_size < size_of::<MemoryDescriptor>() |
| 16 | || !meta |
| 17 | .desc_size |
| 18 | .is_multiple_of(align_of::<MemoryDescriptor>()) |
| 19 | || !meta.map_size.is_multiple_of(meta.desc_size) |
| 20 | { |
| 21 | Err(MemoryMapError::InvalidSize) |
| 22 | } else { |
| 23 | Ok(meta.map_size / meta.desc_size) |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | /// Errors that may happen when constructing a [`MemoryMapRef`] or |
| 28 | /// [`MemoryMapRefMut`]. |
| 29 | #[derive(Copy, Clone, Debug)] |
| 30 | pub enum MemoryMapError { |
| 31 | /// The buffer is not 8-byte aligned. |
| 32 | Misaligned, |
| 33 | /// The memory map size is invalid. |
| 34 | InvalidSize, |
| 35 | } |
| 36 | |
| 37 | impl Display for MemoryMapError { |
| 38 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { |
| 39 | Debug::fmt(self, f) |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | impl error::Error for MemoryMapError {} |
| 44 | |
| 45 | /// Implementation of [`MemoryMap`] for the given buffer. |
| 46 | #[derive(Debug)] |
| 47 | pub struct MemoryMapRef<'a> { |
| 48 | buf: &'a [u8], |
| 49 | meta: MemoryMapMeta, |
| 50 | len: usize, |
| 51 | } |
| 52 | |
| 53 | impl<'a> MemoryMapRef<'a> { |
| 54 | /// Constructs a new [`MemoryMapRef`]. |
| 55 | /// |
| 56 | /// The underlying memory might contain an invalid/malformed memory map |
| 57 | /// which can't be checked during construction of this type. The entry |
| 58 | /// iterator might yield unexpected results. |
| 59 | pub fn new(buffer: &'a [u8], meta: MemoryMapMeta) -> Result<Self, MemoryMapError> { |
| 60 | if buffer.as_ptr().align_offset(8) != 0 { |
| 61 | return Err(MemoryMapError::Misaligned); |
| 62 | } |
| 63 | if buffer.len() < meta.map_size { |
| 64 | return Err(MemoryMapError::InvalidSize); |
| 65 | } |
| 66 | let len = validate_meta(meta)?; |
| 67 | Ok(Self { |
| 68 | buf: buffer, |
| 69 | meta, |
| 70 | len, |
| 71 | }) |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | impl MemoryMap for MemoryMapRef<'_> { |
| 76 | fn meta(&self) -> MemoryMapMeta { |
| 77 | self.meta |
| 78 | } |
| 79 | |
| 80 | fn key(&self) -> MemoryMapKey { |
| 81 | self.meta.map_key |
| 82 | } |
| 83 | |
| 84 | fn len(&self) -> usize { |
| 85 | self.len |
| 86 | } |
| 87 | |
| 88 | fn buffer(&self) -> &[u8] { |
| 89 | self.buf |
| 90 | } |
| 91 | |
| 92 | fn entries(&self) -> MemoryMapIter<'_> { |
| 93 | MemoryMapIter { |
| 94 | memory_map: self, |
| 95 | index: 0, |
| 96 | } |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | impl Index<usize> for MemoryMapRef<'_> { |
| 101 | type Output = MemoryDescriptor; |
| 102 | |
| 103 | fn index(&self, index: usize) -> &Self::Output { |
| 104 | self.get(index).unwrap() |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | /// Implementation of [`MemoryMapMut`] for the given buffer. |
| 109 | #[derive(Debug)] |
| 110 | pub struct MemoryMapRefMut<'a> { |
| 111 | buf: &'a mut [u8], |
| 112 | meta: MemoryMapMeta, |
| 113 | len: usize, |
| 114 | } |
| 115 | |
| 116 | impl<'a> MemoryMapRefMut<'a> { |
| 117 | /// Constructs a new [`MemoryMapRefMut`]. |
| 118 | /// |
| 119 | /// The underlying memory might contain an invalid/malformed memory map |
| 120 | /// which can't be checked during construction of this type. The entry |
| 121 | /// iterator might yield unexpected results. |
| 122 | pub fn new(buffer: &'a mut [u8], meta: MemoryMapMeta) -> Result<Self, MemoryMapError> { |
| 123 | if buffer.as_ptr().align_offset(8) != 0 { |
| 124 | return Err(MemoryMapError::Misaligned); |
| 125 | } |
| 126 | if buffer.len() < meta.map_size { |
| 127 | return Err(MemoryMapError::InvalidSize); |
| 128 | } |
| 129 | let len = validate_meta(meta)?; |
| 130 | Ok(Self { |
| 131 | buf: buffer, |
| 132 | meta, |
| 133 | len, |
| 134 | }) |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | impl MemoryMap for MemoryMapRefMut<'_> { |
| 139 | fn meta(&self) -> MemoryMapMeta { |
| 140 | self.meta |
| 141 | } |
| 142 | |
| 143 | fn key(&self) -> MemoryMapKey { |
| 144 | self.meta.map_key |
| 145 | } |
| 146 | |
| 147 | fn len(&self) -> usize { |
| 148 | self.len |
| 149 | } |
| 150 | |
| 151 | fn buffer(&self) -> &[u8] { |
| 152 | self.buf |
| 153 | } |
| 154 | |
| 155 | fn entries(&self) -> MemoryMapIter<'_> { |
| 156 | MemoryMapIter { |
| 157 | memory_map: self, |
| 158 | index: 0, |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | impl MemoryMapMut for MemoryMapRefMut<'_> { |
| 164 | fn sort(&mut self) { |
| 165 | if self.len > 1 { |
| 166 | self.qsort(0, self.len - 1); |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | unsafe fn buffer_mut(&mut self) -> &mut [u8] { |
| 171 | self.buf |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | impl MemoryMapRefMut<'_> { |
| 176 | /// Hoare partition scheme for quicksort. |
| 177 | /// Must be called with `low` and `high` being indices within bounds. |
| 178 | fn qsort(&mut self, low: usize, high: usize) { |
| 179 | if low >= high { |
| 180 | return; |
| 181 | } |
| 182 | |
| 183 | let p = self.partition(low, high); |
| 184 | self.qsort(low, p); |
| 185 | self.qsort(p + 1, high); |
| 186 | } |
| 187 | |
| 188 | fn partition(&mut self, low: usize, high: usize) -> usize { |
| 189 | let pivot = self.get_element_phys_addr(low + (high - low) / 2); |
| 190 | |
| 191 | let mut left_index = low.wrapping_sub(1); |
| 192 | let mut right_index = high.wrapping_add(1); |
| 193 | |
| 194 | loop { |
| 195 | while { |
| 196 | left_index = left_index.wrapping_add(1); |
| 197 | |
| 198 | self.get_element_phys_addr(left_index) < pivot |
| 199 | } {} |
| 200 | |
| 201 | while { |
| 202 | right_index = right_index.wrapping_sub(1); |
| 203 | |
| 204 | self.get_element_phys_addr(right_index) > pivot |
| 205 | } {} |
| 206 | |
| 207 | if left_index >= right_index { |
| 208 | return right_index; |
| 209 | } |
| 210 | |
| 211 | self.swap(left_index, right_index); |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | /// Indices must be smaller than len. |
| 216 | fn swap(&mut self, index1: usize, index2: usize) { |
| 217 | assert!(index1 < self.len); |
| 218 | assert!(index2 < self.len); |
| 219 | |
| 220 | if index1 == index2 { |
| 221 | return; |
| 222 | } |
| 223 | |
| 224 | let base = self.buf.as_mut_ptr(); |
| 225 | |
| 226 | let offset1 = index1 * self.meta.desc_size; |
| 227 | let offset2 = index2 * self.meta.desc_size; |
| 228 | |
| 229 | // SAFETY: the data starting at `offset1` and `offset2` are valid |
| 230 | // descriptors, and do not overlap. |
| 231 | // SAFETY: The memory is valid. |
| 232 | unsafe { |
| 233 | ptr::swap_nonoverlapping(base.add(offset1), base.add(offset2), self.meta.desc_size); |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | fn get_element_phys_addr(&self, index: usize) -> PhysicalAddress { |
| 238 | assert!(index < self.len); |
| 239 | let offset = index.checked_mul(self.meta.desc_size).unwrap(); |
| 240 | // SAFETY: the data starting at `offset` is a valid descriptor. |
| 241 | let elem = unsafe { &*self.buf.as_ptr().add(offset).cast::<MemoryDescriptor>() }; |
| 242 | elem.phys_start |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | impl Index<usize> for MemoryMapRefMut<'_> { |
| 247 | type Output = MemoryDescriptor; |
| 248 | |
| 249 | fn index(&self, index: usize) -> &Self::Output { |
| 250 | self.get(index).unwrap() |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | impl IndexMut<usize> for MemoryMapRefMut<'_> { |
| 255 | fn index_mut(&mut self, index: usize) -> &mut Self::Output { |
| 256 | self.get_mut(index).unwrap() |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | /// The backing memory for the UEFI memory app on the UEFI heap, allocated using |
| 261 | /// the UEFI boot services allocator. This occupied memory will also be |
| 262 | /// reflected in the memory map itself. |
| 263 | /// |
| 264 | /// Although untyped, it is similar to the `Box` type in terms of heap |
| 265 | /// allocation and deallocation, as well as ownership of the corresponding |
| 266 | /// memory. Apart from that, this type only has the semantics of a buffer. |
| 267 | /// |
| 268 | /// The memory is untyped, which is necessary due to the nature of the UEFI |
| 269 | /// spec. It still ensures a correct alignment to hold [`MemoryDescriptor`]. The |
| 270 | /// size of the buffer is sufficient to hold the memory map at the point in time |
| 271 | /// where this is created. Note that due to (not obvious or asynchronous) |
| 272 | /// allocations/deallocations in your environment, this might be outdated at the |
| 273 | /// time you store the memory map in it. |
| 274 | /// |
| 275 | /// Note that due to the nature of the UEFI memory app, this buffer might |
| 276 | /// hold (a few) bytes more than necessary. The `map_size` reported by |
| 277 | /// `get_memory_map` tells the actual size. |
| 278 | /// |
| 279 | /// When this type is dropped and boot services are not exited yet, the memory |
| 280 | /// is freed. |
| 281 | /// |
| 282 | /// # Usage |
| 283 | /// The type is intended to be used like this: |
| 284 | /// 1. create it using [`MemoryMapBackingMemory::new`] |
| 285 | /// 2. pass it to [`boot::get_memory_map`] |
| 286 | /// 3. construct a [`MemoryMapOwned`] from it |
| 287 | /// |
| 288 | /// [`boot::get_memory_map`]: crate::boot::get_memory_map |
| 289 | #[derive(Debug)] |
| 290 | pub(crate) struct MemoryMapBackingMemory(NonNull<[u8]>); |
| 291 | |
| 292 | impl MemoryMapBackingMemory { |
| 293 | /// Constructs a new [`MemoryMapBackingMemory`]. |
| 294 | /// |
| 295 | /// # Arguments |
| 296 | /// - `memory_type`: The memory type for the memory map allocation. |
| 297 | /// Typically, [`MemoryType::LOADER_DATA`] for regular UEFI applications. |
| 298 | pub(crate) fn new(memory_type: MemoryType) -> crate::Result<Self> { |
| 299 | let memory_map_meta = boot::memory_map_size(); |
| 300 | let len = Self::safe_allocation_size_hint(memory_map_meta); |
| 301 | let ptr = boot::allocate_pool(memory_type, len)?.as_ptr(); |
| 302 | // Initialize all bytes. |
| 303 | // |
| 304 | // SAFETY: Pointer is valid. |
| 305 | unsafe { |
| 306 | ptr.write_bytes(0, len); |
| 307 | }; |
| 308 | |
| 309 | // Should be fine as UEFI always has allocations with a guaranteed |
| 310 | // alignment of 8 bytes. |
| 311 | assert_eq!(ptr.align_offset(align_of::<MemoryDescriptor>()), 0); |
| 312 | |
| 313 | // If this panics, the UEFI implementation is broken. |
| 314 | assert_eq!(memory_map_meta.map_size % memory_map_meta.desc_size, 0); |
| 315 | |
| 316 | // SAFETY: The memory is valid. |
| 317 | unsafe { Ok(Self::from_raw(ptr, len)) } |
| 318 | } |
| 319 | |
| 320 | unsafe fn from_raw(ptr: *mut u8, len: usize) -> Self { |
| 321 | assert_eq!(ptr.align_offset(align_of::<MemoryDescriptor>()), 0); |
| 322 | |
| 323 | let ptr = NonNull::new(ptr).expect("UEFI should never return a null ptr. An error should have been reflected via an Err earlier."); |
| 324 | let slice = NonNull::slice_from_raw_parts(ptr, len); |
| 325 | |
| 326 | Self(slice) |
| 327 | } |
| 328 | |
| 329 | /// INTERNAL, for unit tests. |
| 330 | /// |
| 331 | /// Creates an instance from the provided memory, which is not necessarily |
| 332 | /// on the UEFI heap. |
| 333 | #[cfg(test)] |
| 334 | pub(crate) fn from_slice(buffer: &mut [u8]) -> Self { |
| 335 | let len = buffer.len(); |
| 336 | // SAFETY: The memory is valid. |
| 337 | unsafe { Self::from_raw(buffer.as_mut_ptr(), len) } |
| 338 | } |
| 339 | |
| 340 | /// Returns a "safe" best-effort size hint for the memory map size with |
| 341 | /// some additional bytes in buffer compared to the [`MemoryMapMeta`]. This |
| 342 | /// takes into account that, as you go, more (small) allocations might |
| 343 | /// happen. |
| 344 | #[must_use] |
| 345 | const fn safe_allocation_size_hint(mmm: MemoryMapMeta) -> usize { |
| 346 | // Allocate space for extra entries beyond the current size of the |
| 347 | // memory map. The value of 8 matches the value in the Linux kernel: |
| 348 | // https://github.com/torvalds/linux/blob/e544a07438/drivers/firmware/efi/libstub/efistub.h#L173 |
| 349 | const EXTRA_ENTRIES: usize = 8; |
| 350 | |
| 351 | let extra_size = mmm.desc_size * EXTRA_ENTRIES; |
| 352 | mmm.map_size + extra_size |
| 353 | } |
| 354 | |
| 355 | /// Returns a slice to the underlying memory. |
| 356 | #[must_use] |
| 357 | pub const fn as_slice(&self) -> &[u8] { |
| 358 | // SAFETY: Memory is valid and initialized. |
| 359 | unsafe { self.0.as_ref() } |
| 360 | } |
| 361 | |
| 362 | /// Returns a mutable slice to the underlying memory. |
| 363 | #[must_use] |
| 364 | pub const fn as_mut_slice(&mut self) -> &mut [u8] { |
| 365 | // SAFETY: Memory is valid and initialized. |
| 366 | unsafe { self.0.as_mut() } |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | // Don't drop when we use this in unit tests. |
| 371 | impl Drop for MemoryMapBackingMemory { |
| 372 | fn drop(&mut self) { |
| 373 | if boot::are_boot_services_active() { |
| 374 | // SAFETY: This pointer was allocated by the matching UEFI allocator. |
| 375 | let res = unsafe { boot::free_pool(self.0.cast()) }; |
| 376 | if let Err(e) = res { |
| 377 | log::error!("Failed to deallocate memory map: {e:?}"); |
| 378 | } |
| 379 | } else { |
| 380 | log::debug!( |
| 381 | "Boot services are exited. Memory map won't be freed using the UEFI boot services allocator." |
| 382 | ); |
| 383 | } |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | /// Implementation of [`MemoryMapMut`] that owns the buffer on the UEFI heap. |
| 388 | #[derive(Debug)] |
| 389 | pub struct MemoryMapOwned { |
| 390 | /// Backing memory, properly initialized at this point. |
| 391 | pub(crate) buf: MemoryMapBackingMemory, |
| 392 | pub(crate) meta: MemoryMapMeta, |
| 393 | pub(crate) len: usize, |
| 394 | } |
| 395 | |
| 396 | impl MemoryMapOwned { |
| 397 | /// Creates a [`MemoryMapOwned`] from the given **initialized** memory map |
| 398 | /// (stored inside the provided buffer) and the corresponding |
| 399 | /// [`MemoryMapMeta`]. |
| 400 | pub(crate) fn from_initialized_mem(buf: MemoryMapBackingMemory, meta: MemoryMapMeta) -> Self { |
| 401 | // `sort` trusts `map_size` when it accesses descriptors through the |
| 402 | // backing memory, so the map must fit into it. |
| 403 | assert!( |
| 404 | meta.map_size <= buf.as_slice().len(), |
| 405 | "The memory map size should not exceed the backing memory" |
| 406 | ); |
| 407 | // Validate `desc_size` fully: besides being large enough, it must be a |
| 408 | // multiple of the descriptor alignment. Otherwise descriptors past the |
| 409 | // first would be accessed through misaligned references. |
| 410 | let len = validate_meta(meta).expect("The memory map metadata should be valid"); |
| 411 | Self { buf, meta, len } |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | impl MemoryMap for MemoryMapOwned { |
| 416 | fn meta(&self) -> MemoryMapMeta { |
| 417 | self.meta |
| 418 | } |
| 419 | |
| 420 | fn key(&self) -> MemoryMapKey { |
| 421 | self.meta.map_key |
| 422 | } |
| 423 | |
| 424 | fn len(&self) -> usize { |
| 425 | self.len |
| 426 | } |
| 427 | |
| 428 | fn buffer(&self) -> &[u8] { |
| 429 | &self.buf.as_slice()[..self.meta.map_size] |
| 430 | } |
| 431 | |
| 432 | fn entries(&self) -> MemoryMapIter<'_> { |
| 433 | MemoryMapIter { |
| 434 | memory_map: self, |
| 435 | index: 0, |
| 436 | } |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | impl MemoryMapMut for MemoryMapOwned { |
| 441 | fn sort(&mut self) { |
| 442 | let mut reference = MemoryMapRefMut { |
| 443 | buf: self.buf.as_mut_slice(), |
| 444 | meta: self.meta, |
| 445 | len: self.len, |
| 446 | }; |
| 447 | reference.sort(); |
| 448 | } |
| 449 | |
| 450 | unsafe fn buffer_mut(&mut self) -> &mut [u8] { |
| 451 | &mut self.buf.as_mut_slice()[..self.meta.map_size] |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | impl Index<usize> for MemoryMapOwned { |
| 456 | type Output = MemoryDescriptor; |
| 457 | |
| 458 | fn index(&self, index: usize) -> &Self::Output { |
| 459 | self.get(index).unwrap() |
| 460 | } |
| 461 | } |
| 462 | |
| 463 | impl IndexMut<usize> for MemoryMapOwned { |
| 464 | fn index_mut(&mut self, index: usize) -> &mut Self::Output { |
| 465 | self.get_mut(index).unwrap() |
| 466 | } |
| 467 | } |
| 468 | |
| 469 | #[cfg(test)] |
| 470 | mod tests { |
| 471 | use super::*; |
| 472 | use alloc::vec::Vec; |
| 473 | use size_of; |
| 474 | |
| 475 | const BASE_MMAP_UNSORTED: [MemoryDescriptor; 3] = [ |
| 476 | MemoryDescriptor { |
| 477 | ty: MemoryType::CONVENTIONAL, |
| 478 | padding: 0, |
| 479 | phys_start: 0x3000, |
| 480 | virt_start: 0x3000, |
| 481 | page_count: 1, |
| 482 | att: MemoryAttribute::WRITE_BACK, |
| 483 | }, |
| 484 | MemoryDescriptor { |
| 485 | ty: MemoryType::CONVENTIONAL, |
| 486 | padding: 0, |
| 487 | phys_start: 0x2000, |
| 488 | virt_start: 0x2000, |
| 489 | page_count: 1, |
| 490 | att: MemoryAttribute::WRITE_BACK, |
| 491 | }, |
| 492 | MemoryDescriptor { |
| 493 | ty: MemoryType::CONVENTIONAL, |
| 494 | padding: 0, |
| 495 | phys_start: 0x1000, |
| 496 | virt_start: 0x1000, |
| 497 | page_count: 1, |
| 498 | att: MemoryAttribute::WRITE_BACK, |
| 499 | }, |
| 500 | ]; |
| 501 | |
| 502 | /// Returns a copy of [`BASE_MMAP_UNSORTED`] owned on the stack. |
| 503 | const fn new_mmap_memory() -> [MemoryDescriptor; 3] { |
| 504 | BASE_MMAP_UNSORTED |
| 505 | } |
| 506 | |
| 507 | fn mmap_raw<'a>(memory: &mut [MemoryDescriptor]) -> (&'a mut [u8], MemoryMapMeta) { |
| 508 | let desc_size = size_of::<MemoryDescriptor>(); |
| 509 | let len = size_of_val(memory); |
| 510 | let ptr = memory.as_mut_ptr().cast::<u8>(); |
| 511 | // SAFETY: The pointer is valid for the requested slice length. |
| 512 | let slice = unsafe { core::slice::from_raw_parts_mut(ptr, len) }; |
| 513 | let meta = MemoryMapMeta { |
| 514 | map_size: len, |
| 515 | desc_size, |
| 516 | map_key: Default::default(), |
| 517 | desc_version: MemoryDescriptor::VERSION, |
| 518 | }; |
| 519 | (slice, meta) |
| 520 | } |
| 521 | |
| 522 | /// Basic sanity checks for the type [`MemoryMapRef`]. |
| 523 | #[test] |
| 524 | fn memory_map_ref() { |
| 525 | let mut memory = new_mmap_memory(); |
| 526 | let (mmap, meta) = mmap_raw(&mut memory); |
| 527 | let mmap = MemoryMapRef::new(mmap, meta).unwrap(); |
| 528 | |
| 529 | assert_eq!(mmap.entries().count(), 3); |
| 530 | assert_eq!( |
| 531 | mmap.entries().copied().collect::<Vec<_>>().as_slice(), |
| 532 | &BASE_MMAP_UNSORTED |
| 533 | ); |
| 534 | let mut entries = mmap.entries(); |
| 535 | assert_eq!(entries.len(), 3); |
| 536 | assert!(entries.next().is_some()); |
| 537 | assert_eq!(entries.len(), 2); |
| 538 | assert!(!mmap.is_sorted()); |
| 539 | } |
| 540 | |
| 541 | /// Basic sanity checks for the type [`MemoryMapRefMut`]. |
| 542 | #[test] |
| 543 | fn memory_map_ref_mut() { |
| 544 | let mut memory = new_mmap_memory(); |
| 545 | let (mmap, meta) = mmap_raw(&mut memory); |
| 546 | let mut mmap = MemoryMapRefMut::new(mmap, meta).unwrap(); |
| 547 | |
| 548 | assert_eq!(mmap.entries().count(), 3); |
| 549 | assert_eq!( |
| 550 | mmap.entries().copied().collect::<Vec<_>>().as_slice(), |
| 551 | &BASE_MMAP_UNSORTED |
| 552 | ); |
| 553 | assert!(!mmap.is_sorted()); |
| 554 | mmap.sort(); |
| 555 | assert!(mmap.is_sorted()); |
| 556 | } |
| 557 | |
| 558 | #[test] |
| 559 | fn memory_map_ref_mut_sorts_empty_map() { |
| 560 | let mut memory: [MemoryDescriptor; 0] = []; |
| 561 | let desc_size = size_of::<MemoryDescriptor>(); |
| 562 | // SAFETY: The pointer is valid for the requested slice length. |
| 563 | let raw = unsafe { core::slice::from_raw_parts_mut(memory.as_mut_ptr().cast(), 0) }; |
| 564 | let meta = MemoryMapMeta { |
| 565 | map_size: 0, |
| 566 | desc_size, |
| 567 | map_key: Default::default(), |
| 568 | desc_version: MemoryDescriptor::VERSION, |
| 569 | }; |
| 570 | |
| 571 | let mut mmap = MemoryMapRefMut::new(raw, meta).unwrap(); |
| 572 | mmap.sort(); |
| 573 | |
| 574 | assert!(mmap.is_empty()); |
| 575 | assert!(mmap.is_sorted()); |
| 576 | } |
| 577 | |
| 578 | #[test] |
| 579 | fn memory_map_ref_rejects_invalid_meta() { |
| 580 | let mut memory = [MemoryDescriptor::default(); 2]; |
| 581 | let raw_len = size_of_val(&memory); |
| 582 | // SAFETY: The pointer is valid for the requested slice length. |
| 583 | let raw = unsafe { core::slice::from_raw_parts_mut(memory.as_mut_ptr().cast(), raw_len) }; |
| 584 | let desc_size = size_of::<MemoryDescriptor>(); |
| 585 | let base_meta = MemoryMapMeta { |
| 586 | map_size: desc_size, |
| 587 | desc_size, |
| 588 | map_key: Default::default(), |
| 589 | desc_version: MemoryDescriptor::VERSION, |
| 590 | }; |
| 591 | |
| 592 | let mut meta = base_meta; |
| 593 | meta.desc_size = 0; |
| 594 | assert!(matches!( |
| 595 | MemoryMapRef::new(raw, meta), |
| 596 | Err(MemoryMapError::InvalidSize) |
| 597 | )); |
| 598 | |
| 599 | let mut meta = base_meta; |
| 600 | meta.desc_size = desc_size - 1; |
| 601 | assert!(matches!( |
| 602 | MemoryMapRef::new(raw, meta), |
| 603 | Err(MemoryMapError::InvalidSize) |
| 604 | )); |
| 605 | |
| 606 | let mut meta = base_meta; |
| 607 | meta.desc_size = desc_size + 1; |
| 608 | meta.map_size = meta.desc_size; |
| 609 | assert!(matches!( |
| 610 | MemoryMapRef::new(raw, meta), |
| 611 | Err(MemoryMapError::InvalidSize) |
| 612 | )); |
| 613 | |
| 614 | let mut meta = base_meta; |
| 615 | meta.map_size = desc_size + 1; |
| 616 | assert!(matches!( |
| 617 | MemoryMapRef::new(raw, meta), |
| 618 | Err(MemoryMapError::InvalidSize) |
| 619 | )); |
| 620 | } |
| 621 | |
| 622 | /// Basic sanity checks for the type [`MemoryMapOwned`]. |
| 623 | #[test] |
| 624 | fn memory_map_owned() { |
| 625 | let mut memory = new_mmap_memory(); |
| 626 | let (mmap, meta) = mmap_raw(&mut memory); |
| 627 | let mmap = MemoryMapBackingMemory::from_slice(mmap); |
| 628 | let mut mmap = MemoryMapOwned::from_initialized_mem(mmap, meta); |
| 629 | |
| 630 | assert_eq!(mmap.entries().count(), 3); |
| 631 | assert_eq!( |
| 632 | mmap.entries().copied().collect::<Vec<_>>().as_slice(), |
| 633 | &BASE_MMAP_UNSORTED |
| 634 | ); |
| 635 | assert!(!mmap.is_sorted()); |
| 636 | mmap.sort(); |
| 637 | assert!(mmap.is_sorted()); |
| 638 | } |
| 639 | |
| 640 | #[test] |
| 641 | fn memory_map_owned_buffer_uses_map_size() { |
| 642 | let mut memory = [MemoryDescriptor::default(); 4]; |
| 643 | memory[..BASE_MMAP_UNSORTED.len()].copy_from_slice(&BASE_MMAP_UNSORTED); |
| 644 | |
| 645 | let desc_size = size_of::<MemoryDescriptor>(); |
| 646 | let map_size = BASE_MMAP_UNSORTED.len() * desc_size; |
| 647 | let raw_len = size_of_val(&memory); |
| 648 | // SAFETY: The pointer is valid for the requested slice length. |
| 649 | let raw = unsafe { core::slice::from_raw_parts_mut(memory.as_mut_ptr().cast(), raw_len) }; |
| 650 | let meta = MemoryMapMeta { |
| 651 | map_size, |
| 652 | desc_size, |
| 653 | map_key: Default::default(), |
| 654 | desc_version: MemoryDescriptor::VERSION, |
| 655 | }; |
| 656 | |
| 657 | let mmap = MemoryMapBackingMemory::from_slice(raw); |
| 658 | let mut mmap = MemoryMapOwned::from_initialized_mem(mmap, meta); |
| 659 | |
| 660 | assert_eq!(mmap.buffer().len(), map_size); |
| 661 | // SAFETY: The memory is valid. |
| 662 | assert_eq!(unsafe { mmap.buffer_mut() }.len(), map_size); |
| 663 | } |
| 664 | |
| 665 | /// The map must fit into the backing memory, as `sort` accesses the |
| 666 | /// descriptors without bounds checks against the buffer. |
| 667 | #[test] |
| 668 | #[should_panic(expected = "should not exceed the backing memory")] |
| 669 | fn memory_map_owned_map_size_exceeds_buffer() { |
| 670 | let mut memory = new_mmap_memory(); |
| 671 | let (mmap, mut meta) = mmap_raw(&mut memory); |
| 672 | meta.map_size += meta.desc_size; |
| 673 | let mmap = MemoryMapBackingMemory::from_slice(mmap); |
| 674 | let mut mmap = MemoryMapOwned::from_initialized_mem(mmap, meta); |
| 675 | mmap.sort(); |
| 676 | } |
| 677 | } |