Skip to main content

memory/
manager.rs

1use core::{
2    alloc::GlobalAlloc,
3    ptr::{NonNull, null_mut},
4};
5
6use crate::{CapabilityFlags, Layout, ManagerTrait};
7
8unsafe extern "Rust" {
9    unsafe static __XILA_MEMORY_MANAGER: Manager<'static>;
10}
11
12/// A wrapper type that adapts any type implementing `Allocator_trait` to the standard
13/// Rust `GlobalAlloc` trait.
14///
15/// This enables custom allocators that implement the Xila-specific `Allocator_trait`
16/// to be used as the global memory allocator for Rust's allocation system.
17pub struct Manager<'a>(&'a dyn ManagerTrait);
18
19impl<'a> Manager<'a> {
20    /// Creates a new instance of `Allocator_type` wrapping the provided allocator.
21    ///
22    /// # Parameters
23    /// * `Allocator` - The allocator to wrap
24    ///
25    /// # Returns
26    /// A new instance of `Allocator_type` containing the provided allocator.
27    pub const fn new(allocator: &'a dyn ManagerTrait) -> Self {
28        Self(allocator)
29    }
30
31    /// Allocates memory with the specified capabilities and layout.
32    ///
33    /// # Parameters
34    /// * `Capabilities` - Specific requirements for the allocation
35    /// * `Layout` - Size and alignment requirements for the allocation
36    ///
37    /// # Returns
38    /// A pointer to the allocated memory, or a null pointer if allocation failed.
39    ///
40    /// # Safety
41    /// This function is unsafe because the caller must ensure that:
42    pub unsafe fn allocate(&self, capabilities: CapabilityFlags, layout: Layout) -> *mut u8 {
43        if layout.size() == 0 {
44            return null_mut();
45        }
46
47        match unsafe { self.0.allocate(capabilities, layout) } {
48            Some(ptr) => ptr.as_ptr(),
49            None => {
50                null_mut()
51                //        panic!(
52                //            "xila_memory_allocate for capabilities {:?} and layout {:?} failed",
53                //            capabilities, layout
54                //        );
55            }
56        }
57    }
58
59    /// Deallocates memory previously allocated by this allocator.
60    ///
61    /// # Parameters
62    /// * `Pointer` - Pointer to the memory to deallocate
63    /// * `Layout` - The layout that was used to allocate the memory
64    ///
65    /// # Safety
66    /// This function is unsafe because the caller must ensure that:
67    /// - The pointer was allocated by this allocator
68    /// - The layout matches the layout used for allocation
69    pub unsafe fn deallocate(&self, pointer: *mut u8, layout: Layout) {
70        if let Some(pointer) = NonNull::new(pointer) {
71            unsafe { self.0.deallocate(pointer, layout) }
72        } else {
73            // No panic since its allowed in C
74            // panic!("Attempted to deallocate a null pointer");
75        }
76    }
77
78    /// Resizes memory with its original alignment and capabilities.
79    ///
80    /// A null pointer requests a fresh allocation. On success, the contents of the old
81    /// block are preserved up to the smaller of the old and new sizes. On failure, the
82    /// original block remains valid.
83    ///
84    /// # Parameters
85    /// * `capabilities` - The capability requirements of the allocation
86    /// * `Pointer` - Pointer to the memory to reallocate. If null, acts as a new allocation
87    /// * `Old_layout` - The layout that was used for the original allocation
88    /// * `New_size` - The new size for the memory
89    ///
90    /// # Returns
91    /// A pointer to the reallocated memory with the new layout, or a null pointer if reallocation failed.
92    ///
93    /// # Safety
94    /// This function is unsafe because the caller must ensure that:
95    /// - If `Pointer` is not null, it was allocated by this allocator
96    /// - The layout and capabilities match those used for the original allocation
97    /// - The old memory is not used after successful reallocation
98    /// - The returned memory is properly initialized before use
99    pub unsafe fn reallocate(
100        &self,
101        capabilities: CapabilityFlags,
102        pointer: *mut u8,
103        layout: Layout,
104        new_size: usize,
105    ) -> *mut u8 {
106        let Ok(new_layout) = Layout::from_size_align(new_size, layout.align()) else {
107            return null_mut();
108        };
109
110        let pointer = match NonNull::new(pointer) {
111            Some(pointer) => unsafe {
112                self.0.reallocate(capabilities, pointer, layout, new_layout)
113            },
114            None => return unsafe { self.allocate(capabilities, new_layout) },
115        };
116
117        pointer.map_or(null_mut(), |ptr| ptr.as_ptr())
118    }
119
120    pub fn get_page_size(&self) -> usize {
121        self.0.get_page_size()
122    }
123
124    pub fn flush_data_cache(&self) {
125        self.0.flush_data_cache()
126    }
127
128    /// Flushes the instruction cache for the specified memory region.
129    ///
130    /// # Parameters
131    /// * `Address` - Starting address of the memory region
132    /// * `Size` - Size of the memory region in bytes
133    /// # Safety
134    /// This function is unsafe because the caller must ensure that:
135    /// - The address is valid and points to a memory region of at least `size` bytes
136    /// - The memory region is not being modified while the instruction cache is being flushed
137    pub unsafe fn flush_instruction_cache(&self, address: *const u8, size: usize) {
138        let Some(address) = NonNull::new(address as *mut u8) else {
139            return;
140        };
141
142        self.0.flush_instruction_cache(address, size)
143    }
144
145    /// Returns the amount of memory currently used.
146    ///
147    /// # Returns
148    /// The number of bytes currently allocated.
149    pub fn get_used(&self) -> usize {
150        self.0.get_used()
151    }
152
153    /// Returns the amount of memory currently available.
154    ///
155    /// # Returns
156    /// The number of bytes available for allocation.
157    ///
158    pub fn get_free(&self) -> usize {
159        self.0.get_free()
160    }
161
162    /// Returns the total size of the memory managed by this allocator.
163    ///
164    /// # Returns
165    /// The total number of bytes managed by the allocator.
166    pub fn get_total_size(&self) -> usize {
167        self.0.get_total_size()
168    }
169}
170
171/// Implementation of the standard library's `GlobalAlloc` trait for any wrapped
172/// type that implements `Allocator_trait`.
173///
174/// This implementation delegates the standard allocation operations to the wrapped
175/// allocator's methods, converting between Rust's and Xila's allocation types.
176///
177/// # Safety
178/// The implementation upholds the safety guarantees required by `GlobalAlloc`:
179/// - Memory is properly aligned according to the layout
180/// - Deallocation uses the same layout that was used for allocation
181unsafe impl<'a> GlobalAlloc for Manager<'a> {
182    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
183        unsafe { self.allocate(CapabilityFlags::empty(), layout) }
184    }
185
186    unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
187        unsafe { self.deallocate(pointer, layout) }
188    }
189
190    unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
191        unsafe { self.reallocate(CapabilityFlags::empty(), pointer, layout, new_size) }
192    }
193}
194
195pub fn global_manager() -> &'static Manager<'static> {
196    unsafe { &__XILA_MEMORY_MANAGER }
197}