|
24 | 24 | #![deny(missing_debug_implementations)]
|
25 | 25 | #![deny(rustdoc::all)]
|
26 | 26 | // --- END STYLE CHECKS ---
|
| 27 | + |
| 28 | +#[cfg_attr(test, macro_use)] |
| 29 | +#[cfg(test)] |
| 30 | +extern crate std; |
| 31 | + |
| 32 | +// Doesn't work: #[cfg(test)] |
| 33 | +#[allow(unused)] |
| 34 | +pub mod test_utils; |
| 35 | + |
| 36 | +use core::fmt::Debug; |
| 37 | +use core::marker::PhantomData; |
| 38 | +use core::mem; |
| 39 | +use core::ops::Deref; |
| 40 | + |
| 41 | +/// The alignment of all Multiboot2 data structures. |
| 42 | +pub const ALIGNMENT: usize = 8; |
| 43 | + |
| 44 | +/// A sized header type for [`DynSizedStructure`]. Note that `header` refers to |
| 45 | +/// the header pattern. Thus, depending on the use case, this is not just the |
| 46 | +/// tag header. Instead, it refers to all bytes that are fixed and not part of |
| 47 | +/// any optional terminating dynamic `[u8]` slice. |
| 48 | +/// |
| 49 | +/// It's alignment **must** be the alignment of the tags. Typically, |
| 50 | +/// [`ALIGNMENT`]. |
| 51 | +pub trait Header: Sized + PartialEq + Eq + Debug { |
| 52 | + /// Returns the length of the payload, i.e., the bytes that are additional |
| 53 | + /// to the header. The value is measured in bytes. |
| 54 | + fn payload_len(&self) -> usize; |
| 55 | +} |
| 56 | + |
| 57 | +/// Errors that occur when constructing [`DynSizedStructure`]. |
| 58 | +#[derive(Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)] |
| 59 | +pub enum DynSizedStructureError { |
| 60 | + /// The size-property has an illegal value that can't be fulfilled with the |
| 61 | + /// given bytes. |
| 62 | + SizeTooBig, |
| 63 | +} |
| 64 | + |
| 65 | +/// A dynamically sized type with a common sized header and a dynamic amount of |
| 66 | +/// bytes that owns all its memory. It is fulfilling all memory requirements and |
| 67 | +/// guarantees of Multiboot2 structures and Rustc/Miri. |
| 68 | +/// |
| 69 | +/// # ABI |
| 70 | +/// This has a C ABI. The fixed [`Header`] portion is always there. Further, |
| 71 | +/// there is a variable amount of payload bytes. Thus, this type can only |
| 72 | +/// exist on the heap or references to it can be made by cast via fat pointers. |
| 73 | +#[derive(Debug, PartialEq, Eq, ptr_meta::Pointee)] |
| 74 | +#[repr(C, align(8))] |
| 75 | +pub struct DynSizedStructure<H: Header> { |
| 76 | + header: H, |
| 77 | + payload: [u8], |
| 78 | + // Plus optional padding bytes to next alignment boundary, which are not |
| 79 | + // reflected here. However, Rustc allocates them anyway and expects them |
| 80 | + // to be there. |
| 81 | + // See <https://doc.rust-lang.org/reference/type-layout.html>. |
| 82 | +} |
| 83 | + |
| 84 | +impl<H: Header> DynSizedStructure<H> { |
| 85 | + /// Returns a new reference from the given [`BytesRef`]. |
| 86 | + pub fn ref_from(bytes: BytesRef<H>) -> Result<&Self, DynSizedStructureError> { |
| 87 | + let header = bytes.as_ptr().cast::<H>(); |
| 88 | + let header = unsafe { &*header }; |
| 89 | + |
| 90 | + if header.payload_len() > bytes.len() { |
| 91 | + return Err(DynSizedStructureError::SizeTooBig); |
| 92 | + } |
| 93 | + |
| 94 | + // Create fat pointer for DST. |
| 95 | + let structure: *const Self = |
| 96 | + ptr_meta::from_raw_parts(bytes.as_ptr().cast(), header.payload_len()); |
| 97 | + let structure = unsafe { &*structure }; |
| 98 | + Ok(structure) |
| 99 | + } |
| 100 | + |
| 101 | + /// Returns the underlying [`Header`]. |
| 102 | + pub const fn header(&self) -> &H { |
| 103 | + &self.header |
| 104 | + } |
| 105 | + |
| 106 | + /// Returns the underlying payload. |
| 107 | + pub const fn payload(&self) -> &[u8] { |
| 108 | + &self.payload |
| 109 | + } |
| 110 | +} |
| 111 | + |
| 112 | +/// Wraps a byte slice representing a Multiboot2 structure including an optional |
| 113 | +/// terminating padding, if necessary. Guarantees that the memory requirements |
| 114 | +/// for both Multiboot2 and Rustc/Miri are fulfilled. |
| 115 | +/// |
| 116 | +/// Useful to construct [`DynSizedStructure`]. The main reason for this |
| 117 | +/// dedicated type is to create fine-grained unit-tests for Miri. |
| 118 | +/// |
| 119 | +/// # Memory Requirements |
| 120 | +/// - At least as big as a `size_of::<HeaderT>()` |
| 121 | +/// - at least [`ALIGNMENT`]-aligned |
| 122 | +/// - Length is multiple of [`ALIGNMENT`]. In other words, there are enough |
| 123 | +/// padding bytes so that the pointer coming right after the last byte |
| 124 | +/// is [`ALIGNMENT`]-aligned. |
| 125 | +/// |
| 126 | +/// See <https://doc.rust-lang.org/reference/type-layout.html> for information. |
| 127 | +#[derive(Clone, Debug, PartialEq, Eq)] |
| 128 | +#[repr(transparent)] |
| 129 | +pub struct BytesRef<'a, H: Header> { |
| 130 | + bytes: &'a [u8], |
| 131 | + // Ensure that consumers can rely on the size properties for HeaderT that |
| 132 | + // already have been verified when this type was constructed. |
| 133 | + _h: PhantomData<H>, |
| 134 | +} |
| 135 | + |
| 136 | +impl<'a, H: Header> TryFrom<&'a [u8]> for BytesRef<'a, H> { |
| 137 | + type Error = BytesRefError; |
| 138 | + |
| 139 | + fn try_from(bytes: &'a [u8]) -> Result<Self, Self::Error> { |
| 140 | + if bytes.len() < mem::size_of::<H>() { |
| 141 | + return Err(BytesRefError::MinLengthNotSatisfied); |
| 142 | + } |
| 143 | + // Doesn't work as expected: if align_of_val(&value[0]) < ALIGNMENT { |
| 144 | + if bytes.as_ptr().align_offset(ALIGNMENT) != 0 { |
| 145 | + return Err(BytesRefError::WrongAlignment); |
| 146 | + } |
| 147 | + let padding_bytes = bytes.len() % ALIGNMENT; |
| 148 | + if padding_bytes != 0 { |
| 149 | + return Err(BytesRefError::MissingPadding); |
| 150 | + } |
| 151 | + Ok(Self { |
| 152 | + bytes, |
| 153 | + _h: PhantomData, |
| 154 | + }) |
| 155 | + } |
| 156 | +} |
| 157 | + |
| 158 | +impl<'a, H: Header> Deref for BytesRef<'a, H> { |
| 159 | + type Target = &'a [u8]; |
| 160 | + |
| 161 | + fn deref(&self) -> &Self::Target { |
| 162 | + &self.bytes |
| 163 | + } |
| 164 | +} |
| 165 | + |
| 166 | +/// Errors that occur when constructing [`BytesRef`]. |
| 167 | +#[derive(Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)] |
| 168 | +pub enum BytesRefError { |
| 169 | + /// The memory must be at least [`ALIGNMENT`]-aligned. |
| 170 | + WrongAlignment, |
| 171 | + /// The memory must cover at least the length of the sized structure header |
| 172 | + /// type. |
| 173 | + MinLengthNotSatisfied, |
| 174 | + /// The buffer misses the terminating padding to the next alignment |
| 175 | + /// boundary. The padding is relevant to satisfy Rustc/Miri, but also the |
| 176 | + /// spec mandates that the padding is added. |
| 177 | + MissingPadding, |
| 178 | +} |
| 179 | + |
| 180 | +#[cfg(test)] |
| 181 | +mod tests { |
| 182 | + use super::*; |
| 183 | + use crate::test_utils::{AlignedBytes, DummyTestHeader}; |
| 184 | + |
| 185 | + #[test] |
| 186 | + fn test_bytes_ref() { |
| 187 | + let empty: &[u8] = &[]; |
| 188 | + assert_eq!( |
| 189 | + BytesRef::<'_, DummyTestHeader>::try_from(empty), |
| 190 | + Err(BytesRefError::MinLengthNotSatisfied) |
| 191 | + ); |
| 192 | + |
| 193 | + let slice = &[0_u8, 1, 2, 3, 4, 5, 6]; |
| 194 | + assert_eq!( |
| 195 | + BytesRef::<'_, DummyTestHeader>::try_from(&slice[..]), |
| 196 | + Err(BytesRefError::MinLengthNotSatisfied) |
| 197 | + ); |
| 198 | + |
| 199 | + let slice = AlignedBytes([0_u8, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0]); |
| 200 | + // Guaranteed wrong alignment |
| 201 | + let unaligned_slice = &slice[3..]; |
| 202 | + assert_eq!( |
| 203 | + BytesRef::<'_, DummyTestHeader>::try_from(unaligned_slice), |
| 204 | + Err(BytesRefError::WrongAlignment) |
| 205 | + ); |
| 206 | + |
| 207 | + let slice = AlignedBytes([0_u8, 1, 2, 3, 4, 5, 6, 7]); |
| 208 | + let slice = &slice[..]; |
| 209 | + assert_eq!( |
| 210 | + BytesRef::try_from(slice), |
| 211 | + Ok(BytesRef { |
| 212 | + bytes: slice, |
| 213 | + _h: PhantomData::<DummyTestHeader> |
| 214 | + }) |
| 215 | + ); |
| 216 | + } |
| 217 | +} |
0 commit comments