Skip to main content

libdd_profiling_heap_allocator/
allocator.rs

1// Copyright 2025-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3
4use core::alloc::{GlobalAlloc, Layout};
5use std::alloc::System;
6
7#[cfg(target_os = "linux")]
8use libdd_profiling_heap_sampler::{
9    dd_allocation_created, dd_allocation_freed, dd_allocation_requested,
10};
11
12/// `GlobalAlloc` wrapper that routes each alloc/dealloc through
13/// `libdd-profiling-heap-sampler` before forwarding to the inner allocator `A`.
14///
15/// The default `realloc` / `alloc_zeroed` impls from [`GlobalAlloc`] are
16/// inherited; they dispatch back to `alloc` / `dealloc`, so sampling
17/// still fires for those paths.
18///
19/// On non-Linux targets the sampler integration is a no-op and this is
20/// just a transparent forwarder to `inner`; callers can use the same
21/// `#[global_allocator]` setup unconditionally.
22pub struct SampledAllocator<A> {
23    inner: A,
24}
25
26impl<A> SampledAllocator<A> {
27    /// Wrap an allocator. `const` so it's usable directly in a
28    /// `#[global_allocator]` static.
29    pub const fn new(inner: A) -> Self {
30        Self { inner }
31    }
32}
33
34impl SampledAllocator<System> {
35    /// Default wrap of the system allocator, usable directly in a
36    /// `#[global_allocator]` static.
37    pub const DEFAULT: Self = Self { inner: System };
38}
39
40unsafe impl<A: GlobalAlloc> GlobalAlloc for SampledAllocator<A> {
41    #[cfg(target_os = "linux")]
42    #[inline]
43    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
44        unsafe {
45            // when sampling is disabled via
46            // DD_HEAP_SAMPLING_ENABLED, forward straight to the inner allocator
47            // so we're indistinguishable from an unwrapped allocator. realloc /
48            // alloc_zeroed are inherited from GlobalAlloc and dispatch back
49            // through alloc/dealloc, so they pass through too.
50            if !libdd_profiling_heap_sampler::heap_sampling_enabled() {
51                return self.inner.alloc(layout);
52            }
53            let req = dd_allocation_requested(layout.size(), layout.align());
54            // Sampled paths may bump the size for inline flag storage;
55            // forward the returned size to the inner allocator verbatim.
56            let inner_layout = Layout::from_size_align_unchecked(req.size, layout.align());
57            let raw = self.inner.alloc(inner_layout);
58            dd_allocation_created(raw.cast(), req).cast()
59        }
60    }
61
62    #[cfg(not(target_os = "linux"))]
63    #[inline(always)]
64    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
65        unsafe { self.inner.alloc(layout) }
66    }
67
68    #[cfg(target_os = "linux")]
69    #[inline]
70    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
71        unsafe {
72            // Honour bypass
73            if !libdd_profiling_heap_sampler::heap_sampling_enabled() {
74                return self.inner.dealloc(ptr, layout);
75            }
76            let freed = dd_allocation_freed(ptr.cast(), layout.size(), layout.align());
77            // `layout.align()` is reused here rather than anything derived from
78            // `freed`: alignment never changes between the original `alloc` and
79            // this `dealloc`, so pairing `freed.size` with the caller's own
80            // alignment is exactly what `GlobalAlloc::dealloc`'s safety contract
81            // already requires (the layout passed here must match the one used
82            // for the original allocation). This isn't a guarantee `SampledAllocator`
83            // adds — it's just satisfying the contract our caller is on the hook for.
84            let inner_layout = Layout::from_size_align_unchecked(freed.size, layout.align());
85            self.inner.dealloc(freed.ptr.cast(), inner_layout);
86        }
87    }
88
89    #[cfg(not(target_os = "linux"))]
90    #[inline(always)]
91    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
92        unsafe {
93            self.inner.dealloc(ptr, layout);
94        }
95    }
96}
97
98// Tests dispatch through the wrapped allocator and (on Linux) into the
99// sampler's C-side TLS primitives via FFI; miri can't execute those.
100#[cfg(all(test, not(miri)))]
101mod tests {
102    use super::*;
103    use core::sync::atomic::{AtomicUsize, Ordering};
104    #[cfg(target_os = "linux")]
105    use libdd_profiling_heap_sampler::dd_tl_state_get;
106
107    /// Minimal `GlobalAlloc` that forwards to `System` while recording
108    /// counters so tests can assert the sampled wrapper passed the right
109    /// size/align through.
110    struct CountingSystem {
111        alloc_count: AtomicUsize,
112        dealloc_count: AtomicUsize,
113        last_alloc_size: AtomicUsize,
114    }
115
116    impl CountingSystem {
117        const fn new() -> Self {
118            Self {
119                alloc_count: AtomicUsize::new(0),
120                dealloc_count: AtomicUsize::new(0),
121                last_alloc_size: AtomicUsize::new(0),
122            }
123        }
124    }
125
126    unsafe impl GlobalAlloc for CountingSystem {
127        unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
128            unsafe {
129                self.alloc_count.fetch_add(1, Ordering::Relaxed);
130                self.last_alloc_size.store(layout.size(), Ordering::Relaxed);
131                System.alloc(layout)
132            }
133        }
134        unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
135            unsafe {
136                self.dealloc_count.fetch_add(1, Ordering::Relaxed);
137                System.dealloc(ptr, layout);
138            }
139        }
140    }
141
142    #[test]
143    fn alloc_dealloc_forwards_to_inner() {
144        let sampled = SampledAllocator::new(CountingSystem::new());
145        let layout = Layout::from_size_align(128, 16).unwrap();
146
147        unsafe {
148            let p = sampled.alloc(layout);
149            assert!(!p.is_null());
150
151            assert_eq!(sampled.inner.alloc_count.load(Ordering::Relaxed), 1);
152            // Sampler may bump size for flag storage once that's wired up;
153            // today it returns the requested size verbatim.
154            assert!(sampled.inner.last_alloc_size.load(Ordering::Relaxed) >= 128);
155
156            sampled.dealloc(p, layout);
157            assert_eq!(sampled.inner.dealloc_count.load(Ordering::Relaxed), 1);
158        }
159    }
160
161    // Touches sampler TLS internals, which only exist on Linux.
162    #[cfg(target_os = "linux")]
163    #[test]
164    fn alloc_skips_tls_when_no_profiler_attached() {
165        // With the USDT semaphore inactive, alloc should not touch TLS.
166        std::thread::spawn(|| unsafe {
167            assert!(dd_tl_state_get().is_null());
168
169            let sampled = SampledAllocator::<System>::DEFAULT;
170            let layout = Layout::from_size_align(64, 8).unwrap();
171            let p = sampled.alloc(layout);
172            assert!(!p.is_null());
173
174            // Semaphore inactive: TLS never initialized.
175            assert!(dd_tl_state_get().is_null());
176
177            sampled.dealloc(p, layout);
178        })
179        .join()
180        .unwrap();
181    }
182
183    #[test]
184    fn default_matches_new_system() {
185        let _ = SampledAllocator::<System>::DEFAULT;
186        let _ = SampledAllocator::new(System);
187    }
188}