Skip to main content

nadir_platform/
alloc_counter.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The allocation counter of development builds (feature `dev`). The global
16//! allocator counts every heap allocation, for each thread and for the
17//! whole process, so that tests and the game can show that a steady frame
18//! allocates nothing.
19//!
20//! With the feature on, every binary that links this crate allocates
21//! through it, and no other crate may declare a `#[global_allocator]`: the
22//! build fails if one does. Turn `dev` on only from a `[features]` table
23//! or a `[dev-dependencies]` entry, never from a normal dependency, so that
24//! no release build carries it.
25//!
26//! It sees only what goes through Rust's global allocator. C libraries that
27//! call `malloc` themselves, such as Mesa, Xlib and EGL, are not counted.
28
29use std::alloc::{GlobalAlloc, Layout, System};
30use std::cell::Cell;
31use std::sync::atomic::{AtomicU64, Ordering};
32
33/// Counts of heap use, on one thread or in the whole process.
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35pub struct AllocCounts {
36    /// Allocations, reallocations included: a reallocation is how a `Vec`
37    /// or a `String` grows.
38    pub allocations: u64,
39    /// Deallocations. A reallocation is not one.
40    pub deallocations: u64,
41    /// The bytes the allocations asked for: for a reallocation, its new
42    /// size.
43    pub bytes: u64,
44}
45
46impl AllocCounts {
47    /// The counts since `earlier`, an earlier reading of the same counts.
48    #[must_use]
49    pub fn since(self, earlier: AllocCounts) -> AllocCounts {
50        AllocCounts {
51            allocations: self.allocations.wrapping_sub(earlier.allocations),
52            deallocations: self.deallocations.wrapping_sub(earlier.deallocations),
53            bytes: self.bytes.wrapping_sub(earlier.bytes),
54        }
55    }
56}
57
58/// The heap use of this thread since it started.
59pub fn thread_alloc_counts() -> AllocCounts {
60    THREAD.try_with(Cell::get).unwrap_or_default()
61}
62
63/// The heap use of every thread since the process started.
64pub fn process_alloc_counts() -> AllocCounts {
65    AllocCounts {
66        allocations: PROCESS_ALLOCATIONS.load(Ordering::Relaxed),
67        deallocations: PROCESS_DEALLOCATIONS.load(Ordering::Relaxed),
68        bytes: PROCESS_BYTES.load(Ordering::Relaxed),
69    }
70}
71
72const ZERO: AllocCounts = AllocCounts {
73    allocations: 0,
74    deallocations: 0,
75    bytes: 0,
76};
77
78thread_local! {
79    /// This thread's counts. A thread local gets its memory without the
80    /// global allocator, and this one has a constant start and no
81    /// destructor, so the allocator can read it without recursing.
82    static THREAD: Cell<AllocCounts> = const { Cell::new(ZERO) };
83}
84
85static PROCESS_ALLOCATIONS: AtomicU64 = AtomicU64::new(0);
86static PROCESS_DEALLOCATIONS: AtomicU64 = AtomicU64::new(0);
87static PROCESS_BYTES: AtomicU64 = AtomicU64::new(0);
88
89/// Counts an allocation of `bytes`. It never allocates, locks or panics, as
90/// code inside the allocator must not.
91fn count_allocation(bytes: usize) {
92    let bytes = bytes as u64;
93    PROCESS_ALLOCATIONS.fetch_add(1, Ordering::Relaxed);
94    PROCESS_BYTES.fetch_add(bytes, Ordering::Relaxed);
95    // Only a thread that is being torn down has no counts left to add to.
96    let _ = THREAD.try_with(|counts| {
97        let mut thread = counts.get();
98        thread.allocations = thread.allocations.wrapping_add(1);
99        thread.bytes = thread.bytes.wrapping_add(bytes);
100        counts.set(thread);
101    });
102}
103
104/// Counts a deallocation, as [`count_allocation`] counts an allocation.
105fn count_deallocation() {
106    PROCESS_DEALLOCATIONS.fetch_add(1, Ordering::Relaxed);
107    let _ = THREAD.try_with(|counts| {
108        let mut thread = counts.get();
109        thread.deallocations = thread.deallocations.wrapping_add(1);
110        counts.set(thread);
111    });
112}
113
114/// The global allocator of development builds: [`System`], counted.
115struct Counting;
116
117#[global_allocator]
118static ALLOCATOR: Counting = Counting;
119
120// SAFETY: each method passes its arguments, and its caller's guarantees, to
121// the same method of `System`, which meets the `GlobalAlloc` contract, and
122// returns what `System` returns. The counting never allocates, unwinds or
123// touches the memory.
124unsafe impl GlobalAlloc for Counting {
125    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
126        // SAFETY: the caller meets `GlobalAlloc::alloc`'s requirements on
127        // `layout`, which are `System::alloc`'s.
128        let pointer = unsafe { System.alloc(layout) };
129        if !pointer.is_null() {
130            count_allocation(layout.size());
131        }
132        pointer
133    }
134
135    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
136        // SAFETY: as for `alloc`.
137        let pointer = unsafe { System.alloc_zeroed(layout) };
138        if !pointer.is_null() {
139            count_allocation(layout.size());
140        }
141        pointer
142    }
143
144    unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
145        // SAFETY: the caller guarantees that `pointer` came from this
146        // allocator, which is `System`'s, with `layout`, and that
147        // `new_size` is valid for it, as `System::realloc` requires.
148        let moved = unsafe { System.realloc(pointer, layout, new_size) };
149        if !moved.is_null() {
150            count_allocation(new_size);
151        }
152        moved
153    }
154
155    unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
156        // SAFETY: the caller guarantees that `pointer` came from this
157        // allocator, which is `System`'s, with `layout`.
158        unsafe { System.dealloc(pointer, layout) };
159        count_deallocation();
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use std::hint::black_box;
166    use std::thread;
167
168    use super::*;
169
170    #[test]
171    fn a_box_counts_one_allocation_of_its_size_and_one_deallocation() {
172        let start = thread_alloc_counts();
173        let boxed = black_box(Box::new([7u8; 100]));
174        let allocated = thread_alloc_counts().since(start);
175        drop(boxed);
176        let freed = thread_alloc_counts().since(start);
177        assert_eq!(
178            allocated,
179            AllocCounts {
180                allocations: 1,
181                deallocations: 0,
182                bytes: 100
183            }
184        );
185        assert_eq!(
186            freed,
187            AllocCounts {
188                allocations: 1,
189                deallocations: 1,
190                bytes: 100
191            }
192        );
193    }
194
195    #[test]
196    fn a_vec_counts_its_growth_and_not_its_reuse() {
197        let start = thread_alloc_counts();
198        let mut numbers: Vec<u64> = Vec::with_capacity(4);
199        for number in 0..1000 {
200            numbers.push(black_box(number));
201        }
202        let grown = thread_alloc_counts().since(start);
203        // The first allocation, then a reallocation each time it doubles.
204        assert!((2..=12).contains(&grown.allocations), "{grown:?}");
205        assert_eq!(
206            grown.deallocations, 0,
207            "a reallocation is not a deallocation"
208        );
209
210        numbers.clear();
211        let refilled = thread_alloc_counts();
212        for number in 0..1000 {
213            numbers.push(black_box(number));
214        }
215        assert_eq!(
216            thread_alloc_counts().since(refilled),
217            AllocCounts::default()
218        );
219    }
220
221    #[test]
222    fn another_threads_allocations_count_for_the_process_and_not_here() {
223        const MIB: u64 = 1 << 20;
224        let (here, process) = (thread_alloc_counts(), process_alloc_counts());
225        let theirs = thread::spawn(|| {
226            let start = thread_alloc_counts();
227            drop(black_box(vec![1u8; MIB as usize]));
228            thread_alloc_counts().since(start)
229        })
230        .join()
231        .expect("the thread runs");
232        assert_eq!(theirs.allocations, 1);
233        assert_eq!(theirs.bytes, MIB);
234        // Spawning a thread allocates a little here, far less than theirs.
235        let mine = thread_alloc_counts().since(here);
236        assert!(mine.bytes < MIB, "{mine:?}");
237        // Other tests allocate at the same time, so the process may count
238        // more, never less.
239        assert!(process_alloc_counts().since(process).bytes >= MIB);
240    }
241}