Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/vendor/uefi/src/allocator.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / vendor / uefi / src / allocator.rs` 180 lines ยท 7946 bytes Raw Blame History 1 // SPDX-License-Identifier: MIT OR Apache-2.0 2 3 //! This module exports [`Allocator`]. 4 //! 5 //! The allocator can be used as global Rust allocator using the 6 //! `global_allocator` crate feature. See [`helpers`] for more info. 7 //! 8 //! [`helpers`]: uefi::helpers 9 10 use crate::boot::{self, AllocateType}; 11 use crate::mem::memory_map::MemoryType; 12 use crate::proto::loaded_image::LoadedImage; 13 use core::alloc::{GlobalAlloc, Layout}; 14 use core::ptr::{self, NonNull}; 15 use core::sync::atomic::{AtomicU32, Ordering}; 16 use uefi_raw::table::boot::PAGE_SIZE; 17 18 /// Get the memory type to use for allocation. 19 /// 20 /// The first time this is called, the data type of the loaded image will be 21 /// retrieved. That value is cached in a static and reused on subsequent 22 /// calls. If the memory type of the loaded image cannot be retrieved for some 23 /// reason, a default of `LOADER_DATA` is used. 24 fn get_memory_type() -> MemoryType { 25 // Initialize to a `RESERVED` to indicate the actual value hasn't been set yet. 26 static MEMORY_TYPE: AtomicU32 = AtomicU32::new(MemoryType::RESERVED.0); 27 28 let memory_type = MEMORY_TYPE.load(Ordering::Acquire); 29 if memory_type == MemoryType::RESERVED.0 { 30 let memory_type = if let Ok(loaded_image) = 31 boot::open_protocol_exclusive::(boot::image_handle()) 32 { 33 loaded_image.data_type() 34 } else { 35 MemoryType::LOADER_DATA 36 }; 37 MEMORY_TYPE.store(memory_type.0, Ordering::Release); 38 memory_type 39 } else { 40 MemoryType(memory_type) 41 } 42 } 43 44 /// Helper to get a custom alignment out of an allocation with an alignment of 45 /// eight (UEFI default alignment). This works by allocating extra space and 46 /// storing a pointer to the actual allocation right above the allocation 47 /// handed out via the public API. 48 fn alloc_pool_aligned(memory_type: MemoryType, size: usize, align: usize) -> *mut u8 { 49 let full_alloc_ptr = boot::allocate_pool(memory_type, size + align); 50 let full_alloc_ptr = if let Ok(ptr) = full_alloc_ptr { 51 ptr.as_ptr() 52 } else { 53 return ptr::null_mut(); 54 }; 55 56 // Calculate the offset needed to get an aligned pointer within the 57 // full allocation. If that offset is zero, increase it to `align` 58 // so that we still have space to store the extra pointer described 59 // below. 60 let mut offset = full_alloc_ptr.align_offset(align); 61 if offset == 0 { 62 offset = align; 63 } 64 65 // SAFETY: `full_alloc_ptr` points to a valid allocation large enough for 66 // `size + align + size_of::<*mut u8>()`. Adding `offset` keeps 67 // `aligned_ptr` within that allocation and yields the requested alignment. 68 // The allocation size includes enough extra space to reserve the bytes 69 // immediately preceding `aligned_ptr`, where we store `full_alloc_ptr` so 70 // the original allocation can later be recovered. Because `aligned_ptr` is 71 // aligned and valid alignments are powers of two as enforced by `Layout`, 72 // the slot at `aligned_ptr.cast::<*mut u8>().sub(1)` is properly aligned 73 // for writing a `*mut u8`. 74 unsafe { 75 let aligned_ptr = full_alloc_ptr.add(offset); 76 (aligned_ptr.cast::<*mut u8>()).sub(1).write(full_alloc_ptr); 77 aligned_ptr 78 } 79 } 80 81 /// Returns whether the allocation is a multiple of a [`PAGE_SIZE`] and is 82 /// aligned to [`PAGE_SIZE`]. 83 /// 84 /// This does not only check the alignment but also the size. For types 85 /// allocated by Rust itself (e.g., `Box`), the size is always at least the 86 /// alignment, as specified in the [Rust type layout]. However, to be also safe 87 /// when it comes to manual invocations, we additionally check if the size is 88 /// a multiple of [`PAGE_SIZE`]. 89 /// 90 /// [Rust type layout]: https://doc.rust-lang.org/reference/type-layout.html 91 const fn layout_allows_page_alloc_shortcut(layout: &Layout) -> bool { 92 layout.size().is_multiple_of(PAGE_SIZE) && layout.align() == PAGE_SIZE 93 } 94 95 /// Allocator using UEFI boot services. 96 /// 97 /// This type implements [`GlobalAlloc`] and can be marked with the 98 /// `#[global_allocator]` attribute to be used as global Rust allocator. 99 /// 100 /// Note that if boot services are not active (anymore), [`Allocator::alloc`] 101 /// will return a null pointer and [`Allocator::dealloc`] will panic. 102 #[derive(Debug)] 103 pub struct Allocator; 104 105 // SAFETY: `alloc` delegates to UEFI's pool allocator, which returns correctly 106 // aligned, non-aliasing memory. `dealloc` only frees pointers previously returned 107 // by the matching `alloc` call with the same layout. 108 unsafe impl GlobalAlloc for Allocator { 109 /// Allocate memory using the UEFI boot services. 110 /// 111 /// The allocation's [memory type] matches the current image's [data type]. 112 /// 113 /// [memory type]: MemoryType 114 /// [data type]: LoadedImage::data_type 115 unsafe fn alloc(&self, layout: Layout) -> *mut u8 { 116 if !boot::are_boot_services_active() { 117 return ptr::null_mut(); 118 } 119 120 let memory_type = get_memory_type(); 121 let use_page_shortcut = layout_allows_page_alloc_shortcut(&layout); 122 123 match (use_page_shortcut, layout.align()) { 124 // Allocating pages is actually very expected in UEFI OS loaders, so 125 // it makes sense to provide this optimization. 126 (true, _) => { 127 // To spammy, but useful for manual testing. 128 // log::trace!("Taking PAGE_SIZE shortcut for layout={layout:?}"); 129 let count = layout.size().div_ceil(PAGE_SIZE); 130 boot::allocate_pages(AllocateType::AnyPages, memory_type, count) 131 .map(|ptr| ptr.as_ptr()) 132 .unwrap_or(ptr::null_mut()) 133 } 134 (false, 0..=8 /* UEFI default alignment */) => { 135 // The requested alignment is less than or equal to eight, and 136 // `allocate_pool` always provides eight-byte alignment, so we can 137 // use `allocate_pool` directly. 138 boot::allocate_pool(memory_type, layout.size()) 139 .map(|ptr| ptr.as_ptr()) 140 .unwrap_or(ptr::null_mut()) 141 } 142 (false, 9..) => alloc_pool_aligned(memory_type, layout.size(), layout.align()), 143 } 144 } 145 146 /// Deallocate memory using the UEFI boot services. 147 /// 148 /// This will panic after exiting boot services. 149 unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { 150 let ptr = NonNull::new(ptr).unwrap(); 151 152 let use_page_shortcut = layout_allows_page_alloc_shortcut(&layout); 153 154 match (use_page_shortcut, layout.align()) { 155 (true, _) => { 156 // To spammy, but useful for manual testing. 157 // log::trace!("Taking PAGE_SIZE shortcut for layout={layout:?}"); 158 let count = layout.size().div_ceil(PAGE_SIZE); 159 // SAFETY: This pointer was allocated by the matching UEFI allocator. 160 unsafe { boot::free_pages(ptr, count).unwrap() } 161 } 162 (false, 0..=8 /* UEFI default alignment */) => { 163 // Warning: this will panic after exiting boot services. 164 // SAFETY: This pointer was allocated by the matching UEFI allocator. 165 unsafe { boot::free_pool(ptr) }.unwrap(); 166 } 167 (false, 9..) => { 168 let ptr = ptr.as_ptr().cast::<*mut u8>(); 169 // SAFETY: Retrieve the in-bounds pointer to the full allocation 170 // that was packed right before the aligned allocation in 171 // `alloc()`. 172 let actual_alloc_ptr = unsafe { ptr.sub(1).read() }; 173 let ptr = NonNull::new(actual_alloc_ptr).unwrap(); 174 // Warning: this will panic after exiting boot services. 175 // SAFETY: This pointer was allocated by the matching UEFI allocator. 176 unsafe { boot::free_pool(ptr) }.unwrap(); 177 } 178 } 179 } 180 }