libdd-profiling-heap-sampler 1.0.0

Sampling primitives for USDT-based heap profiling.
Documentation
// Copyright 2025-Present Datadog, Inc. https://www.datadoghq.com/
// SPDX-License-Identifier: Apache-2.0

//! Rust bindings for the libdd-profiling-heap-sampler C library.
//!
//! FFI declarations and `#[repr(C)]` struct mirrors are generated by
//! `bindgen` from the public headers under `include/datadog/heap/` at
//! build time; see `build.rs`. All items are re-exported at the crate
//! root.
//!
//! The `static inline __attribute__((always_inline))` fast-path helpers in
//! the headers have no linker symbol, so bindgen's `wrap_static_fns`
//! emits a C shim for each - the shim's body is the static-inline
//! inlined at its one call site. The shim's link-symbol is
//! `<fn>__extern`, but bindgen exposes the Rust fn under the natural C
//! name via `#[link_name]`, so callers write `dd_allocation_requested(…)`
//! the same way they would in C.

// USDT/SystemTap is Linux-only; on every other target the crate is an empty
// rlib. macOS is `unix` too, so we gate on target_os = "linux" specifically.
#[cfg(target_os = "linux")]
#[allow(
    non_camel_case_types,
    non_snake_case,
    non_upper_case_globals,
    dead_code
)]
mod sys {
    include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
}

#[cfg(target_os = "linux")]
pub use sys::*;

/// Runtime ELF self-inspection asserting one USDT note per probe. Opt-in via
/// the `sanity-check` feature (pulls in the `elf`/`anyhow` deps).
#[cfg(all(target_os = "linux", feature = "sanity-check"))]
pub mod usdt_check;

/// Name of the environment variable that toggles heap sampling.
pub const DD_HEAP_SAMPLING_ENABLED: &str = "DD_HEAP_SAMPLING_ENABLED";

/// Set the default mean sample distance (bytes between samples).
///
/// Pass `0` to revert to the compiled-in default (`DD_SAMPLING_INTERVAL_DEFAULT`,
/// 512 KiB). Values below 64 KiB are clamped to 64 KiB to avoid
/// excessive overhead.
#[cfg(target_os = "linux")]
pub fn set_default_sampling_distance(distance_bytes: u64) {
    // SAFETY: dd_set_default_sampling_interval performs a single relaxed atomic
    // store.
    unsafe { sys::dd_set_default_sampling_interval(distance_bytes) }
}

/// Whether heap sampling is enabled for this process. Users of this
/// library can use this to check if they should setup allocation tracking
/// or not.
///
/// Reads [`DD_HEAP_SAMPLING_ENABLED`] once and caches the result: sampling
/// is enabled by default and disabled only when the variable is set to a
/// falsey value (`0`, `false`, `no`, `off`, case-insensitive). Consumers
/// (the GOT interposer, the `GlobalAlloc` wrapper) use this as a
/// short-circuit so that a disabled sampler is as close as possible to not
/// being installed at all.
///
/// The lookup uses `getenv` rather than [`std::env::var`] specifically so it
/// performs no heap allocation so that our consumers don't have to worry about
/// re-entrancy.
#[inline]
pub fn heap_sampling_enabled() -> bool {
    use std::sync::OnceLock;
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(read_heap_sampling_enabled)
}

/// Interpret a raw environment-variable value. `None` (unset) enables
/// sampling; a value equal to `0`/`false`/`no`/`off` (case-insensitive)
/// disables it; anything else enables it. Split out from the `getenv`
/// lookup so the policy is unit-testable without touching process state or
/// the process-wide cache in [`heap_sampling_enabled`].
fn parse_heap_sampling_enabled(value: Option<&[u8]>) -> bool {
    match value {
        None => true,
        Some(bytes) => {
            !(bytes.eq_ignore_ascii_case(b"0")
                || bytes.eq_ignore_ascii_case(b"false")
                || bytes.eq_ignore_ascii_case(b"no")
                || bytes.eq_ignore_ascii_case(b"off"))
        }
    }
}

#[cfg(unix)]
fn read_heap_sampling_enabled() -> bool {
    use core::ffi::{c_char, CStr};

    extern "C" {
        fn getenv(name: *const c_char) -> *mut c_char;
    }

    const NAME: &[u8] = b"DD_HEAP_SAMPLING_ENABLED\0";

    // SAFETY: NAME is a valid NUL-terminated C string; getenv returns either
    // NULL or a pointer to a NUL-terminated string in the process
    // environment, which we only read. No allocation occurs, so this is safe
    // to call from inside a GlobalAlloc hot path.
    unsafe {
        let value = getenv(NAME.as_ptr().cast());
        let bytes = (!value.is_null()).then(|| CStr::from_ptr(value).to_bytes());
        parse_heap_sampling_enabled(bytes)
    }
}

#[cfg(not(unix))]
fn read_heap_sampling_enabled() -> bool {
    // Sampling only exists on Linux; elsewhere there's no environment block to
    // read, so this is moot. Route through the shared policy (None -> enabled)
    // so parse_heap_sampling_enabled isn't dead code on non-unix targets.
    parse_heap_sampling_enabled(None)
}

// Pure-logic tests for the env-var policy; no FFI, safe on every target
// and under miri.
#[cfg(test)]
mod sampling_flag_tests {
    use super::parse_heap_sampling_enabled;

    #[test]
    fn unset_defaults_to_enabled() {
        assert!(parse_heap_sampling_enabled(None));
    }

    #[test]
    fn falsey_values_disable() {
        for v in [
            &b"0"[..],
            b"false",
            b"FALSE",
            b"False",
            b"no",
            b"NO",
            b"off",
            b"Off",
        ] {
            assert!(
                !parse_heap_sampling_enabled(Some(v)),
                "{v:?} should disable"
            );
        }
    }

    #[test]
    fn truthy_and_unrecognized_values_enable() {
        for v in [&b"1"[..], b"true", b"TRUE", b"yes", b"on", b"", b"maybe"] {
            assert!(parse_heap_sampling_enabled(Some(v)), "{v:?} should enable");
        }
    }
}

// Tests exercise the C/FFI sampler primitives directly; miri can't
// execute foreign code, so skip the whole module under miri.
#[cfg(all(test, target_os = "linux", not(miri)))]
mod tests {
    use super::*;
    use core::ffi::c_void;

    #[test]
    fn alloc_req_layout_matches_c() {
        assert_eq!(core::mem::size_of::<dd_alloc_req_t>(), 32);
        assert_eq!(core::mem::align_of::<dd_alloc_req_t>(), 8);
    }

    #[test]
    fn tl_state_layout_matches_c() {
        assert_eq!(core::mem::size_of::<dd_tl_state_t>(), 24);
        assert_eq!(core::mem::align_of::<dd_tl_state_t>(), 8);
    }

    #[test]
    fn requested_initializes_tls_on_first_use() {
        std::thread::spawn(|| unsafe {
            assert!(
                dd_tl_state_get().is_null(),
                "fresh thread should start without sampler TLS"
            );
            let req = dd_allocation_requested(1, 1);
            assert_eq!(req.size, 1);
            assert_eq!(req.weight, 0);
            assert!(
                !dd_tl_state_get().is_null(),
                "request should initialize sampler TLS"
            );
        })
        .join()
        .unwrap();
    }

    #[test]
    fn created_is_passthrough_when_weight_zero() {
        unsafe {
            let fake = 0xdead_beef_usize as *mut c_void;
            let req = dd_alloc_req_t {
                size: 64,
                user_size: 64,
                alignment: 8,
                weight: 0,
            };
            assert_eq!(dd_allocation_created(fake, req), fake);
        }
    }

    // With live-heap tracking compiled out, even a "sampled" allocation
    // (weight > 0) is never flagged: the created pointer is the raw pointer
    // unchanged. The alloc USDT still fires (allocation profiling), but
    // there is no tag/header, so no matching free is expected.
    #[cfg(not(feature = "live-heap"))]
    #[test]
    fn created_does_not_flag_when_live_heap_disabled() {
        unsafe {
            let fake = 0xdead_beef_usize as *mut c_void;
            let req = dd_alloc_req_t {
                size: 64,
                user_size: 64,
                alignment: 8,
                weight: 5,
            };
            assert_eq!(dd_allocation_created(fake, req), fake);
        }
    }

    // With live-heap tracking compiled out, dd_allocation_freed is a
    // straight passthrough: it never inspects the sample-flag header and
    // never fires ddheap:free. Verify this even when the underlying
    // memory happens to contain the magic pattern that *would* trigger
    // the slow path if live-heap were enabled.
    #[cfg(not(feature = "live-heap"))]
    #[test]
    fn freed_is_passthrough_when_live_heap_disabled() {
        const MAGIC: u64 = 0xfab1eddec0dedca7;
        const HEADER_BYTES: usize = 16;

        // Set up a buffer with the magic header so that, if the flag-check
        // were compiled in, it would consider this allocation sampled.
        let mut buf = vec![0u8; 128];
        let base = buf.as_mut_ptr() as usize;
        let user_addr = base + HEADER_BYTES;

        // Stamp magic at ptr - HEADER_BYTES
        buf[0..8].copy_from_slice(&MAGIC.to_ne_bytes());
        // Stamp a plausible offset
        buf[8..16].copy_from_slice(&(HEADER_BYTES as u64).to_ne_bytes());

        let ptr = user_addr as *mut c_void;
        unsafe {
            let freed = dd_allocation_freed(ptr, 64, 8);
            // Without live-heap the pointer is returned unchanged (no
            // flag-check, no raw-pointer recovery).
            assert_eq!(freed.ptr, ptr);
            assert_eq!(freed.size, 64);
        }
    }

    #[test]
    fn zero_sampling_interval_disables_sampling() {
        let mut tl = dd_tl_state_t {
            sampling_interval: 0,
            remaining_bytes: 0,
            remaining_bytes_initialized: true,
            initialized: true,
            reentry_guard: false,
            rng: 1,
        };

        let req = unsafe { dd_allocation_requested_slow(&mut tl, 64, 8) };

        assert_eq!(req.size, 64);
        assert_eq!(req.user_size, 64);
        assert_eq!(req.alignment, 8);
        assert_eq!(req.weight, 0);
        assert!(!tl.reentry_guard);
    }

    #[test]
    fn freed_unsampled_returns_inputs_unchanged() {
        // The C side now reads 8 bytes at ptr-16 looking for DD_MAGIC,
        // so we need a real buffer underneath. Zero contents won't match,
        // so the function returns inputs verbatim.
        let mut buf = vec![0u8; 128];
        let ptr = unsafe { buf.as_mut_ptr().add(16) } as *mut c_void;
        unsafe {
            let freed = dd_allocation_freed(ptr, 64, 8);
            assert_eq!(freed.ptr, ptr);
            assert_eq!(freed.size, 64);
        }
    }

    #[cfg(all(target_arch = "x86_64", feature = "live-heap"))]
    #[test]
    fn sample_flag_check_fast_rejects_invalid_offset() {
        const MAGIC: u64 = 0xfab1eddec0dedca7;
        const HEADER_BYTES: usize = 16;

        let mut buf = vec![0u8; 8192];
        let base = buf.as_mut_ptr() as usize;
        let user_addr = (base + 128 + 4095) & !4095;
        let user_addr = user_addr + 64;
        assert!(user_addr + 64 <= base + buf.len());

        let header = user_addr - HEADER_BYTES;
        let header_idx = header - base;
        buf[header_idx..header_idx + 8].copy_from_slice(&MAGIC.to_ne_bytes());
        // Too small to have been produced by x86_apply().
        buf[header_idx + 8..header_idx + 16].copy_from_slice(&8u64.to_ne_bytes());

        let mut raw = core::ptr::null_mut();
        let sampled = unsafe { dd_sample_flag_check_and_clear(user_addr as *mut c_void, &mut raw) };

        assert!(!sampled);
        assert!(raw.is_null());
        assert_eq!(&buf[header_idx..header_idx + 8], &MAGIC.to_ne_bytes());
    }

    #[cfg(all(target_arch = "x86_64", feature = "live-heap"))]
    #[test]
    fn freed_slow_size_matches_requested_bump_formula() {
        const HEADER_BYTES: usize = 16;

        fn requested_bumped_size(user_size: usize, alignment: usize) -> usize {
            let base = alignment.max(HEADER_BYTES);
            let reserve = 2 * base;
            let bumped = user_size + reserve;
            if alignment > 1 {
                let mask = alignment - 1;
                (bumped + mask) & !mask
            } else {
                bumped
            }
        }

        let user_size = 100;
        let alignment = 16;
        let base = alignment.max(HEADER_BYTES);
        let raw = 0x100000usize as *mut c_void;
        let ptr = (0x100000usize + base) as *mut c_void;

        let freed = unsafe { dd_allocation_freed_slow(ptr, raw, user_size, alignment) };

        assert_eq!(freed.ptr, raw);
        assert_eq!(freed.size, requested_bumped_size(user_size, alignment));
    }

    // When a sampled block is realloc'd to a size so large that reserving
    // room for its header would overflow SIZE_MAX, prepare() must still
    // forward the RAW pointer to the underlying realloc - not the offset
    // user pointer, which is mid-chunk and would corrupt the heap. Drives
    // prepare() directly, so the oversized request is never made.
    #[cfg(all(target_arch = "x86_64", feature = "live-heap"))]
    #[test]
    fn realloc_prepare_oversized_sampled_uses_raw_pointer() {
        let mut buf = vec![0u8; 256];
        let raw = buf.as_mut_ptr() as *mut c_void;

        // Flag the block: stamps the header and returns user = raw + offset.
        let user = unsafe { dd_sample_flag_apply(raw, 16) };
        assert_ne!(
            user, raw,
            "apply should offset the user pointer past the header"
        );

        let prep = unsafe { dd_allocation_realloc_prepare(user, usize::MAX) };
        assert_eq!(
            prep.raw_ptr, raw,
            "oversized sampled realloc must forward old_raw, not the user pointer"
        );
    }

    #[test]
    fn tl_state_init_populates_state() {
        std::thread::spawn(|| unsafe {
            assert!(
                dd_tl_state_get().is_null(),
                "fresh thread should start without sampler TLS"
            );
            dd_tl_state_init();
            let got = dd_tl_state_get();
            assert!(!got.is_null(), "init should populate sampler TLS");
            assert_eq!((*got).sampling_interval, 512 * 1024);
        })
        .join()
        .unwrap();
    }
}