Skip to main content

libdd_profiling_heap_sampler/
lib.rs

1// Copyright 2025-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3
4//! Rust bindings for the libdd-profiling-heap-sampler C library.
5//!
6//! FFI declarations and `#[repr(C)]` struct mirrors are generated by
7//! `bindgen` from the public headers under `include/datadog/heap/` at
8//! build time; see `build.rs`. All items are re-exported at the crate
9//! root.
10//!
11//! The `static inline __attribute__((always_inline))` fast-path helpers in
12//! the headers have no linker symbol, so bindgen's `wrap_static_fns`
13//! emits a C shim for each - the shim's body is the static-inline
14//! inlined at its one call site. The shim's link-symbol is
15//! `<fn>__extern`, but bindgen exposes the Rust fn under the natural C
16//! name via `#[link_name]`, so callers write `dd_allocation_requested(…)`
17//! the same way they would in C.
18
19// USDT/SystemTap is Linux-only; on every other target the crate is an empty
20// rlib. macOS is `unix` too, so we gate on target_os = "linux" specifically.
21#[cfg(target_os = "linux")]
22#[allow(
23    non_camel_case_types,
24    non_snake_case,
25    non_upper_case_globals,
26    dead_code
27)]
28mod sys {
29    include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
30}
31
32#[cfg(target_os = "linux")]
33pub use sys::*;
34
35/// Runtime ELF self-inspection asserting one USDT note per probe. Opt-in via
36/// the `sanity-check` feature (pulls in the `elf`/`anyhow` deps).
37#[cfg(all(target_os = "linux", feature = "sanity-check"))]
38pub mod usdt_check;
39
40/// Name of the environment variable that toggles heap sampling.
41pub const DD_HEAP_SAMPLING_ENABLED: &str = "DD_HEAP_SAMPLING_ENABLED";
42
43/// Set the default mean sample distance (bytes between samples).
44///
45/// Pass `0` to revert to the compiled-in default (`DD_SAMPLING_INTERVAL_DEFAULT`,
46/// 512 KiB). Values below 64 KiB are clamped to 64 KiB to avoid
47/// excessive overhead.
48#[cfg(target_os = "linux")]
49pub fn set_default_sampling_distance(distance_bytes: u64) {
50    // SAFETY: dd_set_default_sampling_interval performs a single relaxed atomic
51    // store.
52    unsafe { sys::dd_set_default_sampling_interval(distance_bytes) }
53}
54
55/// Returns true when an external profiler is currently attached to the
56/// `ddheap:alloc` USDT in this object file.
57///
58/// This is a point-in-time read of the alloc probe's USDT semaphore. A profiler
59/// can attach or detach immediately after this returns. Use it as a
60/// diagnostic/readiness signal, not as a synchronization primitive.
61#[cfg(target_os = "linux")]
62#[inline]
63pub fn is_profiler_attached() -> bool {
64    // SAFETY: dd_heap_profiler_attached performs a single semaphore read and
65    // has no preconditions.
66    unsafe { sys::dd_heap_profiler_attached() }
67}
68
69/// Non-Linux builds do not expose USDT heap probes.
70#[cfg(not(target_os = "linux"))]
71#[inline]
72pub fn is_profiler_attached() -> bool {
73    false
74}
75
76/// Whether heap sampling is enabled for this process. Users of this
77/// library can use this to check if they should setup allocation tracking
78/// or not.
79///
80/// Reads [`DD_HEAP_SAMPLING_ENABLED`] once and caches the result: sampling
81/// is enabled by default and disabled only when the variable is set to a
82/// falsey value (`0`, `false`, `no`, `off`, case-insensitive). Consumers
83/// (the GOT interposer, the `GlobalAlloc` wrapper) use this as a
84/// short-circuit so that a disabled sampler is as close as possible to not
85/// being installed at all.
86///
87/// The lookup uses `getenv` rather than [`std::env::var`] specifically so it
88/// performs no heap allocation so that our consumers don't have to worry about
89/// re-entrancy.
90#[inline]
91pub fn heap_sampling_enabled() -> bool {
92    use std::sync::OnceLock;
93    static ENABLED: OnceLock<bool> = OnceLock::new();
94    *ENABLED.get_or_init(read_heap_sampling_enabled)
95}
96
97/// Interpret a raw environment-variable value. `None` (unset) enables
98/// sampling; a value equal to `0`/`false`/`no`/`off` (case-insensitive)
99/// disables it; anything else enables it. Split out from the `getenv`
100/// lookup so the policy is unit-testable without touching process state or
101/// the process-wide cache in [`heap_sampling_enabled`].
102fn parse_heap_sampling_enabled(value: Option<&[u8]>) -> bool {
103    match value {
104        None => true,
105        Some(bytes) => {
106            !(bytes.eq_ignore_ascii_case(b"0")
107                || bytes.eq_ignore_ascii_case(b"false")
108                || bytes.eq_ignore_ascii_case(b"no")
109                || bytes.eq_ignore_ascii_case(b"off"))
110        }
111    }
112}
113
114#[cfg(unix)]
115fn read_heap_sampling_enabled() -> bool {
116    use core::ffi::{CStr, c_char};
117
118    unsafe extern "C" {
119        fn getenv(name: *const c_char) -> *mut c_char;
120    }
121
122    const NAME: &[u8] = b"DD_HEAP_SAMPLING_ENABLED\0";
123
124    // SAFETY: NAME is a valid NUL-terminated C string; getenv returns either
125    // NULL or a pointer to a NUL-terminated string in the process
126    // environment, which we only read. No allocation occurs, so this is safe
127    // to call from inside a GlobalAlloc hot path.
128    unsafe {
129        let value = getenv(NAME.as_ptr().cast());
130        let bytes = (!value.is_null()).then(|| CStr::from_ptr(value).to_bytes());
131        parse_heap_sampling_enabled(bytes)
132    }
133}
134
135#[cfg(not(unix))]
136fn read_heap_sampling_enabled() -> bool {
137    // Sampling only exists on Linux; elsewhere there's no environment block to
138    // read, so this is moot. Route through the shared policy (None -> enabled)
139    // so parse_heap_sampling_enabled isn't dead code on non-unix targets.
140    parse_heap_sampling_enabled(None)
141}
142
143// Pure-logic tests for the env-var policy; no FFI, safe on every target
144// and under miri.
145#[cfg(test)]
146mod sampling_flag_tests {
147    use super::parse_heap_sampling_enabled;
148
149    #[test]
150    fn unset_defaults_to_enabled() {
151        assert!(parse_heap_sampling_enabled(None));
152    }
153
154    #[test]
155    fn falsey_values_disable() {
156        for v in [
157            &b"0"[..],
158            b"false",
159            b"FALSE",
160            b"False",
161            b"no",
162            b"NO",
163            b"off",
164            b"Off",
165        ] {
166            assert!(
167                !parse_heap_sampling_enabled(Some(v)),
168                "{v:?} should disable"
169            );
170        }
171    }
172
173    #[test]
174    fn truthy_and_unrecognized_values_enable() {
175        for v in [&b"1"[..], b"true", b"TRUE", b"yes", b"on", b"", b"maybe"] {
176            assert!(parse_heap_sampling_enabled(Some(v)), "{v:?} should enable");
177        }
178    }
179}
180
181// Tests exercise the C/FFI sampler primitives directly; miri can't
182// execute foreign code, so skip the whole module under miri.
183#[cfg(all(test, target_os = "linux", not(miri)))]
184mod tests {
185    use super::*;
186    use core::ffi::c_void;
187
188    #[test]
189    fn alloc_req_layout_matches_c() {
190        assert_eq!(core::mem::size_of::<dd_alloc_req_t>(), 32);
191        assert_eq!(core::mem::align_of::<dd_alloc_req_t>(), 8);
192    }
193
194    #[test]
195    fn tl_state_layout_matches_c() {
196        assert_eq!(core::mem::size_of::<dd_tl_state_t>(), 24);
197        assert_eq!(core::mem::align_of::<dd_tl_state_t>(), 8);
198    }
199
200    #[test]
201    fn requested_skips_tls_init_when_no_profiler_attached() {
202        std::thread::spawn(|| unsafe {
203            assert!(dd_tl_state_get().is_null());
204            let req = dd_allocation_requested(1, 1);
205            assert_eq!(req.size, 1);
206            assert_eq!(req.weight, 0);
207            // Semaphore is inactive (no profiler), so TLS is never touched.
208            assert!(dd_tl_state_get().is_null());
209        })
210        .join()
211        .unwrap();
212    }
213
214    #[test]
215    fn created_is_passthrough_when_weight_zero() {
216        unsafe {
217            let fake = 0xdead_beef_usize as *mut c_void;
218            let req = dd_alloc_req_t {
219                size: 64,
220                user_size: 64,
221                alignment: 8,
222                weight: 0,
223            };
224            assert_eq!(dd_allocation_created(fake, req), fake);
225        }
226    }
227
228    // With live-heap tracking compiled out, even a "sampled" allocation
229    // (weight > 0) is never flagged: the created pointer is the raw pointer
230    // unchanged. The alloc USDT still fires (allocation profiling), but
231    // there is no tag/header, so no matching free is expected.
232    #[cfg(not(feature = "live-heap"))]
233    #[test]
234    fn created_does_not_flag_when_live_heap_disabled() {
235        unsafe {
236            let fake = 0xdead_beef_usize as *mut c_void;
237            let req = dd_alloc_req_t {
238                size: 64,
239                user_size: 64,
240                alignment: 8,
241                weight: 5,
242            };
243            assert_eq!(dd_allocation_created(fake, req), fake);
244        }
245    }
246
247    // With live-heap tracking compiled out, dd_allocation_freed is a
248    // straight passthrough: it never inspects the sample-flag header and
249    // never fires ddheap:free. Verify this even when the underlying
250    // memory happens to contain the magic pattern that *would* trigger
251    // the slow path if live-heap were enabled.
252    #[cfg(not(feature = "live-heap"))]
253    #[test]
254    fn freed_is_passthrough_when_live_heap_disabled() {
255        const MAGIC: u64 = 0xfab1eddec0dedca7;
256        const HEADER_BYTES: usize = 16;
257
258        // Set up a buffer with the magic header so that, if the flag-check
259        // were compiled in, it would consider this allocation sampled.
260        let mut buf = vec![0u8; 128];
261        let base = buf.as_mut_ptr() as usize;
262        let user_addr = base + HEADER_BYTES;
263
264        // Stamp magic at ptr - HEADER_BYTES
265        buf[0..8].copy_from_slice(&MAGIC.to_ne_bytes());
266        // Stamp a plausible offset
267        buf[8..16].copy_from_slice(&(HEADER_BYTES as u64).to_ne_bytes());
268
269        let ptr = user_addr as *mut c_void;
270        unsafe {
271            let freed = dd_allocation_freed(ptr, 64, 8);
272            // Without live-heap the pointer is returned unchanged (no
273            // flag-check, no raw-pointer recovery).
274            assert_eq!(freed.ptr, ptr);
275            assert_eq!(freed.size, 64);
276        }
277    }
278
279    #[test]
280    fn zero_sampling_interval_disables_sampling() {
281        let mut tl = dd_tl_state_t {
282            sampling_interval: 0,
283            remaining_bytes: 0,
284            remaining_bytes_initialized: true,
285            initialized: true,
286            reentry_guard: false,
287            rng: 1,
288        };
289
290        let req = unsafe { dd_allocation_requested_slow(&mut tl, 64, 8) };
291
292        assert_eq!(req.size, 64);
293        assert_eq!(req.user_size, 64);
294        assert_eq!(req.alignment, 8);
295        assert_eq!(req.weight, 0);
296        assert!(!tl.reentry_guard);
297    }
298
299    #[test]
300    fn freed_unsampled_returns_inputs_unchanged() {
301        // The C side now reads 8 bytes at ptr-16 looking for DD_MAGIC,
302        // so we need a real buffer underneath. Zero contents won't match,
303        // so the function returns inputs verbatim.
304        let mut buf = vec![0u8; 128];
305        let ptr = unsafe { buf.as_mut_ptr().add(16) } as *mut c_void;
306        unsafe {
307            let freed = dd_allocation_freed(ptr, 64, 8);
308            assert_eq!(freed.ptr, ptr);
309            assert_eq!(freed.size, 64);
310        }
311    }
312
313    #[cfg(all(target_arch = "x86_64", feature = "live-heap"))]
314    #[test]
315    fn sample_flag_check_fast_rejects_invalid_offset() {
316        const MAGIC: u64 = 0xfab1eddec0dedca7;
317        const HEADER_BYTES: usize = 16;
318
319        let mut buf = vec![0u8; 8192];
320        let base = buf.as_mut_ptr() as usize;
321        let user_addr = (base + 128 + 4095) & !4095;
322        let user_addr = user_addr + 64;
323        assert!(user_addr + 64 <= base + buf.len());
324
325        let header = user_addr - HEADER_BYTES;
326        let header_idx = header - base;
327        buf[header_idx..header_idx + 8].copy_from_slice(&MAGIC.to_ne_bytes());
328        // Too small to have been produced by x86_apply().
329        buf[header_idx + 8..header_idx + 16].copy_from_slice(&8u64.to_ne_bytes());
330
331        let mut raw = core::ptr::null_mut();
332        let sampled = unsafe { dd_sample_flag_check_and_clear(user_addr as *mut c_void, &mut raw) };
333
334        assert!(!sampled);
335        assert!(raw.is_null());
336        assert_eq!(&buf[header_idx..header_idx + 8], &MAGIC.to_ne_bytes());
337    }
338
339    #[cfg(all(target_arch = "x86_64", feature = "live-heap"))]
340    #[test]
341    fn freed_slow_size_matches_requested_bump_formula() {
342        const HEADER_BYTES: usize = 16;
343
344        fn requested_bumped_size(user_size: usize, alignment: usize) -> usize {
345            let base = alignment.max(HEADER_BYTES);
346            let reserve = 2 * base;
347            let bumped = user_size + reserve;
348            if alignment > 1 {
349                let mask = alignment - 1;
350                (bumped + mask) & !mask
351            } else {
352                bumped
353            }
354        }
355
356        let user_size = 100;
357        let alignment = 16;
358        let base = alignment.max(HEADER_BYTES);
359        let raw = 0x100000usize as *mut c_void;
360        let ptr = (0x100000usize + base) as *mut c_void;
361
362        let freed = unsafe { dd_allocation_freed_slow(ptr, raw, user_size, alignment) };
363
364        assert_eq!(freed.ptr, raw);
365        assert_eq!(freed.size, requested_bumped_size(user_size, alignment));
366    }
367
368    // When a sampled block is realloc'd to a size so large that reserving
369    // room for its header would overflow SIZE_MAX, prepare() must still
370    // forward the RAW pointer to the underlying realloc - not the offset
371    // user pointer, which is mid-chunk and would corrupt the heap. Drives
372    // prepare() directly, so the oversized request is never made.
373    #[cfg(all(target_arch = "x86_64", feature = "live-heap"))]
374    #[test]
375    fn realloc_prepare_oversized_sampled_uses_raw_pointer() {
376        let mut buf = vec![0u8; 256];
377        let raw = buf.as_mut_ptr() as *mut c_void;
378
379        // Flag the block: stamps the header and returns user = raw + offset.
380        let user = unsafe { dd_sample_flag_apply(raw, 16) };
381        assert_ne!(
382            user, raw,
383            "apply should offset the user pointer past the header"
384        );
385
386        let prep = unsafe { dd_allocation_realloc_prepare(user, usize::MAX) };
387        assert_eq!(
388            prep.raw_ptr, raw,
389            "oversized sampled realloc must forward old_raw, not the user pointer"
390        );
391    }
392
393    #[test]
394    fn tl_state_init_populates_state() {
395        std::thread::spawn(|| unsafe {
396            assert!(
397                dd_tl_state_get().is_null(),
398                "fresh thread should start without sampler TLS"
399            );
400            dd_tl_state_init();
401            let got = dd_tl_state_get();
402            assert!(!got.is_null(), "init should populate sampler TLS");
403            assert_eq!((*got).sampling_interval, 512 * 1024);
404        })
405        .join()
406        .unwrap();
407    }
408}