use std::path::Path;
use std::ptr::null_mut;
use std::ptr::NonNull;
use crate::util::path_to_cstring;
use crate::util::validate_bpf_ret;
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)?;
let opts = null_mut();
let ptr = unsafe { libbpf_sys::bpf_linker__new(output.as_ptr(), opts) };
let ptr = validate_bpf_ret(ptr).context("failed to attach iterator")?;
let slf = Self { linker: ptr };
Ok(slf)
}
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>();
}
}