1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
use super::*;
/// Lock-free allocation recording helpers for `CountingAllocator`.
impl CountingAllocator {
/// Records one completed heap allocation when tracking is active.
///
/// # Arguments
///
/// - `usize` - Allocated byte size from `Layout::size`.
#[inline(always)]
fn record_alloc(size: usize) {
if ALLOC_TRACK_DEPTH.load(Ordering::Relaxed) == 0 {
return;
}
let bytes: u64 = size as u64;
let signed: i64 = size as i64;
let _: u64 = ALLOC_COUNT.fetch_add(1, Ordering::Relaxed);
let _: u64 = BYTES_ALLOCATED.fetch_add(bytes, Ordering::Relaxed);
let _: i64 = LIVE_ALLOCS_DELTA.fetch_add(1, Ordering::Relaxed);
let next_live: i64 = LIVE_BYTES_DELTA
.fetch_add(signed, Ordering::Relaxed)
.saturating_add(signed);
if next_live > 0 {
let _: u64 = PEAK_LIVE_BYTES.fetch_max(next_live as u64, Ordering::Relaxed);
}
}
/// Records one completed heap deallocation when tracking is active.
///
/// # Arguments
///
/// - `usize` - Deallocated byte size from `Layout::size`.
#[inline(always)]
fn record_dealloc(size: usize) {
if ALLOC_TRACK_DEPTH.load(Ordering::Relaxed) == 0 {
return;
}
let bytes: u64 = size as u64;
let signed: i64 = size as i64;
let _: u64 = FREE_COUNT.fetch_add(1, Ordering::Relaxed);
let _: u64 = BYTES_FREED.fetch_add(bytes, Ordering::Relaxed);
let _: i64 = LIVE_ALLOCS_DELTA.fetch_sub(1, Ordering::Relaxed);
let _: i64 = LIVE_BYTES_DELTA.fetch_sub(signed, Ordering::Relaxed);
}
/// Records one completed heap reallocation when tracking is active.
///
/// # Arguments
///
/// - `usize` - Previous byte size from `Layout::size`.
/// - `usize` - New requested byte size.
#[inline(always)]
fn record_realloc(old_size: usize, new_size: usize) {
if ALLOC_TRACK_DEPTH.load(Ordering::Relaxed) == 0 {
return;
}
let _: u64 = ALLOC_COUNT.fetch_add(1, Ordering::Relaxed);
let _: u64 = FREE_COUNT.fetch_add(1, Ordering::Relaxed);
let _: u64 = BYTES_ALLOCATED.fetch_add(new_size as u64, Ordering::Relaxed);
let _: u64 = BYTES_FREED.fetch_add(old_size as u64, Ordering::Relaxed);
let delta: i64 = (new_size as i64).saturating_sub(old_size as i64);
let next_live: i64 = LIVE_BYTES_DELTA
.fetch_add(delta, Ordering::Relaxed)
.saturating_add(delta);
if next_live > 0 {
let _: u64 = PEAK_LIVE_BYTES.fetch_max(next_live as u64, Ordering::Relaxed);
}
}
}
/// Global allocator delegation with relaxed fast-path counting for `CountingAllocator`.
unsafe impl GlobalAlloc for CountingAllocator {
/// Allocates memory through the system allocator and records bytes when tracking is active.
///
/// # Arguments
///
/// - `&Self` - Counting allocator reference.
/// - `Layout` - Requested memory layout.
///
/// # Returns
///
/// - `*mut u8` - Pointer to allocated memory or null on allocation failure.
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let ptr: *mut u8 = unsafe { System.alloc(layout) };
if !ptr.is_null() {
Self::record_alloc(layout.size());
}
ptr
}
/// Deallocates memory through the system allocator and records freed bytes when tracking is active.
///
/// # Arguments
///
/// - `&Self` - Counting allocator reference.
/// - `*mut u8` - Pointer to previously allocated memory.
/// - `Layout` - Original allocation layout.
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
Self::record_dealloc(layout.size());
unsafe { System.dealloc(ptr, layout) };
}
/// Allocates zero-initialized memory through the system allocator and records bytes when tracking is active.
///
/// # Arguments
///
/// - `&Self` - Counting allocator reference.
/// - `Layout` - Requested memory layout.
///
/// # Returns
///
/// - `*mut u8` - Pointer to zeroed memory or null on allocation failure.
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
let ptr: *mut u8 = unsafe { System.alloc_zeroed(layout) };
if !ptr.is_null() {
Self::record_alloc(layout.size());
}
ptr
}
/// Reallocates memory through the system allocator and records byte deltas when tracking is active.
///
/// # Arguments
///
/// - `&Self` - Counting allocator reference.
/// - `*mut u8` - Pointer to previously allocated memory.
/// - `Layout` - Previous allocation layout.
/// - `usize` - New requested byte size.
///
/// # Returns
///
/// - `*mut u8` - Pointer to reallocated memory or null on failure.
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
let next: *mut u8 = unsafe { System.realloc(ptr, layout, new_size) };
if !next.is_null() {
Self::record_realloc(layout.size(), new_size);
}
next
}
}
/// Delta arithmetic for `RawAllocCounters`.
impl RawAllocCounters {
/// Computes an `AllocationSnapshot` delta relative to an earlier `before` counter capture.
///
/// # Arguments
///
/// - `&Self` - Later counter snapshot.
/// - `RawAllocCounters` - Earlier baseline counter snapshot.
///
/// # Returns
///
/// - `AllocationSnapshot` - Exact allocation and byte delta between `before` and `self`.
#[must_use]
pub fn delta_since(&self, before: RawAllocCounters) -> AllocationSnapshot {
let alloc_count: u64 = self
.get_alloc_count()
.saturating_sub(before.get_alloc_count());
let free_count: u64 = self
.get_free_count()
.saturating_sub(before.get_free_count());
let bytes_allocated: u64 = self
.get_bytes_allocated()
.saturating_sub(before.get_bytes_allocated());
let bytes_freed: u64 = self
.get_bytes_freed()
.saturating_sub(before.get_bytes_freed());
let signed_live_bytes: i64 = self
.get_live_bytes_delta()
.saturating_sub(before.get_live_bytes_delta());
let signed_live_allocs: i64 = self
.get_live_allocs_delta()
.saturating_sub(before.get_live_allocs_delta());
let live_bytes_delta: u64 = if signed_live_bytes > 0 {
signed_live_bytes as u64
} else {
0
};
let live_allocs_delta: u64 = if signed_live_allocs > 0 {
signed_live_allocs as u64
} else {
0
};
let peak_live_bytes: u64 = self.get_peak_live_bytes().max(live_bytes_delta);
AllocationSnapshot::new(
alloc_count,
free_count,
bytes_allocated,
bytes_freed,
live_bytes_delta,
live_allocs_delta,
peak_live_bytes,
)
}
}
/// Scoped allocation tracking lifecycle for `AllocationScopeGuard`.
impl AllocationScopeGuard {
/// Enters a serialized allocation tracking scope, resetting live-delta and peak counters on outermost entry.
///
/// # Returns
///
/// - `Self` - Active RAII scope guard that disables tracking on drop.
#[must_use]
pub fn enter() -> Self {
let already_in_scope: bool = ALLOC_THREAD_IN_SCOPE.with(|flag: &Cell<bool>| flag.get());
if already_in_scope {
let _: usize = ALLOC_TRACK_DEPTH.fetch_add(1, Ordering::AcqRel);
let start_counters: RawAllocCounters = snapshot_raw_alloc_counters();
return Self {
_lock_guard: None,
owns_scope: false,
start_counters,
};
}
let lock_guard: MutexGuard<'static, ()> = ALLOC_SCOPE_LOCK
.lock()
.unwrap_or_else(|poisoned: PoisonError<MutexGuard<'static, ()>>| poisoned.into_inner());
ALLOC_THREAD_IN_SCOPE.with(|flag: &Cell<bool>| flag.set(true));
LIVE_BYTES_DELTA.store(0, Ordering::Relaxed);
LIVE_ALLOCS_DELTA.store(0, Ordering::Relaxed);
PEAK_LIVE_BYTES.store(0, Ordering::Relaxed);
let _: usize = ALLOC_TRACK_DEPTH.fetch_add(1, Ordering::AcqRel);
fence(Ordering::SeqCst);
let start_counters: RawAllocCounters = snapshot_raw_alloc_counters();
Self {
_lock_guard: Some(lock_guard),
owns_scope: true,
start_counters,
}
}
/// Returns the cumulative `AllocationSnapshot` recorded since this guard was entered.
///
/// # Arguments
///
/// - `&Self` - Active allocation scope guard.
///
/// # Returns
///
/// - `AllocationSnapshot` - Elapsed allocation counts and bytes inside this scope.
#[must_use]
pub fn elapsed_snapshot(&self) -> AllocationSnapshot {
let Self { start_counters, .. } = *self;
fence(Ordering::SeqCst);
snapshot_raw_alloc_counters().delta_since(start_counters)
}
}
/// Automatic scope teardown for `AllocationScopeGuard`.
impl Drop for AllocationScopeGuard {
/// Decrements the active tracking depth and releases thread scope ownership on drop.
///
/// # Arguments
///
/// - `&Self` - Dropping allocation scope guard.
fn drop(&mut self) {
let Self { owns_scope, .. } = *self;
fence(Ordering::SeqCst);
let _: usize = ALLOC_TRACK_DEPTH.fetch_sub(1, Ordering::AcqRel);
if owns_scope {
ALLOC_THREAD_IN_SCOPE.with(|flag: &Cell<bool>| flag.set(false));
}
}
}