bpf_loader_lib/
elf_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 object::ElfFile;
9use ouroboros::self_referencing;
10/// A helper struct to solve the reference problem of ElfFile
11/// This struct contains the binary of the original elf file and the ElfFile struct
12/// With this we don't need to take care of the reference problem anymore
13#[self_referencing]
14pub struct ElfContainer {
15    bin: Vec<u8>,
16    #[borrows(bin)]
17    #[covariant]
18    pub(crate) elf: ElfFile<'this>,
19}
20
21impl ElfContainer {
22    /// Create a container from a ELF binary
23    pub fn new_from_binary(bin: &[u8]) -> Result<Self> {
24        let bin = bin.to_vec();
25        let val = ElfContainerTryBuilder {
26            bin,
27            elf_builder: |vec: &Vec<u8>| {
28                ElfFile::parse(&vec[..]).map_err(|e| anyhow!("Failed to parse elf: {}", e))
29            },
30        }
31        .try_build()?;
32        Ok(val)
33    }
34}