aya: loader: take BTF info as reference

Allows sharing the same BTF info across many loaders
pull/66/head
Alessandro Decina 3 years ago
parent 090efc863d
commit 5f8f18e3a1

@ -76,13 +76,13 @@ impl Default for PinningType {
} }
#[derive(Default, Debug)] #[derive(Default, Debug)]
pub struct BpfLoader { pub struct BpfLoader<'a> {
btf: Option<Btf>, btf: Option<&'a Btf>,
map_pin_path: Option<PathBuf>, map_pin_path: Option<PathBuf>,
} }
impl BpfLoader { impl<'a> BpfLoader<'a> {
pub fn new() -> BpfLoader { pub fn new() -> BpfLoader<'a> {
BpfLoader { BpfLoader {
btf: None, btf: None,
map_pin_path: None, map_pin_path: None,
@ -90,13 +90,13 @@ impl BpfLoader {
} }
// Set the target BTF // Set the target BTF
pub fn btf(&mut self, btf: Btf) -> &mut BpfLoader { pub fn btf(&mut self, btf: Option<&'a Btf>) -> &mut BpfLoader<'a> {
self.btf = Some(btf); self.btf = btf;
self self
} }
// Set the map pin path // Set the map pin path
pub fn map_pin_path<P: AsRef<Path>>(&mut self, path: P) -> &mut BpfLoader { pub fn map_pin_path<P: AsRef<Path>>(&mut self, path: P) -> &mut BpfLoader<'a> {
self.map_pin_path = Some(path.as_ref().to_owned()); self.map_pin_path = Some(path.as_ref().to_owned());
self self
} }
@ -135,9 +135,9 @@ impl BpfLoader {
/// ///
/// let data = fs::read("file.o").unwrap(); /// let data = fs::read("file.o").unwrap();
/// // load the BTF data from /sys/kernel/btf/vmlinux /// // load the BTF data from /sys/kernel/btf/vmlinux
/// let bpf = BpfLoader::new()
/// let target_btf = Btf::from_sys_fs().unwrap(); /// .btf(Btf::from_sys_fs().ok().as_ref())
/// let bpf = BpfLoader::new().btf(target_btf).load(&data); /// .load(&data);
/// # Ok::<(), aya::BpfError>(()) /// # Ok::<(), aya::BpfError>(())
/// ``` /// ```
pub fn load(&mut self, data: &[u8]) -> Result<Bpf, BpfError> { pub fn load(&mut self, data: &[u8]) -> Result<Bpf, BpfError> {
@ -293,12 +293,9 @@ impl Bpf {
/// # Ok::<(), aya::BpfError>(()) /// # Ok::<(), aya::BpfError>(())
/// ``` /// ```
pub fn load_file<P: AsRef<Path>>(path: P) -> Result<Bpf, BpfError> { pub fn load_file<P: AsRef<Path>>(path: P) -> Result<Bpf, BpfError> {
let mut loader = BpfLoader::new(); BpfLoader::new()
let path = path.as_ref(); .btf(Btf::from_sys_fs().ok().as_ref())
if let Ok(btf) = Btf::from_sys_fs() { .load_file(path)
loader.btf(btf);
};
loader.load_file(path)
} }
/// Load eBPF bytecode. /// Load eBPF bytecode.
@ -320,11 +317,9 @@ impl Bpf {
/// # Ok::<(), aya::BpfError>(()) /// # Ok::<(), aya::BpfError>(())
/// ``` /// ```
pub fn load(data: &[u8]) -> Result<Bpf, BpfError> { pub fn load(data: &[u8]) -> Result<Bpf, BpfError> {
let mut loader = BpfLoader::new(); BpfLoader::new()
if let Ok(btf) = Btf::from_sys_fs() { .btf(Btf::from_sys_fs().ok().as_ref())
loader.btf(btf); .load(data)
};
loader.load(data)
} }
/// Returns a reference to the map with the given name. /// Returns a reference to the map with the given name.

Loading…
Cancel
Save