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 / util.rs
| 1 | // SPDX-License-Identifier: MIT OR Apache-2.0 |
| 2 | |
| 3 | //! This is a utility module with helper methods for allocations/memory. |
| 4 | |
| 5 | use crate::data_types::Align; |
| 6 | use crate::{Error, Result, Status}; |
| 7 | use ::alloc::alloc::{alloc, dealloc, realloc}; |
| 8 | use ::alloc::boxed::Box; |
| 9 | use core::alloc::Layout; |
| 10 | use core::ptr::{self, NonNull}; |
| 11 | use core::slice; |
| 12 | use ptr_meta::Pointee; |
| 13 | |
| 14 | /// Calls `fetch_data_fn` with an empty buffer to learn the size it needs. |
| 15 | fn query_required_size<'a, Data: ?Sized + 'a>( |
| 16 | fetch_data_fn: &mut impl FnMut(&'a mut [u8]) -> Result<&'a mut Data, Option<usize>>, |
| 17 | ) -> Result<usize> { |
| 18 | match fetch_data_fn(&mut []).map_err(Error::split) { |
| 19 | // The expected case: the empty buffer is too small, and the error |
| 20 | // payload tells us how much is needed. A size of zero contradicts |
| 21 | // that error and cannot be allocated, so treat it as a missing size. |
| 22 | Err((Status::BUFFER_TOO_SMALL, Some(size))) if size > 0 => Ok(size), |
| 23 | Err((status, _)) => Err(status.into()), |
| 24 | Ok(_) => { |
| 25 | log::debug!("empty buffer was unexpectedly accepted"); |
| 26 | Err(Status::UNSUPPORTED.into()) |
| 27 | } |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | /// Resizes the allocation `buf` so that it exactly matches `value_layout`, |
| 32 | /// and returns the address of the resized allocation. |
| 33 | /// |
| 34 | /// # Safety |
| 35 | /// |
| 36 | /// `buf` must be an allocation of `layout` that nothing else owns, and |
| 37 | /// `value_layout` must have the same alignment as `layout` and must not be |
| 38 | /// larger than it. |
| 39 | unsafe fn fit_allocation( |
| 40 | buf: NonNull<u8>, |
| 41 | layout: Layout, |
| 42 | value_layout: Layout, |
| 43 | ) -> Result<*mut u8> { |
| 44 | debug_assert_eq!(value_layout.align(), layout.align()); |
| 45 | debug_assert!(value_layout.size() <= layout.size()); |
| 46 | |
| 47 | if value_layout.size() == layout.size() { |
| 48 | return Ok(buf.as_ptr()); |
| 49 | } |
| 50 | |
| 51 | if value_layout.size() == 0 { |
| 52 | // A zero-sized value does not own an allocation, it just needs a |
| 53 | // well-aligned address. |
| 54 | // SAFETY: Guaranteed by the caller. |
| 55 | unsafe { dealloc(buf.as_ptr(), layout) }; |
| 56 | return Ok(ptr::without_provenance_mut(value_layout.align())); |
| 57 | } |
| 58 | |
| 59 | // SAFETY: Guaranteed by the caller. The new size is non-zero and smaller |
| 60 | // than the current one, so this is a valid shrink. |
| 61 | let shrunk = unsafe { realloc(buf.as_ptr(), layout, value_layout.size()) }; |
| 62 | if shrunk.is_null() { |
| 63 | // SAFETY: A failed `realloc` leaves the original allocation intact. |
| 64 | unsafe { dealloc(buf.as_ptr(), layout) }; |
| 65 | return Err(Status::OUT_OF_RESOURCES.into()); |
| 66 | } |
| 67 | Ok(shrunk) |
| 68 | } |
| 69 | |
| 70 | /// Helper to return owned versions of certain UEFI data structures on the heap |
| 71 | /// in a [`Box`]. |
| 72 | /// |
| 73 | /// This function is intended to wrap low-level UEFI functions of this crate |
| 74 | /// that: |
| 75 | /// - can consume an empty buffer without a panic to get the required buffer |
| 76 | /// size in the errors payload, |
| 77 | /// - consume a mutable reference to a buffer that will be filled with some data |
| 78 | /// if the provided buffer size is sufficient, and |
| 79 | /// - return a mutable typed reference that points to the same memory as the |
| 80 | /// input buffer on success. |
| 81 | /// |
| 82 | /// The complexity here comes from the fact that we first allocate matching |
| 83 | /// memory and then we must make sure that the layout of the inner value |
| 84 | /// assumed by `Box` matches the allocation to fulfill all Rust guarantees. We |
| 85 | /// only learn the value's real size after the firmware call: we allocate what |
| 86 | /// the firmware said it needed, and the fetch closure returns what it actually |
| 87 | /// wrote, which is smaller when a file shrinks between the size query and the |
| 88 | /// read, or when firmware over-reports. Freeing a 112-byte allocation with a |
| 89 | /// 104-byte layout is undefined behavior, so the allocation is resized to match |
| 90 | /// before ownership is handed to `Box`. In the normal case the two sizes agree |
| 91 | /// and no reallocation happens at all. |
| 92 | pub(crate) fn make_boxed< |
| 93 | 'a, |
| 94 | // The UEFI data structure. |
| 95 | Data: Align + Pointee + ?Sized + 'a, |
| 96 | F: FnMut(&'a mut [u8]) -> Result<&'a mut Data, Option<usize>>, |
| 97 | >( |
| 98 | // A function to read the UEFI data structure into a provided buffer. |
| 99 | mut fetch_data_fn: F, |
| 100 | ) -> Result<Box<Data>> { |
| 101 | let required_size = query_required_size(&mut fetch_data_fn)?; |
| 102 | |
| 103 | // The size of a Rust value is always a multiple of its alignment, so the |
| 104 | // allocation needs the trailing padding on top of the reported size. |
| 105 | let layout = Layout::from_size_align(required_size, Data::alignment()) |
| 106 | .unwrap() |
| 107 | .pad_to_align(); |
| 108 | |
| 109 | // SAFETY: The layout has a non-zero size. |
| 110 | let buf = |
| 111 | NonNull::new(unsafe { alloc(layout) }).ok_or(Error::from(Status::OUT_OF_RESOURCES))?; |
| 112 | |
| 113 | // Hand out the whole allocation, padding included, so that a reference to |
| 114 | // `Data` derived from it does not exceed the provenance of this slice. |
| 115 | // SAFETY: The allocation is valid for `layout.size()` bytes. |
| 116 | let slice = unsafe { slice::from_raw_parts_mut(buf.as_ptr(), layout.size()) }; |
| 117 | |
| 118 | let data = match fetch_data_fn(slice) { |
| 119 | Ok(data) => data, |
| 120 | Err(err) => { |
| 121 | // SAFETY: Allocated with `layout` and unused from here on. |
| 122 | unsafe { dealloc(buf.as_ptr(), layout) }; |
| 123 | return Err(err.to_err_without_payload()); |
| 124 | } |
| 125 | }; |
| 126 | |
| 127 | // `Box` frees using the layout of its value, which is smaller than the |
| 128 | // allocation if the firmware wrote less than the size it reported. Freeing |
| 129 | // with a layout that does not match the allocation is undefined behavior, |
| 130 | // so resize the allocation to fit the value first. |
| 131 | let value_layout = Layout::for_value(data); |
| 132 | // Take the metadata before the resize invalidates `data`. |
| 133 | let meta = ptr_meta::metadata(ptr::from_mut(data)); |
| 134 | // SAFETY: `buf` was allocated with `layout` and holds `data` alone, whose |
| 135 | // alignment is `Data::alignment()` and whose size fits the allocation. |
| 136 | let fitted = unsafe { fit_allocation(buf, layout, value_layout)? }; |
| 137 | |
| 138 | let ptr = ptr_meta::from_raw_parts_mut(fitted.cast(), meta); |
| 139 | |
| 140 | // SAFETY: The allocation now matches the layout of the value. |
| 141 | Ok(unsafe { Box::from_raw(ptr) }) |
| 142 | } |
| 143 | |
| 144 | #[cfg(test)] |
| 145 | mod tests { |
| 146 | use super::*; |
| 147 | use crate::{ResultExt, StatusExt}; |
| 148 | |
| 149 | /// Some simple dummy type to test [`make_boxed`]. |
| 150 | #[derive(Debug)] |
| 151 | #[repr(C)] |
| 152 | struct SomeData([u8; 4]); |
| 153 | |
| 154 | impl Align for SomeData { |
| 155 | fn alignment() -> usize { |
| 156 | align_of::<Self>() |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | /// Type wrapper that ensures an alignment of 16 for the underlying data. |
| 161 | #[derive(Debug)] |
| 162 | #[repr(C, align(16))] |
| 163 | struct Align16<T>(T); |
| 164 | |
| 165 | /// Version of [`SomeData`] that has an alignment of 16. |
| 166 | type SomeDataAlign16 = Align16<SomeData>; |
| 167 | |
| 168 | impl Align for SomeDataAlign16 { |
| 169 | fn alignment() -> usize { |
| 170 | align_of::<Self>() |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | // Some basic sanity checks of the helper types so that we can catch |
| 175 | // problems early that miri would detect otherwise. |
| 176 | const _: () = { |
| 177 | assert!(size_of::<SomeData>() == 4); |
| 178 | assert!(align_of::<SomeData>() == 1); |
| 179 | // The size is 16 instead of 4, as in Rust the size is always a |
| 180 | // multiple of the alignment. |
| 181 | assert!(size_of::<SomeDataAlign16>() == 16); |
| 182 | assert!(align_of::<SomeDataAlign16>() == 16); |
| 183 | }; |
| 184 | |
| 185 | /// Function that behaves like the other UEFI functions. It takes a |
| 186 | /// mutable reference to a buffer memory that represents a [`SomeData`] |
| 187 | /// instance. |
| 188 | fn uefi_function_stub_read<Data: Align>(buf: &mut [u8]) -> Result<&mut Data, Option<usize>> { |
| 189 | let required_size = size_of::<Data>(); |
| 190 | |
| 191 | if buf.len() < required_size { |
| 192 | // We can use an zero-length buffer to find the required size. |
| 193 | return Status::BUFFER_TOO_SMALL.to_result_with(|| panic!(), |_| Some(required_size)); |
| 194 | }; |
| 195 | |
| 196 | // assert alignment |
| 197 | assert_eq!( |
| 198 | buf.as_ptr() as usize % Data::alignment(), |
| 199 | 0, |
| 200 | "The buffer must be correctly aligned!" |
| 201 | ); |
| 202 | |
| 203 | buf[0] = 1; |
| 204 | buf[1] = 2; |
| 205 | buf[2] = 3; |
| 206 | buf[3] = 4; |
| 207 | |
| 208 | // SAFETY: The buffer is not null, aligned, and initialized. |
| 209 | let data = unsafe { &mut *buf.as_mut_ptr().cast::<Data>() }; |
| 210 | |
| 211 | Ok(data) |
| 212 | } |
| 213 | |
| 214 | // Tests `uefi_function_stub_read` which is the foundation for the `test_make_boxed_utility` |
| 215 | // test. |
| 216 | #[test] |
| 217 | fn test_basic_stub_read() { |
| 218 | assert_eq!( |
| 219 | uefi_function_stub_read::<SomeData>(&mut []).status(), |
| 220 | Status::BUFFER_TOO_SMALL |
| 221 | ); |
| 222 | assert_eq!( |
| 223 | *uefi_function_stub_read::<SomeData>(&mut []) |
| 224 | .unwrap_err() |
| 225 | .data(), |
| 226 | Some(4) |
| 227 | ); |
| 228 | |
| 229 | let mut buf: [u8; 4] = [0; 4]; |
| 230 | let data: &mut SomeData = uefi_function_stub_read(&mut buf).unwrap(); |
| 231 | assert_eq!(&data.0, &[1, 2, 3, 4]); |
| 232 | |
| 233 | let mut buf: Align16<[u8; 16]> = Align16([0; 16]); |
| 234 | let data: &mut SomeDataAlign16 = uefi_function_stub_read(&mut buf.0).unwrap(); |
| 235 | assert_eq!(&data.0.0, &[1, 2, 3, 4]); |
| 236 | } |
| 237 | |
| 238 | /// A reported required size of zero is inconsistent with |
| 239 | /// `BUFFER_TOO_SMALL` for an empty buffer and must not lead to a |
| 240 | /// zero-size allocation. |
| 241 | #[test] |
| 242 | fn test_make_boxed_zero_required_size() { |
| 243 | let fetch_data_fn = |_buf: &mut [u8]| -> Result<&mut SomeData, Option<usize>> { |
| 244 | Status::BUFFER_TOO_SMALL.to_result_with(|| panic!(), |_| Some(0)) |
| 245 | }; |
| 246 | |
| 247 | let result = make_boxed(fetch_data_fn); |
| 248 | assert_eq!(result.unwrap_err().status(), Status::BUFFER_TOO_SMALL); |
| 249 | } |
| 250 | |
| 251 | /// The fetch function may return less data than it reported as |
| 252 | /// required, e.g. when the firmware over-reports the size or the data |
| 253 | /// shrinks between the two calls. The returned `Box` must then own an |
| 254 | /// allocation that matches the value, or its deallocation is undefined |
| 255 | /// behavior. |
| 256 | #[test] |
| 257 | fn test_make_boxed_shrinking_data() { |
| 258 | /// Reports 16 bytes as required, but returns only `data_len` of them. |
| 259 | fn uefi_function_stub_read_less( |
| 260 | buf: &mut [u8], |
| 261 | data_len: usize, |
| 262 | ) -> Result<&mut [u8], Option<usize>> { |
| 263 | if buf.is_empty() { |
| 264 | return Status::BUFFER_TOO_SMALL.to_result_with(|| panic!(), |_| Some(16)); |
| 265 | } |
| 266 | assert_eq!(buf.len(), 16); |
| 267 | buf[..data_len].fill(7); |
| 268 | Ok(&mut buf[..data_len]) |
| 269 | } |
| 270 | |
| 271 | for data_len in [8, 0] { |
| 272 | let fetch_data_fn = |buf| uefi_function_stub_read_less(buf, data_len); |
| 273 | |
| 274 | let data: Box<[u8]> = make_boxed(fetch_data_fn).unwrap(); |
| 275 | assert_eq!(data.len(), data_len); |
| 276 | assert!(data.iter().all(|byte| *byte == 7)); |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | /// This unit tests checks the [`make_boxed`] utility. |
| 281 | /// |
| 282 | /// This test is especially useful when run by miri. |
| 283 | #[test] |
| 284 | fn test_make_boxed_utility() { |
| 285 | let fetch_data_fn = |buf| uefi_function_stub_read(buf); |
| 286 | |
| 287 | let data: Box<SomeData> = make_boxed(fetch_data_fn).unwrap(); |
| 288 | assert_eq!(&data.0, &[1, 2, 3, 4]); |
| 289 | |
| 290 | let fetch_data_fn = |buf| uefi_function_stub_read(buf); |
| 291 | |
| 292 | let data: Box<SomeDataAlign16> = make_boxed(fetch_data_fn).unwrap(); |
| 293 | |
| 294 | assert_eq!(&data.0.0, &[1, 2, 3, 4]); |
| 295 | } |
| 296 | } |