interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / vendor / uefi / src / mem / aligned_buffer.rs

224 lines · 8153 bytes Raw Blame History
1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3use alloc::alloc::{Layout, LayoutError, alloc_zeroed, dealloc};
4use core::error::Error;
5use core::num::NonZero;
6use core::ptr::NonNull;
7use core::{fmt, slice};
8
9/// Helper class to maintain the lifetime of a memory region allocated with a non-standard alignment.
10/// Facilitates RAII to properly deallocate when lifetime of the object ends.
11///
12/// Note: This uses the global Rust allocator under the hood.
13#[derive(Debug)]
14pub struct AlignedBuffer {
15 ptr: NonNull<u8>,
16 layout: Layout,
17}
18
19impl AlignedBuffer {
20 /// Allocate a new memory region with the requested len and alignment.
21 ///
22 /// The memory is zero-initialized.
23 ///
24 /// # Panics
25 /// This method panics when the allocation fails (e.g. due to an out of memory situation).
26 pub fn from_size_align(len: usize, alignment: usize) -> Result<Self, LayoutError> {
27 let layout = Layout::from_size_align(len, alignment)?;
28 Ok(Self::from_layout(layout))
29 }
30
31 /// Allocate a new memory region with the requested layout.
32 ///
33 /// The memory is zero-initialized.
34 ///
35 /// # Panics
36 /// This method panics when the allocation fails (e.g. due to an out of memory situation).
37 #[must_use]
38 pub fn from_layout(layout: Layout) -> Self {
39 let ptr = if layout.size() == 0 {
40 // `GlobalAlloc` forbids zero-size layouts. A dangling but aligned
41 // pointer is all that a zero-length slice needs.
42 let align = NonZero::new(layout.align()).expect("layout alignment should be non-zero");
43 NonNull::without_provenance(align)
44 } else {
45 // The safe accessors (`as_slice`, `iter`, ...) hand out `&[u8]`
46 // over the whole region, so it must be initialized from the start.
47 // SAFETY: The layout has a non-zero size.
48 let ptr = unsafe { alloc_zeroed(layout) };
49 NonNull::new(ptr).expect("Allocation failed")
50 };
51 Self { ptr, layout }
52 }
53
54 // TODO: Add non-panicking method variants as soon as alloc::AllocError was stabilized (#32838).
55 // - try_from_layout(layout: Layout) -> Result<Self, AllocError>;
56
57 /// Get a pointer to the aligned memory region managed by this instance.
58 #[must_use]
59 pub const fn ptr(&self) -> *const u8 {
60 self.ptr.as_ptr().cast_const()
61 }
62
63 /// Get a mutable pointer to the aligned memory region managed by this instance.
64 #[must_use]
65 pub const fn ptr_mut(&mut self) -> *mut u8 {
66 self.ptr.as_ptr()
67 }
68
69 /// Get the underlying memory region as immutable slice.
70 #[must_use]
71 pub const fn as_slice(&self) -> &[u8] {
72 // SAFETY: The pointer is valid for the requested slice length.
73 unsafe { slice::from_raw_parts(self.ptr(), self.size()) }
74 }
75
76 /// Get the underlying memory region as mutable slice.
77 #[must_use]
78 pub const fn as_slice_mut(&mut self) -> &mut [u8] {
79 // SAFETY: The pointer is valid for the requested slice length.
80 unsafe { slice::from_raw_parts_mut(self.ptr_mut(), self.size()) }
81 }
82
83 /// Get the size of the aligned memory region managed by this instance.
84 #[must_use]
85 pub const fn size(&self) -> usize {
86 self.layout.size()
87 }
88
89 /// Returns an iterator over the aligned buffer contents.
90 pub fn iter(&self) -> impl Iterator<Item = &u8> {
91 self.as_slice().iter()
92 }
93
94 /// Returns a mutable iterator over the aligned buffer contents.
95 pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut u8> {
96 self.as_slice_mut().iter_mut()
97 }
98
99 /// Fill the aligned memory region with data from the given buffer.
100 ///
101 /// The length of `src` must be the same as `self`.
102 pub fn copy_from_slice(&mut self, src: &[u8]) {
103 assert_eq!(self.size(), src.len());
104 // SAFETY: The memory is valid.
105 unsafe {
106 self.ptr_mut().copy_from(src.as_ptr(), src.len());
107 }
108 }
109
110 /// Fill the aligned memory region with data from the given iterator.
111 /// If the given iterator is shorter than the buffer, the remaining area will be left untouched.
112 pub fn copy_from_iter(&mut self, src: impl Iterator<Item = u8>) {
113 self.iter_mut()
114 .zip(src)
115 .for_each(|(dst, src_byte)| *dst = src_byte);
116 }
117
118 /// Check the buffer's alignment against the `required_alignment`.
119 pub fn check_alignment(&self, required_alignment: usize) -> Result<(), AlignmentError> {
120 //TODO: use bfr.addr() when it's available
121 if !(self.ptr() as usize).is_multiple_of(required_alignment) {
122 return Err(AlignmentError); //TODO: use >is_aligned_to< when it's available
123 }
124 Ok(())
125 }
126}
127
128impl Drop for AlignedBuffer {
129 fn drop(&mut self) {
130 // Zero-size buffers were never allocated, see `from_layout`.
131 if self.layout.size() == 0 {
132 return;
133 }
134 // SAFETY: The memory was allocated with this layout.
135 unsafe {
136 dealloc(self.ptr_mut(), self.layout);
137 }
138 }
139}
140
141/// The `AlignmentError` is returned if a user-provided buffer doesn't fulfill alignment requirements.
142#[derive(Clone, PartialEq, Eq, Debug)]
143pub struct AlignmentError;
144impl Error for AlignmentError {}
145impl fmt::Display for AlignmentError {
146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147 f.write_str("Buffer alignment does not fulfill requirements.")
148 }
149}
150
151#[cfg(test)]
152mod tests {
153 use super::AlignedBuffer;
154
155 #[test]
156 fn test_invalid_arguments() {
157 // invalid alignments, valid len
158 for request_alignment in [0, 3, 5, 7, 9] {
159 for request_len in [1, 32, 64, 128, 1024] {
160 assert!(AlignedBuffer::from_size_align(request_len, request_alignment).is_err());
161 }
162 }
163 }
164
165 #[test]
166 fn test_allocation_alignment() {
167 for request_alignment in [1, 2, 4, 8, 16, 32, 64, 128] {
168 for request_len in [1_usize, 32, 64, 128, 1024] {
169 let buffer =
170 AlignedBuffer::from_size_align(request_len, request_alignment).unwrap();
171 assert_eq!(buffer.ptr() as usize % request_alignment, 0);
172 assert_eq!(buffer.size(), request_len);
173 }
174 }
175 }
176
177 /// A fresh buffer must be readable through the safe accessors, so its
178 /// memory must be initialized (Miri catches a read of uninitialized
179 /// memory here otherwise).
180 #[test]
181 fn test_fresh_buffer_is_zeroed() {
182 let bfr = AlignedBuffer::from_size_align(8, 8).unwrap();
183 assert_eq!(bfr.as_slice(), [0; 8]);
184 }
185
186 /// A zero-size buffer must not hit the allocator (zero-size layouts are
187 /// not allowed by `GlobalAlloc`), but must still behave like an empty,
188 /// aligned buffer.
189 #[test]
190 fn test_zero_size() {
191 for request_alignment in [1, 8, 64] {
192 let mut bfr = AlignedBuffer::from_size_align(0, request_alignment).unwrap();
193 assert_eq!(bfr.size(), 0);
194 assert!(bfr.as_slice().is_empty());
195 assert!(bfr.as_slice_mut().is_empty());
196 bfr.check_alignment(request_alignment).unwrap();
197 bfr.copy_from_slice(&[]);
198 }
199 }
200
201 #[test]
202 fn test_copy_from_iter() {
203 let src8: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
204 {
205 // src as large as dst
206 let mut bfr = AlignedBuffer::from_size_align(8, 8).unwrap();
207 bfr.copy_from_iter(src8.iter().cloned());
208 assert_eq!(bfr.as_slice(), src8);
209 }
210 {
211 // src larger than dst
212 let mut bfr = AlignedBuffer::from_size_align(7, 8).unwrap();
213 bfr.copy_from_iter(src8.iter().cloned());
214 assert_eq!(bfr.as_slice(), [1, 2, 3, 4, 5, 6, 7]);
215 }
216 {
217 // src smaller than dst
218 let mut bfr = AlignedBuffer::from_size_align(9, 8).unwrap();
219 bfr.iter_mut().for_each(|dst| *dst = 0); // fill with 0s
220 bfr.copy_from_iter(src8.iter().cloned());
221 assert_eq!(bfr.as_slice(), [1, 2, 3, 4, 5, 6, 7, 8, 0]);
222 }
223 }
224}