1use alloc::collections::btree_map::BTreeMap;
2use core::{
3 alloc::Layout,
4 ops::Range,
5 sync::atomic::{AtomicBool, Ordering},
6};
7
8use ax_kspin::SpinNoIrq;
9use axbacktrace::Backtrace;
10
11pub(crate) static TRACKING_ENABLED: AtomicBool = AtomicBool::new(false);
12
13#[ax_percpu::def_percpu]
14pub(crate) static IN_GLOBAL_ALLOCATOR: bool = false;
15#[derive(Debug)]
22pub struct AllocationInfo {
23 pub layout: Layout,
25 pub backtrace: Backtrace,
27 pub generation: u64,
29}
30
31pub(crate) struct GlobalState {
32 pub map: BTreeMap<usize, AllocationInfo>,
34 pub generation: u64,
35}
36
37static STATE: SpinNoIrq<GlobalState> = SpinNoIrq::new(GlobalState {
38 map: BTreeMap::new(),
39 generation: 0,
40});
41
42pub fn enable_tracking() {
44 TRACKING_ENABLED.store(true, Ordering::SeqCst);
45}
46
47pub fn disable_tracking() {
49 TRACKING_ENABLED.store(false, Ordering::SeqCst);
50}
51
52pub fn tracking_enabled() -> bool {
54 TRACKING_ENABLED.load(Ordering::SeqCst)
55}
56
57pub(crate) fn with_state<R>(f: impl FnOnce(Option<&mut GlobalState>) -> R) -> R {
58 IN_GLOBAL_ALLOCATOR.with_current(|in_global| {
59 if *in_global || !tracking_enabled() {
60 f(None)
61 } else {
62 *in_global = true;
63 let mut state = STATE.lock();
64 let result = f(Some(&mut state));
65 *in_global = false;
66 result
67 }
68 })
69}
70
71pub fn current_generation() -> u64 {
78 STATE.lock().generation
79}
80
81pub fn allocations_in(range: Range<u64>, visitor: impl FnMut(&AllocationInfo)) {
84 with_state(|state| {
85 state
86 .unwrap()
87 .map
88 .values()
89 .filter(move |info| range.contains(&info.generation))
90 .for_each(visitor)
91 });
92}