libdd-profiling-heap-sampler 1.1.3

Sampling primitives for USDT-based heap profiling.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// 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) }
}

/// Returns true when an external profiler is currently attached to the
/// `ddheap:alloc` USDT in this object file.
///
/// This is a point-in-time read of the alloc probe's USDT semaphore. A profiler
/// can attach or detach immediately after this returns. Use it as a
/// diagnostic/readiness signal, not as a synchronization primitive.
#[cfg(target_os = "linux")]
#[inline]
pub fn is_profiler_attached() -> bool {
    // SAFETY: dd_heap_profiler_attached performs a single semaphore read and
    // has no preconditions.
    unsafe { sys::dd_heap_profiler_attached() }
}

/// Non-Linux builds do not expose USDT heap probes.
#[cfg(not(target_os = "linux"))]
#[inline]
pub fn is_profiler_attached() -> bool {
    false
}

/// 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::{CStr, c_char};

    unsafe 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_skips_tls_init_when_no_profiler_attached() {
        std::thread::spawn(|| unsafe {
            assert!(dd_tl_state_get().is_null());
            let req = dd_allocation_requested(1, 1);
            assert_eq!(req.size, 1);
            assert_eq!(req.weight, 0);
            // Semaphore is inactive (no profiler), so TLS is never touched.
            assert!(dd_tl_state_get().is_null());
        })
        .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();
    }
}