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        // when sampling is disabled via
45        // DD_HEAP_SAMPLING_ENABLED, forward straight to the inner allocator
46        // so we're indistinguishable from an unwrapped allocator. realloc /
47        // alloc_zeroed are inherited from GlobalAlloc and dispatch back
48        // through alloc/dealloc, so they pass through too.
49        if !libdd_profiling_heap_sampler::heap_sampling_enabled() {
50            return self.inner.alloc(layout);
51        }
52        let req = dd_allocation_requested(layout.size(), layout.align());
53        // Sampled paths may bump the size for inline flag storage;
54        // forward the returned size to the inner allocator verbatim.
55        let inner_layout = Layout::from_size_align_unchecked(req.size, layout.align());
56        let raw = self.inner.alloc(inner_layout);
57        dd_allocation_created(raw.cast(), req).cast()
58    }
59
60    #[cfg(not(target_os = "linux"))]
61    #[inline(always)]
62    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
63        self.inner.alloc(layout)
64    }
65
66    #[cfg(target_os = "linux")]
67    #[inline]
68    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
69        // Honour bypass
70        if !libdd_profiling_heap_sampler::heap_sampling_enabled() {
71            return self.inner.dealloc(ptr, layout);
72        }
73        let freed = dd_allocation_freed(ptr.cast(), layout.size(), layout.align());
74        // `layout.align()` is reused here rather than anything derived from
75        // `freed`: alignment never changes between the original `alloc` and
76        // this `dealloc`, so pairing `freed.size` with the caller's own
77        // alignment is exactly what `GlobalAlloc::dealloc`'s safety contract
78        // already requires (the layout passed here must match the one used
79        // for the original allocation). This isn't a guarantee `SampledAllocator`
80        // adds — it's just satisfying the contract our caller is on the hook for.
81        let inner_layout = Layout::from_size_align_unchecked(freed.size, layout.align());
82        self.inner.dealloc(freed.ptr.cast(), inner_layout);
83    }
84
85    #[cfg(not(target_os = "linux"))]
86    #[inline(always)]
87    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
88        self.inner.dealloc(ptr, layout);
89    }
90}
91
92// Tests dispatch through the wrapped allocator and (on Linux) into the
93// sampler's C-side TLS primitives via FFI; miri can't execute those.
94#[cfg(all(test, not(miri)))]
95mod tests {
96    use super::*;
97    use core::sync::atomic::{AtomicUsize, Ordering};
98    #[cfg(target_os = "linux")]
99    use libdd_profiling_heap_sampler::dd_tl_state_get;
100
101    /// Minimal `GlobalAlloc` that forwards to `System` while recording
102    /// counters so tests can assert the sampled wrapper passed the right
103    /// size/align through.
104    struct CountingSystem {
105        alloc_count: AtomicUsize,
106        dealloc_count: AtomicUsize,
107        last_alloc_size: AtomicUsize,
108    }
109
110    impl CountingSystem {
111        const fn new() -> Self {
112            Self {
113                alloc_count: AtomicUsize::new(0),
114                dealloc_count: AtomicUsize::new(0),
115                last_alloc_size: AtomicUsize::new(0),
116            }
117        }
118    }
119
120    unsafe impl GlobalAlloc for CountingSystem {
121        unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
122            self.alloc_count.fetch_add(1, Ordering::Relaxed);
123            self.last_alloc_size.store(layout.size(), Ordering::Relaxed);
124            System.alloc(layout)
125        }
126        unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
127            self.dealloc_count.fetch_add(1, Ordering::Relaxed);
128            System.dealloc(ptr, layout);
129        }
130    }
131
132    #[test]
133    fn alloc_dealloc_forwards_to_inner() {
134        let sampled = SampledAllocator::new(CountingSystem::new());
135        let layout = Layout::from_size_align(128, 16).unwrap();
136
137        unsafe {
138            let p = sampled.alloc(layout);
139            assert!(!p.is_null());
140
141            assert_eq!(sampled.inner.alloc_count.load(Ordering::Relaxed), 1);
142            // Sampler may bump size for flag storage once that's wired up;
143            // today it returns the requested size verbatim.
144            assert!(sampled.inner.last_alloc_size.load(Ordering::Relaxed) >= 128);
145
146            sampled.dealloc(p, layout);
147            assert_eq!(sampled.inner.dealloc_count.load(Ordering::Relaxed), 1);
148        }
149    }
150
151    // Touches sampler TLS internals, which only exist on Linux.
152    #[cfg(target_os = "linux")]
153    #[test]
154    fn alloc_skips_tls_when_no_profiler_attached() {
155        // With the USDT semaphore inactive, alloc should not touch TLS.
156        std::thread::spawn(|| unsafe {
157            assert!(dd_tl_state_get().is_null());
158
159            let sampled = SampledAllocator::<System>::DEFAULT;
160            let layout = Layout::from_size_align(64, 8).unwrap();
161            let p = sampled.alloc(layout);
162            assert!(!p.is_null());
163
164            // Semaphore inactive: TLS never initialized.
165            assert!(dd_tl_state_get().is_null());
166
167            sampled.dealloc(p, layout);
168        })
169        .join()
170        .unwrap();
171    }
172
173    #[test]
174    fn default_matches_new_system() {
175        let _ = SampledAllocator::<System>::DEFAULT;
176        let _ = SampledAllocator::new(System);
177    }
178}