bpf_loader_lib/
btf_container.rs

1//!  SPDX-License-Identifier: MIT
2//!
3//! Copyright (c) 2023, eunomia-bpf
4//! All rights reserved.
5//!
6
7use anyhow::{anyhow, Result};
8use btf::types::Btf;
9use ouroboros::self_referencing;
10
11use crate::elf_container::ElfContainer;
12/// A helper struct to solve the reference problem of btf::types::Btf
13/// This struct contains the binary of the original elf file, the ElfFile struct and Btf struct.
14/// With this we don't need to take care of the reference problem anymore
15#[self_referencing]
16pub struct BtfContainer {
17    pub(crate) elf_container: ElfContainer,
18    #[borrows(elf_container)]
19    #[covariant]
20    pub(crate) btf: Btf<'this>,
21}
22
23impl BtfContainer {
24    /// Create a btf container from a ELF binary
25    pub fn new_from_binary(bin: &[u8]) -> Result<Self> {
26        let elf = ElfContainer::new_from_binary(bin)?;
27        let val = BtfContainerTryBuilder {
28            elf_container: elf,
29            btf_builder: |elf: &ElfContainer| {
30                Btf::load(elf.borrow_elf()).map_err(|e| anyhow!("Failed to build btf: {}", e))
31            },
32        }
33        .try_build()?;
34        Ok(val)
35    }
36}