1 /*
2 * Copyright (C) 2025 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 //! Functions to interact with BPF through C FFI.
18
19 use anyhow::{ensure, Result};
20 use uprobestats_bpf_bindgen::{bpfPerfEventOpen, pollRingBuf};
21
22 use std::{ffi::c_void, fmt::Debug, mem::size_of};
23
24 mod c_string;
25 use c_string::c_string;
26
27 /// Polls the BPF ring buffer at the passed `map_path`, collecting any values
28 /// emitted within `timeout_ms` into a `Vec<T>`, where `T` is expected to be
29 /// the type written to the ring buffer by a corresponding eBPF program.
30 ///
31 /// # Safety
32 /// - `T` matches the type that is written to the BPF ring buffer at `map_path`.
poll_ring_buf<T: Copy + Debug>(map_path: &str, timeout_ms: i32) -> Result<Vec<T>>33 pub unsafe fn poll_ring_buf<T: Copy + Debug>(map_path: &str, timeout_ms: i32) -> Result<Vec<T>> {
34 let map_path = c_string(map_path)?;
35 let mut data: Vec<T> = Vec::new();
36 let data_ptr = &mut data as *mut _ as *mut c_void;
37 // SAFETY:
38 // - `map_path` is a valid pointer by virtue of coming from a `CString`.
39 // - caller has guaranteed that `T` is the right type, which we use to derive its size.
40 // - `callback` is a valid function pointer defined below.
41 // - `data_ptr` is a valid pointer from the `Vec::new` construction above.
42 // - due to all of the above, `callback` will be called with a valid pointer to a `T` and a
43 // valid pointer to a `Vec<T>`, which is safe to mutate because we have an exclusive
44 // reference to the `Vec`.
45 let result = unsafe {
46 pollRingBuf(map_path.as_ptr(), timeout_ms, size_of::<T>(), Some(callback::<T>), data_ptr)
47 };
48 ensure!(result >= 0, "Failed to poll ring buffer. Error code: {}", result);
49 Ok(data)
50 }
51
52 /// Callback function for `pollRingBuf`.
53 ///
54 /// # Safety
55 /// - `value` must be a valid, non-null pointer to a value of type `T` written to the BPF ring buffer.
56 /// - `cookie` must be a valid, non-null pointer to a `Vec<T>`.
callback<T: Copy + Debug>(value: *const c_void, cookie: *mut c_void)57 unsafe extern "C" fn callback<T: Copy + Debug>(value: *const c_void, cookie: *mut c_void) {
58 let value = value as *const T;
59 // SAFETY: the caller has guaranteed a valid pointer to a `T`, which is `Copy`, so we can get an owned value.
60 let value = unsafe { *value };
61 // SAFETY: the caller has guaranteed a is a valid pointer to a `Vec<T>`.
62 let cookie: &mut Vec<T> = unsafe { &mut *(cookie as *mut Vec<T>) };
63 cookie.push(value);
64 }
65
66 /// Attaches the eBPF program specified at `bpf_program_path`
67 /// to the user space program for process `pid`, located by `filename` and `offset`.
bpf_perf_event_open( filename: String, offset: i32, pid: i32, bpf_program_path: String, ) -> Result<()>68 pub fn bpf_perf_event_open(
69 filename: String,
70 offset: i32,
71 pid: i32,
72 bpf_program_path: String,
73 ) -> Result<()> {
74 let filename = c_string(&filename)?;
75 let bpf_program_path = c_string(&bpf_program_path)?;
76 let res =
77 // SAFETY: `filename` and `bpf_program_path` are valid by virtue of being derived from a `CString`.
78 unsafe { bpfPerfEventOpen(filename.as_ptr(), offset, pid, bpf_program_path.as_ptr()) };
79 ensure!(res == 0, "Failed to attach BPF. Error code: {}", res);
80 Ok(())
81 }
82