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