bpf_rs/
lib.rs

1// DOCS: enable #![warn(missing_docs)]
2// DOCS: enable #![warn(missing_doc_code_examples)]
3//! `bpf-rs` is a safe, lean library for inspecting and querying eBPF objects. A lot of the
4//! design & inspiration stems from [bpftool](https://github.com/libbpf/bpftool) internals and
5//! [libbpf-rs](https://docs.rs/libbpf-rs).
6//!
7//! It is based upon the work of [libbpf-sys](https://github.com/libbpf/libbpf-sys) to safely create
8//! wrappers around [libbpf](https://github.com/libbpf/libbpf).
9//!
10//! This crate is **NOT** meant to help with writing and loading of sophisticated eBPF programs
11//! and maps. For that, we recommend [libbpf-rs](https://docs.rs/libbpf-rs) and
12//! [libbpf-cargo](https://docs.rs/libbpf-cargo).
13//!
14mod helper;
15pub mod insns;
16mod map;
17mod program;
18
19// Re-exports
20pub use helper::BpfHelper;
21pub use libbpf_sys;
22pub use map::MapType;
23pub use program::{ProgramInfo, ProgramLicense, ProgramType};
24
25use std::fmt::Debug;
26use thiserror::Error as ThisError;
27
28/// Propagates error variants from libbpf-sys
29#[derive(ThisError, Debug)]
30pub enum Error {
31    #[error("errno: {0}")]
32    Errno(i32),
33    #[error("error code: {0}")]
34    Code(i32),
35    #[error("unknown: {0}")]
36    Unknown(i32),
37}
38
39// WARNING: Highly coupled to the proc macro bpf_rs_macros::Derive
40trait StaticName {
41    fn name(&self) -> &'static str;
42}
43
44#[cfg(test)]
45mod tests {
46    use super::libbpf_sys as sys;
47    use super::*;
48
49    #[test]
50    fn bpf_helper_iter() {
51        let count = BpfHelper::iter()
52            .map(|helper| {
53                let name = helper.name();
54                assert_ne!(name, "<utf8err>");
55                assert_ne!(name, "<unknown>");
56            })
57            .count();
58
59        assert_eq!(count, usize::try_from(sys::__BPF_FUNC_MAX_ID - 1).unwrap());
60
61        // Because libbpf-sys's bindings generate consts we can't loop (although
62        // maybe we should have this ability?) and verify that u32 values match
63        // up with our helpers. We sample a few here
64        assert_eq!(
65            u32::from(BpfHelper::GetPrandomU32),
66            sys::BPF_FUNC_get_prandom_u32
67        );
68        assert_eq!(
69            u32::from(BpfHelper::TraceVprintk),
70            sys::BPF_FUNC_trace_vprintk
71        );
72        assert_eq!(
73            u32::from(BpfHelper::TcpRawGenSyncookieIpv6),
74            sys::BPF_FUNC_tcp_raw_gen_syncookie_ipv6
75        );
76
77        let invalid_helper = BpfHelper::try_from(sys::__BPF_FUNC_MAX_ID);
78        assert!(invalid_helper.is_err());
79    }
80
81    #[test]
82    fn program_license_ptr() {
83        assert!(!ProgramLicense::GPL.as_ptr().is_null());
84    }
85}