Skip to main content

libbpf_cargo/
lib.rs

1//! libbpf-cargo helps you develop and build eBPF (BPF) programs with standard rust tooling.
2//!
3//! libbpf-cargo supports two interfaces:
4//! * [`SkeletonBuilder`] API, for use with [build scripts](https://doc.rust-lang.org/cargo/reference/build-scripts.html)
5//! * `cargo-libbpf` cargo subcommand, for use with `cargo`
6//!
7//! The **build script interface is recommended** over the cargo subcommand interface because:
8//! * once set up, you cannot forget to update the generated skeletons if your source changes
9//! * build scripts are standard practice for projects that include codegen
10//! * newcomers to your project can `cargo build` and it will "just work"
11//!
12//! The following sections in this document describe the `cargo-libbpf` plugin. See the API
13//! reference for documentation on the build script interface.
14//!
15//! # Configuration
16//!
17//! cargo-libbpf consumes the following Cargo.toml configuration options:
18//!
19//! ```text
20//! [package.metadata.libbpf]
21//! prog_dir = "src/other_bpf_dir"  # default: <manifest_directory>/src/bpf
22//! target_dir = "other_target_dir" # default: <target_dir>/bpf
23//! ```
24//!
25//! * `prog_dir`: path relative to package Cargo.toml to search for bpf progs
26//! * `target_dir`: path relative to workspace target directory to place compiled bpf progs
27//!
28//! # Subcommands
29//!
30//! ## build
31//!
32//! `cargo libbpf build` compiles `<NAME>.bpf.c` C files into corresponding `<NAME>.bpf.o` ELF
33//! object files. Each object file may contain one or more BPF programs, maps, and associated
34//! metadata. The object file may then be handed over to `libbpf-rs` for loading and interaction.
35//!
36//! cargo-libbpf-build enforces a few conventions:
37//!
38//! * source file names must be in the `<NAME>.bpf.c` format
39//! * object file names will be generated in `<NAME>.bpf.o` format
40//! * there may not be any two identical `<NAME>.bpf.c` file names in any two projects in a cargo
41//!   workspace
42//!
43//! ## gen
44//!
45//! `cargo libbpf gen` generates a skeleton module for each BPF object file in the project.  Each
46//! `<NAME>.bpf.o` object file will have its own module. One `mod.rs` file is also generated. All
47//! output files are placed into `package.metadata.libbpf.prog_dir`.
48//!
49//! Be careful to run cargo-libbpf-build before running cargo-libbpf-gen. cargo-libbpf-gen reads
50//! object files from `package.metadata.libbpf.target_dir`.
51//!
52//! ## make
53//!
54//! `cargo libbpf make` sequentially runs cargo-libbpf-build, cargo-libbpf-gen, and `cargo
55//! build`. This is a convenience command so you don't forget any steps. Alternatively, you could
56//! write a Makefile for your project.
57
58use std::env;
59use std::ffi::OsStr;
60use std::ffi::OsString;
61use std::path::Path;
62use std::path::PathBuf;
63
64use anyhow::anyhow;
65use anyhow::Context as _;
66use anyhow::Result;
67
68use tempfile::tempdir;
69use tempfile::TempDir;
70
71mod build;
72mod r#gen;
73mod make;
74mod metadata;
75pub mod util;
76
77#[cfg(test)]
78mod test;
79
80use build::BpfObjBuilder;
81
82
83/// `SkeletonBuilder` builds and generates a single skeleton.
84///
85/// This type is typically used from within a build scripts.
86///
87/// # Examples
88///
89/// ```no_run
90/// use libbpf_cargo::SkeletonBuilder;
91///
92/// SkeletonBuilder::new()
93///     .source("myobject.bpf.c")
94///     .clang("/opt/clang/clang")
95///     .build_and_generate("/output/path")
96///     .unwrap();
97/// ```
98#[derive(Debug)]
99pub struct SkeletonBuilder {
100    source: Option<PathBuf>,
101    obj: Option<PathBuf>,
102    clang: Option<PathBuf>,
103    clang_args: Vec<OsString>,
104    rustfmt: PathBuf,
105    dir: Option<TempDir>,
106    reference_obj: bool,
107}
108
109impl Default for SkeletonBuilder {
110    fn default() -> Self {
111        Self::new()
112    }
113}
114
115impl SkeletonBuilder {
116    /// Create a new [`SkeletonBuilder`].
117    pub fn new() -> Self {
118        Self {
119            source: None,
120            obj: None,
121            clang: None,
122            clang_args: Vec::new(),
123            rustfmt: "rustfmt".into(),
124            dir: None,
125            reference_obj: false,
126        }
127    }
128
129    /// Point the [`SkeletonBuilder`] to a source file for compilation
130    ///
131    /// Default is None
132    pub fn source<P: AsRef<Path>>(&mut self, source: P) -> &mut Self {
133        self.source = Some(source.as_ref().to_path_buf());
134        self
135    }
136
137    /// Point the [`SkeletonBuilder`] to an object file for generation
138    ///
139    /// Default is None
140    pub fn obj<P: AsRef<Path>>(&mut self, obj: P) -> &mut Self {
141        self.obj = Some(obj.as_ref().to_path_buf());
142        self
143    }
144
145    /// Specify which `clang` binary to use
146    ///
147    /// Default searches `$PATH` for `clang`
148    pub fn clang<P: AsRef<Path>>(&mut self, clang: P) -> &mut Self {
149        self.clang = Some(clang.as_ref().to_path_buf());
150        self
151    }
152
153    /// Pass additional arguments to `clang` when building BPF object file
154    ///
155    /// # Examples
156    ///
157    /// ```no_run
158    /// use libbpf_cargo::SkeletonBuilder;
159    ///
160    /// SkeletonBuilder::new()
161    ///     .source("myobject.bpf.c")
162    ///     .clang_args([
163    ///         "-DMACRO=value",
164    ///         "-I/some/include/dir",
165    ///     ])
166    ///     .build_and_generate("/output/path")
167    ///     .unwrap();
168    /// ```
169    pub fn clang_args<A, S>(&mut self, args: A) -> &mut Self
170    where
171        A: IntoIterator<Item = S>,
172        S: AsRef<OsStr>,
173    {
174        self.clang_args = args
175            .into_iter()
176            .map(|arg| arg.as_ref().to_os_string())
177            .collect();
178        self
179    }
180
181    /// Specify which `rustfmt` binary to use
182    ///
183    /// Default searches `$PATH` for `rustfmt`
184    pub fn rustfmt<P: AsRef<Path>>(&mut self, rustfmt: P) -> &mut Self {
185        self.rustfmt = rustfmt.as_ref().to_path_buf();
186        self
187    }
188
189    /// Reference the object file via `include_bytes!` instead of inlining
190    /// the raw bytes in the generated skeleton.
191    ///
192    /// When enabled, the generated skeleton uses `include_bytes!` to
193    /// reference the compiled BPF object file by path. This dramatically
194    /// reduces memory usage and build times for large object files, but
195    /// means the skeleton is no longer self-contained — the object file
196    /// must be present at its original path when rustc compiles the
197    /// skeleton.
198    ///
199    /// When no explicit [`obj`](Self::obj) path is set, the object file
200    /// is placed in `OUT_DIR` so that it persists for rustc. If `OUT_DIR`
201    /// is not set (e.g. outside a build script), an explicit `obj` path
202    /// must be provided.
203    ///
204    /// Default is `false` (inline bytes, self-contained skeleton).
205    pub fn reference_obj(&mut self, reference: bool) -> &mut Self {
206        self.reference_obj = reference;
207        self
208    }
209
210    /// Build BPF programs and generate the skeleton at path `output`
211    ///
212    /// # Notes
213    /// When used from a build script, you may be interested in
214    /// surfacing compiler warnings as part of the build. Please refer
215    /// to [`util::CargoWarningFormatter`] and its documentation for how
216    /// to go about that.
217    pub fn build_and_generate<P: AsRef<Path>>(&mut self, output: P) -> Result<()> {
218        self.build()?;
219        self.generate(output)?;
220
221        Ok(())
222    }
223
224    /// Build BPF programs without generating a skeleton.
225    ///
226    /// [`SkeletonBuilder::source`] must be set for this to succeed.
227    ///
228    /// # Notes
229    /// When used from a build script, you may be interested in
230    /// surfacing compiler warnings as part of the build. Please refer
231    /// to [`util::CargoWarningFormatter`] and its documentation for how
232    /// to go about that.
233    pub fn build(&mut self) -> Result<()> {
234        let source = self
235            .source
236            .as_ref()
237            .ok_or_else(|| anyhow!("No source file provided"))?;
238
239        let filename = source
240            .file_name()
241            .ok_or_else(|| anyhow!("Missing file name"))?
242            .to_str()
243            .ok_or_else(|| anyhow!("Invalid unicode in file name"))?;
244
245        if !filename.ends_with(".bpf.c") {
246            return Err(anyhow!(
247                "Source `{}` does not have .bpf.c suffix",
248                source.display()
249            ));
250        }
251
252        if self.obj.is_none() {
253            let name = filename.split('.').next().unwrap();
254            if self.reference_obj {
255                // Place in OUT_DIR so the .o file persists after the build
256                // script exits and is available when rustc processes
257                // include_bytes! in the generated skeleton.
258                let out_dir = env::var("OUT_DIR")
259                    .context("reference_obj requires OUT_DIR or an explicit obj path")?;
260                // Hash the source path to avoid collisions when
261                // multiple sources share the same name prefix.
262                let hash = {
263                    use std::collections::hash_map::DefaultHasher;
264                    use std::hash::Hash;
265                    use std::hash::Hasher;
266                    let mut h = DefaultHasher::new();
267                    source.hash(&mut h);
268                    h.finish()
269                };
270                let objfile = PathBuf::from(out_dir).join(format!("{name}_{hash:016x}.o"));
271                self.obj = Some(objfile);
272            } else {
273                let dir = tempdir().context("failed to create temporary directory")?;
274                let objfile = dir.path().join(format!("{name}.o"));
275                self.obj = Some(objfile);
276                // Hold onto tempdir so that it doesn't get deleted early
277                self.dir = Some(dir);
278            }
279        }
280
281        let mut builder = BpfObjBuilder::default();
282        if let Some(clang) = &self.clang {
283            builder.compiler(clang);
284        }
285        builder.compiler_args(&self.clang_args);
286
287        // SANITY: Unwrap is safe here since we guarantee that obj.is_some() above.
288        builder
289            .build(source, self.obj.as_ref().unwrap())
290            .with_context(|| format!("failed to build `{}`", source.display()))
291    }
292
293    /// Generate a skeleton at path `output` without building BPF programs.
294    ///
295    /// [`SkeletonBuilder::obj`] must be set for this to succeed.
296    pub fn generate<P: AsRef<Path>>(&mut self, output: P) -> Result<()> {
297        let objfile = self.obj.as_ref().ok_or_else(|| anyhow!("No object file"))?;
298
299        r#gen::gen_single(
300            objfile,
301            r#gen::OutputDest::File(output.as_ref()),
302            Some(&self.rustfmt),
303            self.reference_obj,
304        )
305        .with_context(|| format!("failed to generate `{}`", objfile.display()))?;
306
307        Ok(())
308    }
309}
310
311
312/// Implementation details shared with the binary.
313///
314/// NOT PART OF PUBLIC API SURFACE!
315#[doc(hidden)]
316pub mod __private {
317    pub mod build {
318        pub use crate::build::build_project;
319    }
320    pub mod r#gen {
321        pub use crate::r#gen::generate;
322    }
323    pub mod make {
324        pub use crate::make::make;
325    }
326}