use std::path::Path;
use std::ptr::null_mut;
use std::ptr::NonNull;
use crate::util;
use crate::util::path_to_cstring;
use crate::AsRawLibbpf;
use crate::Error;
use crate::ErrorExt as _;
use crate::Result;
#[derive(Debug)]
pub struct Linker {
linker: NonNull<libbpf_sys::bpf_linker>,
}
impl Linker {
pub fn new<P>(output: P) -> Result<Self>
where
P: AsRef<Path>,
{
let output = path_to_cstring(output)?;
util::create_bpf_entity_checked(|| {
let opts = null_mut();
unsafe { libbpf_sys::bpf_linker__new(output.as_ptr(), opts) }
})
.map(|linker| Self { linker })
}
pub fn add_file<P>(&mut self, file: P) -> Result<()>
where
P: AsRef<Path>,
{
let file = path_to_cstring(file)?;
let opts = null_mut();
let err =
unsafe { libbpf_sys::bpf_linker__add_file(self.linker.as_ptr(), file.as_ptr(), opts) };
if err != 0 {
Err(Error::from_raw_os_error(err)).context("bpf_linker__add_file failed")
} else {
Ok(())
}
}
pub fn link(&self) -> Result<()> {
let err = unsafe { libbpf_sys::bpf_linker__finalize(self.linker.as_ptr()) };
if err != 0 {
return Err(Error::from_raw_os_error(err)).context("bpf_linker__finalize failed");
}
Ok(())
}
}
impl AsRawLibbpf for Linker {
type LibbpfType = libbpf_sys::bpf_linker;
fn as_libbpf_object(&self) -> NonNull<Self::LibbpfType> {
self.linker
}
}
unsafe impl Send for Linker {}
impl Drop for Linker {
fn drop(&mut self) {
unsafe { libbpf_sys::bpf_linker__free(self.linker.as_ptr()) }
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn linker_is_send() {
fn test<T>()
where
T: Send,
{
}
test::<Linker>();
}
}