Skip to content

Commit 016326e

Browse files
committed
libbpf-cargo: Support linking multiple files
Add support for building a BPF object file from multiple input files, by first compiling each separately and the linking everything together. Signed-off-by: Daniel Müller <deso@posteo.net>
1 parent fac3b87 commit 016326e

File tree

1 file changed

+35
-17
lines changed

1 file changed

+35
-17
lines changed

libbpf-cargo/src/build.rs

Lines changed: 35 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -151,28 +151,36 @@ impl BpfObjBuilder {
151151
f(&compiler_args)
152152
}
153153

154-
/// Build a BPF object file.
155-
pub fn build(&mut self, src: &Path, dst: &Path) -> Result<CompilationOutput> {
154+
/// Build a BPF object file from a set of input files.
155+
pub fn build_many<S, P>(&mut self, srcs: S, dst: &Path) -> Result<Vec<CompilationOutput>>
156+
where
157+
S: IntoIterator<Item = P>,
158+
P: AsRef<Path>,
159+
{
156160
let obj_dir = tempdir().context("failed to create temporary directory")?;
157161
let mut linker = libbpf_rs::Linker::new(dst)
158162
.context("failed to instantiate libbpf object file linker")?;
159163

160164
let output = self.with_compiler_args(|compiler_args| {
161-
let tmp_dst = obj_dir.path().join(src.file_name().with_context(|| {
162-
format!(
163-
"input path `{}` does not have a proper file name",
164-
src.display()
165-
)
166-
})?);
167-
168-
let output = Self::compile_single(src, &tmp_dst, &self.compiler, compiler_args)
169-
.with_context(|| format!("failed to compile `{}`", src.display()))?;
170-
171-
linker
172-
.add_file(tmp_dst)
173-
.context("failed to add object file to BPF linker")?;
174-
175-
Ok(output)
165+
srcs.into_iter()
166+
.map(|src| {
167+
let src = src.as_ref();
168+
let tmp_dst = obj_dir.path().join(src.file_name().with_context(|| {
169+
format!(
170+
"input path `{}` does not have a proper file name",
171+
src.display()
172+
)
173+
})?);
174+
175+
let output = Self::compile_single(src, &tmp_dst, &self.compiler, compiler_args)
176+
.with_context(|| format!("failed to compile `{}`", src.display()))?;
177+
178+
linker
179+
.add_file(tmp_dst)
180+
.context("failed to add object file to BPF linker")?;
181+
Ok(output)
182+
})
183+
.collect::<Result<_, _>>()
176184
})?;
177185

178186
// The resulting object file may contain DWARF information
@@ -185,6 +193,16 @@ impl BpfObjBuilder {
185193

186194
Ok(output)
187195
}
196+
197+
/// Build a BPF object file.
198+
pub fn build(&mut self, src: &Path, dst: &Path) -> Result<CompilationOutput> {
199+
self.build_many([src], dst).map(|vec| {
200+
// SANITY: We pass in a single file we `build_many` is
201+
// guaranteed to produce as many outputs as input
202+
// files; so there must be one.
203+
vec.into_iter().next().unwrap()
204+
})
205+
}
188206
}
189207

190208
impl Default for BpfObjBuilder {

0 commit comments

Comments
 (0)