-
-
Notifications
You must be signed in to change notification settings - Fork 170
Directory::read_entry_boxed
plus common abstraction make_boxed
#559
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
53ee64a
fs: add method read_entry_boxed to Directory + test
phip1611 a9e410b
add memory util `mem::make_boxed`
phip1611 b4f52b4
make_boxed: prevent 'explicit_generic_args_with_impl_trait' due to MSRV
phip1611 f612991
xtask/miri: remove flag that is enabled by default
phip1611 5fdccbd
make_boxed: add tests for different alignments
phip1611 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,179 @@ | ||
//! This is a utility module with helper methods for allocations/memory. | ||
|
||
use crate::ResultExt; | ||
use crate::{Result, Status}; | ||
use ::alloc::{alloc, boxed::Box}; | ||
use core::alloc::Layout; | ||
use core::fmt::Debug; | ||
use core::slice; | ||
use uefi::data_types::Align; | ||
use uefi::Error; | ||
|
||
/// Helper to return owned versions of certain UEFI data structures on the heap in a [`Box`]. This | ||
/// function is intended to wrap low-level UEFI functions of this crate that | ||
/// - can consume an empty buffer without a panic to get the required buffer size in the errors | ||
/// payload, | ||
/// - consume a mutable reference to a buffer that will be filled with some data if the provided | ||
/// buffer size is sufficient, and | ||
/// - return a mutable typed reference that points to the same memory as the input buffer on | ||
/// success. | ||
pub fn make_boxed< | ||
'a, | ||
Data: Align + ?Sized + Debug + 'a, | ||
F: FnMut(&'a mut [u8]) -> Result<&'a mut Data, Option<usize>>, | ||
>( | ||
mut fetch_data_fn: F, | ||
) -> Result<Box<Data>> { | ||
let required_size = match fetch_data_fn(&mut []).map_err(Error::split) { | ||
// This is the expected case: the empty buffer passed in is too | ||
// small, so we get the required size. | ||
Err((Status::BUFFER_TOO_SMALL, Some(required_size))) => Ok(required_size), | ||
// Propagate any other error. | ||
Err((status, _)) => Err(Error::from(status)), | ||
// Success is unexpected, return an error. | ||
Ok(_) => Err(Error::from(Status::UNSUPPORTED)), | ||
}?; | ||
|
||
// We add trailing padding because the size of a rust structure must | ||
// always be a multiple of alignment. | ||
let layout = Layout::from_size_align(required_size, Data::alignment()) | ||
.unwrap() | ||
.pad_to_align(); | ||
|
||
// Allocate the buffer. | ||
let heap_buf: *mut u8 = unsafe { | ||
let ptr = alloc::alloc(layout); | ||
if ptr.is_null() { | ||
return Err(Status::OUT_OF_RESOURCES.into()); | ||
} | ||
ptr | ||
}; | ||
|
||
// Read the data into the provided buffer. | ||
let data: Result<&mut Data> = { | ||
let buffer = unsafe { slice::from_raw_parts_mut(heap_buf, required_size) }; | ||
fetch_data_fn(buffer).discard_errdata() | ||
}; | ||
|
||
// If an error occurred, deallocate the memory before returning. | ||
let data: &mut Data = match data { | ||
Ok(data) => data, | ||
Err(err) => { | ||
unsafe { alloc::dealloc(heap_buf, layout) }; | ||
return Err(err); | ||
} | ||
}; | ||
|
||
let data = unsafe { Box::from_raw(data) }; | ||
|
||
Ok(data) | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
use crate::ResultExt; | ||
use core::mem::{align_of, size_of}; | ||
|
||
/// Some simple dummy type to test [`make_boxed`]. | ||
#[derive(Debug)] | ||
#[repr(C)] | ||
struct SomeData([u8; 4]); | ||
|
||
impl Align for SomeData { | ||
fn alignment() -> usize { | ||
align_of::<Self>() | ||
} | ||
} | ||
|
||
/// Type wrapper that ensures an alignment of 16 for the underlying data. | ||
#[derive(Debug)] | ||
#[repr(C, align(16))] | ||
struct Align16<T>(T); | ||
|
||
/// Version of [`SomeData`] that has an alignment of 16. | ||
type SomeDataAlign16 = Align16<SomeData>; | ||
|
||
impl Align for SomeDataAlign16 { | ||
fn alignment() -> usize { | ||
align_of::<Self>() | ||
} | ||
} | ||
|
||
/// Function that behaves like the other UEFI functions. It takes a | ||
/// mutable reference to a buffer memory that represents a [`SomeData`] | ||
/// instance. | ||
fn uefi_function_stub_read<Data: Align>(buf: &mut [u8]) -> Result<&mut Data, Option<usize>> { | ||
let required_size = size_of::<Data>(); | ||
|
||
if buf.len() < required_size { | ||
// We can use an zero-length buffer to find the required size. | ||
return Status::BUFFER_TOO_SMALL.into_with(|| panic!(), |_| Some(required_size)); | ||
}; | ||
|
||
// assert alignment | ||
assert_eq!( | ||
buf.as_ptr() as usize % Data::alignment(), | ||
0, | ||
"The buffer must be correctly aligned!" | ||
); | ||
|
||
buf[0] = 1; | ||
buf[1] = 2; | ||
buf[2] = 3; | ||
buf[3] = 4; | ||
|
||
let data = unsafe { &mut *buf.as_mut_ptr().cast::<Data>() }; | ||
|
||
Ok(data) | ||
} | ||
|
||
// Some basic sanity checks so that we can catch problems early that miri would detect | ||
// otherwise. | ||
#[test] | ||
fn test_some_data_type_size_constraints() { | ||
assert_eq!(size_of::<SomeData>(), 4); | ||
assert_eq!(SomeData::alignment(), 1); | ||
assert_eq!( | ||
size_of::<SomeDataAlign16>(), | ||
16, | ||
"The size must be 16 instead of 4, as in Rust the runtime size is a multiple of the alignment." | ||
); | ||
assert_eq!(SomeDataAlign16::alignment(), 16); | ||
} | ||
|
||
// Tests `uefi_function_stub_read` which is the foundation for the `test_make_boxed_utility` | ||
// test. | ||
#[test] | ||
fn test_basic_stub_read() { | ||
assert_eq!( | ||
uefi_function_stub_read::<SomeData>(&mut []).status(), | ||
Status::BUFFER_TOO_SMALL | ||
); | ||
assert_eq!( | ||
*uefi_function_stub_read::<SomeData>(&mut []) | ||
.unwrap_err() | ||
.data(), | ||
Some(4) | ||
); | ||
|
||
let mut buf: [u8; 4] = [0; 4]; | ||
let data: &mut SomeData = uefi_function_stub_read(&mut buf).unwrap(); | ||
assert_eq!(&data.0, &[1, 2, 3, 4]); | ||
|
||
let mut buf: Align16<[u8; 16]> = Align16([0; 16]); | ||
let data: &mut SomeDataAlign16 = uefi_function_stub_read(&mut buf.0).unwrap(); | ||
assert_eq!(&data.0 .0, &[1, 2, 3, 4]); | ||
} | ||
|
||
#[test] | ||
fn test_make_boxed_utility() { | ||
let fetch_data_fn = |buf| uefi_function_stub_read(buf); | ||
let data: Box<SomeData> = make_boxed(fetch_data_fn).unwrap(); | ||
assert_eq!(&data.0, &[1, 2, 3, 4]); | ||
|
||
let fetch_data_fn = |buf| uefi_function_stub_read(buf); | ||
let data: Box<SomeDataAlign16> = make_boxed(fetch_data_fn).unwrap(); | ||
assert_eq!(&data.0 .0, &[1, 2, 3, 4]); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.