Skip to main content

c_support/memory/
allocated.rs

1use core::{alloc::Layout, ptr::NonNull};
2
3use memory::CapabilityFlags;
4
5use crate::CompactLayout;
6
7pub struct Allocated {
8    pointer: NonNull<u8>,
9    metadata: CompactLayout,
10}
11
12impl Allocated {
13    const HEADER_SIZE: usize = size_of::<CompactLayout>();
14
15    const fn user_offset(alignment: usize) -> usize {
16        // The header size and the validated alignment are both powers of two.
17        if alignment > Self::HEADER_SIZE {
18            alignment
19        } else {
20            Self::HEADER_SIZE
21        }
22    }
23
24    pub fn get_layout_for_allocation(size: usize, alignment: usize) -> Option<Layout> {
25        if !alignment.is_power_of_two() || alignment > CompactLayout::MAXIMUM_ALIGNMENT {
26            return None;
27        }
28        let total_size = Self::user_offset(alignment).checked_add(size)?;
29        if total_size > CompactLayout::MAXIMUM_SIZE {
30            return None;
31        }
32        Layout::from_size_align(total_size, alignment).ok()
33    }
34
35    /// # Safety
36    ///
37    /// A non-null `pointer` must refer to a writable allocation with the given
38    /// `layout`, including room for the allocation metadata.
39    pub unsafe fn from_layout(
40        pointer: *mut u8,
41        layout: &Layout,
42        capabilities: CapabilityFlags,
43    ) -> Option<Self> {
44        let pointer = NonNull::new(pointer)?;
45        let metadata = CompactLayout::from_layout(layout, capabilities)?;
46        let allocated = Self { pointer, metadata };
47
48        let header_pointer = unsafe { allocated.get_user_pointer().sub(Self::HEADER_SIZE) };
49        unsafe {
50            header_pointer
51                .cast::<[u8; Self::HEADER_SIZE]>()
52                .write(metadata.to_le_bytes())
53        };
54        Some(allocated)
55    }
56
57    /// # Safety
58    ///
59    /// A non-null `user_pointer` must have been returned by `get_user_pointer` for
60    /// a live allocation with intact metadata.
61    pub unsafe fn from_user_pointer(user_pointer: *mut u8) -> Option<Self> {
62        let user_pointer = NonNull::new(user_pointer)?;
63        // SAFETY: The caller guarantees a live allocation whose header precedes it.
64        let header_pointer = unsafe { user_pointer.sub(Self::HEADER_SIZE) };
65        let bytes = unsafe { header_pointer.cast::<[u8; Self::HEADER_SIZE]>().read() };
66        let metadata = CompactLayout::from_le_bytes(bytes);
67        // SAFETY: The base precedes the user pointer within the same allocation.
68        let pointer = unsafe { user_pointer.sub(Self::user_offset(metadata.get_alignment())) };
69        Some(Self { pointer, metadata })
70    }
71
72    pub fn get_layout(&self) -> Option<Layout> {
73        self.metadata.into_layout()
74    }
75
76    pub fn get_capabilities(&self) -> CapabilityFlags {
77        self.metadata.get_capabilities()
78    }
79
80    pub fn get_base_pointer(&self) -> *mut u8 {
81        self.pointer.as_ptr()
82    }
83
84    pub fn get_user_pointer(&self) -> *mut u8 {
85        unsafe {
86            self.pointer
87                .as_ptr()
88                .add(Self::user_offset(self.metadata.get_alignment()))
89        }
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96
97    #[test]
98    fn test_allocation_layout() {
99        for alignment in [1, 2, 4, 8, 16, 32, 64, 128, 32768] {
100            for size in [0, 100] {
101                let layout = Allocated::get_layout_for_allocation(size, alignment).unwrap();
102                let offset = layout.size() - size;
103                assert!(offset >= Allocated::HEADER_SIZE);
104                assert_eq!(offset % alignment, 0);
105                assert_eq!(layout.align(), alignment);
106            }
107        }
108    }
109
110    #[test]
111    fn test_invalid_allocation_layout() {
112        for size in [
113            usize::MAX - 7,
114            isize::MAX as usize,
115            CompactLayout::MAXIMUM_SIZE,
116        ] {
117            assert!(Allocated::get_layout_for_allocation(size, 8).is_none());
118        }
119        for alignment in [0, 3, CompactLayout::MAXIMUM_ALIGNMENT * 2] {
120            assert!(Allocated::get_layout_for_allocation(128, alignment).is_none());
121        }
122    }
123
124    #[test]
125    fn test_metadata_round_trip() {
126        use alloc::alloc::{alloc, dealloc};
127
128        for alignment in [1, 2, 4, 8, 16, 32, 64, 128, 32768] {
129            let layout = Allocated::get_layout_for_allocation(32, alignment).unwrap();
130            let caps = CapabilityFlags::DirectMemoryAccess | CapabilityFlags::AlwaysAccessible;
131            unsafe {
132                let base = alloc(layout);
133                let allocated = Allocated::from_layout(base, &layout, caps).unwrap();
134                let user = allocated.get_user_pointer();
135                assert_eq!(user.addr() % alignment, 0);
136                assert_eq!(user.offset_from(base) as usize, layout.size() - 32);
137                let recovered = Allocated::from_user_pointer(user).unwrap();
138                assert_eq!(recovered.get_base_pointer(), base);
139                assert_eq!(recovered.get_user_pointer(), user);
140                assert_eq!(recovered.get_layout(), Some(layout));
141                assert_eq!(recovered.get_capabilities(), caps);
142                dealloc(base, layout);
143            }
144        }
145    }
146}