heapdump/
bindings.rs

1// Copyright 2025 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// This crate provides Rust bindings for the Heapdump instrumentation API.
6
7use std::ffi::{CStr, c_char};
8use zx::sys::zx_handle_t;
9
10// From heapdump/bind.h
11unsafe extern "C" {
12    fn heapdump_bind_with_channel(registry_channel: zx_handle_t);
13    fn heapdump_bind_with_fdio();
14}
15
16// From heapdump/snapshot.h
17unsafe extern "C" {
18    fn heapdump_take_named_snapshot(snapshot_name: *const c_char);
19}
20
21// From heapdump/stats.h
22#[derive(Clone, Copy, Default)]
23#[repr(C)]
24pub struct GlobalStats {
25    pub total_allocated_bytes: u64,
26    pub total_deallocated_bytes: u64,
27}
28#[derive(Clone, Copy, Default)]
29#[repr(C)]
30pub struct ThreadLocalStats {
31    pub total_allocated_bytes: u64,
32    pub total_deallocated_bytes: u64,
33}
34unsafe extern "C" {
35    fn heapdump_get_stats(global: *mut GlobalStats, local: *mut ThreadLocalStats);
36}
37
38/// Binds the current process to the provided process registry.
39///
40/// Call either this function or `bind_with_fdio` from the process' main function.
41///
42/// See also //src/performance/memory/heapdump/instrumentation/include/heapdump/bind.h
43pub fn bind_with_channel(registry_channel: zx::Channel) {
44    // SAFETY: FFI call that takes ownership of the given handle.
45    unsafe {
46        heapdump_bind_with_channel(registry_channel.into_raw());
47    }
48}
49
50/// Binds the current process to the process registry, using `fdio_service_connect` to locate it.
51///
52/// Call either this function or `bind_with_channel` from the process' main function.
53///
54/// See also //src/performance/memory/heapdump/instrumentation/include/heapdump/bind.h
55pub fn bind_with_fdio() {
56    // SAFETY: FFI call without arguments.
57    unsafe {
58        heapdump_bind_with_fdio();
59    }
60}
61
62/// Publishes a named snapshot of all the current live allocations.
63///
64/// See also //src/performance/memory/heapdump/instrumentation/include/heapdump/snapshot.h
65pub fn take_named_snapshot(snapshot_name: &CStr) {
66    // SAFETY: FFI call that takes a NUL-terminated string.
67    unsafe {
68        heapdump_take_named_snapshot(snapshot_name.as_ptr());
69    }
70}
71
72/// Obtains stats about past allocations.
73///
74/// See also //src/performance/memory/heapdump/instrumentation/include/heapdump/stats.h
75pub fn get_stats() -> (GlobalStats, ThreadLocalStats) {
76    let mut global = GlobalStats::default();
77    let mut local = ThreadLocalStats::default();
78
79    // SAFETY: FFI call that writes into the provided structs, that we just allocated on the stack.
80    unsafe {
81        heapdump_get_stats(&mut global, &mut local);
82    }
83
84    (global, local)
85}