Skip to main content

multiboot2_common/
tag.rs

1//! Module for the traits [`MaybeDynSized`] and [`Tag`].
2
3use crate::{DynSizedStructure, Header};
4use core::slice;
5use ptr_meta::Pointee;
6
7/// A trait to abstract sized and unsized structures (DSTs). It enables
8/// casting a [`DynSizedStructure`] to sized or unsized structures using
9/// [`DynSizedStructure::cast`].
10///
11/// Structs that are a DST must provide a **correct** [`MaybeDynSized::dst_len`]
12/// implementation. The needed metadata type is either `()` for sized types or
13/// `usize` for dynamically sized types. For sized types, there is a default
14/// implementation. Only dynamically sized types need to implement
15/// [`MaybeDynSized::dst_len`].
16///
17/// # Safety
18///
19/// Implementors must be `#[repr(C)]`, start with `Self::Header`, have an
20/// alignment of at most [`ALIGNMENT`], and allow every bit pattern.
21///
22/// [`MaybeDynSized::BASE_SIZE`], [`MaybeDynSized::dst_len`], and
23/// [`Header::total_size`] must correctly describe the initialized,
24/// contiguous memory backing the value. Incorrect sizes or implicit padding
25/// within the reported range can cause out-of-bounds references. Trailing
26/// padding beyond that range is fine.
27///
28/// [`ID`]: Tag::ID
29/// [`ALIGNMENT`]: crate::ALIGNMENT
30/// [`DynSizedStructure`]: crate::DynSizedStructure
31pub unsafe trait MaybeDynSized: Pointee {
32    /// The associated [`Header`] of this tag.
33    type Header: Header;
34
35    /// The true base size of the struct without any implicit or additional
36    /// padding. Note that `size_of::<T>()` isn't sufficient, as for example
37    /// the type could have three `u32` fields, which would add an implicit
38    /// `u32` padding. However, this constant **must always** fulfill
39    /// `BASE_SIZE >= size_of::<Self::Header>()`.
40    ///
41    /// The main purpose of this constant is to create awareness when you
42    /// implement [`Self::dst_len`], where you should use this. If this value
43    /// is correct, we prevent situations where we read uninitialized bytes,
44    /// especially when creating tags in builders.
45    const BASE_SIZE: usize;
46
47    /// Returns the amount of items in the dynamically sized portion of the
48    /// DST. Note that this is not the amount of bytes. So if the dynamically
49    /// sized portion is 16 bytes in size and each element is 4 bytes big, then
50    /// this function must return 4.
51    ///
52    /// For sized tags, this just returns `()`. For DSTs, this returns an
53    /// `usize`.
54    fn dst_len(header: &Self::Header) -> Self::Metadata
55    where
56        // Either `()` or `usize`, never something else
57        Self::Metadata: Default,
58    {
59        let _ = header;
60        Default::default()
61    }
62
63    /// Returns the corresponding [`Header`].
64    fn header(&self) -> &Self::Header {
65        let ptr = &raw const *self;
66        // SAFETY: `self` is a valid reference and `Self::Header` is the
67        // prefix of this `repr(C)` structure at the same address.
68        unsafe { &*ptr.cast::<Self::Header>() }
69    }
70
71    /// Returns the payload, i.e., all memory that is not occupied by the
72    /// [`Header`] of the type. Implicit trailing padding beyond the
73    /// structure size reported in the header is not part of the payload.
74    ///
75    /// # Panics
76    /// Panics if the size reported in the header is smaller than the size of
77    /// the [`Header`] itself, which can only happen for oddly formed values.
78    fn payload(&self) -> &[u8] {
79        let from = size_of::<Self::Header>();
80        &self.as_bytes()[from..]
81    }
82
83    /// Returns the bytes of the structure, i.e., the header and the payload,
84    /// up to the structure size reported by [`Self::header`].
85    ///
86    /// Implicit trailing padding that the Rust memory layout might add beyond
87    /// that size is excluded, as it may be uninitialized for stack-constructed
88    /// values and must never be read.
89    fn as_bytes(&self) -> &[u8] {
90        let ptr = &raw const *self;
91        // Clamp to the allocation: a corrupt header size must never cause an
92        // out-of-bounds slice.
93        let size = self.header().total_size().min(size_of_val(self));
94        // SAFETY: `ptr` points to `self`'s allocation, `size` is in bounds,
95        // and the first `total_size()` bytes of a value are initialized.
96        unsafe { slice::from_raw_parts(ptr.cast::<u8>(), size) }
97    }
98
99    /// Returns a pointer to this structure.
100    fn as_ptr(&self) -> *const Self::Header {
101        self.as_bytes().as_ptr().cast()
102    }
103}
104
105/// Extension of [`MaybeDynSized`] for Tags.
106pub trait Tag: MaybeDynSized {
107    /// The ID type that identifies the tag.
108    type IDType: PartialEq + Eq;
109
110    /// The ID of this tag. This should be unique across all implementors.
111    ///
112    /// Although the ID is not yet used in `multiboot2-common`, it ensures
113    /// a consistent API in consumer crates.
114    const ID: Self::IDType;
115}
116
117// This implementation is not needed for parsing but for creation, when
118// downstream types just wrap this type.
119// SAFETY: `DynSizedStructure` is repr(C) with the header as first field,
120// any bit pattern is valid, and `BASE_SIZE`/`dst_len` match the ABI.
121unsafe impl<H: Header> MaybeDynSized for DynSizedStructure<H> {
122    type Header = H;
123
124    const BASE_SIZE: usize = size_of::<H>();
125
126    fn dst_len(header: &Self::Header) -> Self::Metadata {
127        header.payload_len()
128    }
129}