Skip to main content

testing_support/
memory_manager.rs

1//! A memory manager backed by the standard system allocator.
2
3use core::{cell::Cell, ptr::NonNull};
4use memory::{CapabilityFlags, Layout, ManagerTrait};
5use std::{
6    alloc::{GlobalAlloc, System},
7    sync::atomic::{AtomicUsize, Ordering},
8};
9
10/// Allocation counters recorded for a single thread by [`MemoryManager`].
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
12pub struct ThreadAllocations {
13    allocations: usize,
14    allocated_bytes: usize,
15    deallocated_bytes: usize,
16}
17
18impl ThreadAllocations {
19    /// Number of allocations performed on the thread.
20    pub const fn allocations(self) -> usize {
21        self.allocations
22    }
23
24    /// Total bytes allocated on the thread (not reduced by deallocations).
25    pub const fn allocated_bytes(self) -> usize {
26        self.allocated_bytes
27    }
28
29    /// Total bytes deallocated on the thread.
30    pub const fn deallocated_bytes(self) -> usize {
31        self.deallocated_bytes
32    }
33
34    /// Net bytes allocated minus deallocated on the thread.
35    ///
36    /// Can be negative if the thread freed memory allocated on another thread.
37    pub const fn net_bytes(self) -> isize {
38        self.allocated_bytes.wrapping_sub(self.deallocated_bytes) as isize
39    }
40
41    /// Counters accumulated between `earlier` and `self`.
42    pub const fn since(self, earlier: Self) -> Self {
43        Self {
44            allocations: self.allocations.wrapping_sub(earlier.allocations),
45            allocated_bytes: self.allocated_bytes.wrapping_sub(earlier.allocated_bytes),
46            deallocated_bytes: self
47                .deallocated_bytes
48                .wrapping_sub(earlier.deallocated_bytes),
49        }
50    }
51}
52
53std::thread_local! {
54    static THREAD_ALLOCATIONS: Cell<ThreadAllocations> = const {
55        Cell::new(ThreadAllocations {
56            allocations: 0,
57            allocated_bytes: 0,
58            deallocated_bytes: 0,
59        })
60    };
61}
62
63/// Xila memory manager for tests: every capability is served by [`System`].
64pub struct MemoryManager {
65    used: AtomicUsize,
66}
67
68impl Default for MemoryManager {
69    fn default() -> Self {
70        Self::new()
71    }
72}
73
74impl MemoryManager {
75    pub const fn new() -> Self {
76        Self {
77            used: AtomicUsize::new(0),
78        }
79    }
80
81    /// Snapshot the allocation counters for the calling thread.
82    pub fn thread_allocations() -> ThreadAllocations {
83        THREAD_ALLOCATIONS.with(Cell::get)
84    }
85}
86
87impl ManagerTrait for MemoryManager {
88    unsafe fn allocate(&self, _: CapabilityFlags, layout: Layout) -> Option<NonNull<u8>> {
89        let pointer = NonNull::new(unsafe { System.alloc(layout) })?;
90        self.used.fetch_add(layout.size(), Ordering::Relaxed);
91        let _ = THREAD_ALLOCATIONS.try_with(|counters| {
92            let mut current = counters.get();
93            current.allocations = current.allocations.wrapping_add(1);
94            current.allocated_bytes = current.allocated_bytes.wrapping_add(layout.size());
95            counters.set(current);
96        });
97        Some(pointer)
98    }
99
100    unsafe fn deallocate(&self, pointer: NonNull<u8>, layout: Layout) {
101        unsafe { System.dealloc(pointer.as_ptr(), layout) };
102        self.used.fetch_sub(layout.size(), Ordering::Relaxed);
103        let _ = THREAD_ALLOCATIONS.try_with(|counters| {
104            let mut current = counters.get();
105            current.deallocated_bytes = current.deallocated_bytes.wrapping_add(layout.size());
106            counters.set(current);
107        });
108    }
109
110    fn get_used(&self) -> usize {
111        self.used.load(Ordering::Relaxed)
112    }
113
114    fn get_free(&self) -> usize {
115        (isize::MAX as usize).saturating_sub(self.get_used())
116    }
117}
118
119/// Install [`MemoryManager`] as the global allocator and Xila memory manager.
120#[macro_export]
121macro_rules! instantiate_global_allocator {
122    () => {
123        static __XILA_TESTING_MEMORY_MANAGER: $crate::MemoryManager = $crate::MemoryManager::new();
124        $crate::memory_crate::instantiate_global_allocator!(&__XILA_TESTING_MEMORY_MANAGER);
125    };
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn thread_counters_track_current_thread_and_ignore_other_threads() {
134        let manager = MemoryManager::new();
135        let layout = Layout::from_size_align(128, 8).unwrap();
136
137        let before = MemoryManager::thread_allocations();
138        let pointer = unsafe { manager.allocate(CapabilityFlags::empty(), layout) }.unwrap();
139        let during = MemoryManager::thread_allocations().since(before);
140        assert_eq!(during.allocations(), 1);
141        assert_eq!(during.allocated_bytes(), 128);
142        assert_eq!(during.deallocated_bytes(), 0);
143        assert_eq!(during.net_bytes(), 128);
144
145        let before_other_thread = MemoryManager::thread_allocations();
146        std::thread::scope(|scope| {
147            scope.spawn(|| {
148                let other_before = MemoryManager::thread_allocations();
149                let other = unsafe { manager.allocate(CapabilityFlags::empty(), layout) }.unwrap();
150                unsafe { manager.deallocate(other, layout) };
151                let other_delta = MemoryManager::thread_allocations().since(other_before);
152                assert_eq!(other_delta.allocations(), 1);
153                assert_eq!(other_delta.allocated_bytes(), 128);
154                assert_eq!(other_delta.deallocated_bytes(), 128);
155                assert_eq!(other_delta.net_bytes(), 0);
156            });
157        });
158        assert_eq!(
159            MemoryManager::thread_allocations().since(before_other_thread),
160            ThreadAllocations::default(),
161            "allocations on another thread must not affect this thread's counters"
162        );
163
164        unsafe { manager.deallocate(pointer, layout) };
165        let after = MemoryManager::thread_allocations().since(before);
166        assert_eq!(after.allocations(), 1);
167        assert_eq!(after.allocated_bytes(), 128);
168        assert_eq!(after.deallocated_bytes(), 128);
169        assert_eq!(after.net_bytes(), 0);
170        assert_eq!(manager.get_used(), 0);
171    }
172
173    #[test]
174    fn cross_thread_deallocation_does_not_underflow() {
175        let manager = MemoryManager::new();
176        let layout = Layout::from_size_align(64, 8).unwrap();
177        let pointer_address = unsafe { manager.allocate(CapabilityFlags::empty(), layout) }
178            .unwrap()
179            .as_ptr() as usize;
180
181        std::thread::scope(|scope| {
182            scope.spawn(|| {
183                let before = MemoryManager::thread_allocations();
184                let pointer = NonNull::new(pointer_address as *mut u8).unwrap();
185                unsafe { manager.deallocate(pointer, layout) };
186                let delta = MemoryManager::thread_allocations().since(before);
187                assert_eq!(delta.allocations(), 0);
188                assert_eq!(delta.allocated_bytes(), 0);
189                assert_eq!(delta.deallocated_bytes(), 64);
190                assert_eq!(delta.net_bytes(), -64);
191            });
192        });
193        assert_eq!(manager.get_used(), 0);
194    }
195}