Skip to main content

libdd_profiling_heap_allocator/
lib.rs

1// Copyright 2025-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3
4//! Rust `GlobalAlloc` wrapper that drives `libdd-profiling-heap-sampler` around each
5//! allocation. Wrap any underlying allocator with [`SampledAllocator`]; on
6//! each alloc/dealloc the sampler's decision/flag/USDT machinery runs
7//! around the inner call.
8//!
9//! `SampledAllocator` is portable across targets, so callers can use it in
10//! a single `#[global_allocator]` static without cfg-gating. The sampling
11//! integration (USDT probes via `libdd-profiling-heap-sampler`) is Linux-only; on
12//! every other target the wrapper compiles to a transparent pass-through
13//! to the inner allocator.
14//!
15//! # Features
16//!
17//! * `live-heap` (off by default) - enables live-heap tracking: sampled allocations are flagged at
18//!   alloc time, and that flag is detected again on free, so a profiler can pair each free back to
19//!   its sample and balance allocs against frees. Off = allocation profiling only.
20//!
21//! # Example
22//!
23//! ```no_run
24//! use libdd_profiling_heap_allocator::{set_default_sampling_distance, SampledAllocator};
25//! use std::alloc::System;
26//!
27//! #[global_allocator]
28//! static ALLOC: SampledAllocator<System> = SampledAllocator::<System>::DEFAULT;
29//!
30//! fn main() {
31//!     // Configure the mean sample distance before the application's
32//!     // allocation-heavy work begins. New threads pick up this value
33//!     // when their sampler state is first initialized.
34//!     set_default_sampling_distance(256 * 1024);
35//!
36//!     // ... application runs ...
37//! }
38//! ```
39
40mod allocator;
41
42pub use allocator::SampledAllocator;
43
44/// Set the default mean sample distance (bytes between samples) for the
45/// heap sampler.
46///
47/// The sampler draws from an exponential distribution around this mean,
48/// so individual gaps vary but average to the configured value. Pass `0`
49/// to revert to the compiled-in default (512 KiB). Values below 64 KiB
50/// are clamped to 64 KiB to avoid excessive overhead.
51///
52/// Call this at the top of `main`, before the application's
53/// allocation-heavy work begins. Threads that have already initialized
54/// their sampler state will not pick up the new value.
55#[cfg(target_os = "linux")]
56pub fn set_default_sampling_distance(distance_bytes: u64) {
57    libdd_profiling_heap_sampler::set_default_sampling_distance(distance_bytes);
58}
59
60/// See the Linux variant above.
61#[cfg(not(target_os = "linux"))]
62pub fn set_default_sampling_distance(_distance_bytes: u64) {}