Skip to content

Commit 07231df

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 <[email protected]>
1 parent 2522072 commit 07231df

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
@@ -153,28 +153,36 @@ impl BpfObjBuilder {
153153
f(&compiler_args)
154154
}
155155

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

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

180188
// The resulting object file may contain DWARF information
@@ -187,6 +195,16 @@ impl BpfObjBuilder {
187195

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

192210
impl Default for BpfObjBuilder {

0 commit comments

Comments
 (0)