0

in one of my rust projects I would like to store an the contents of an ELF file in a structure together with its parsed representation created by the goblin crate:

struct AnalysisFile<'a> {
    filename: String,
    content: Vec<u8>,
    elf_info: Elf<'a>
}

impl AnalysisFile<'_> {
    fn new<'a>(filename: String) -> Option<AnalysisFile<'a>> {
        let buffer = fs::read(filename).ok()?;
        let elf = goblin::elf::Elf::parse(&buffer).ok()?;
        Some(AnalysisFile {filename: filename, content: buffer, elf: elf});
    }
}

Unfortunately, this will not compile:

src/main.rs|36 col 9 error 515| cannot return value referencing local variable `buffer` returns a value referencing data owned by the current function
[...]
src/main.rs|36 col 57 error 505| cannot move out of `buffer` because it is borrowed

After some research, I guess this is because of creating a self-reference inside a struct, which is apparently not allowed in Rust. The Elf struct stores pointer to the buffer and the borrow checker will forbid to move the owning Vec to the AnalysisFile as the borrowed references to buffer could become invalid. However, as far as I see, this is bullshit in this case. A Vec stores the data on the heap and the pointer would not become invalid by moving the Vec, right? It would be acceptable for me, if I would prevent further modifications to Vec that could cause invalidation of the allocated buffers on the heap API wise.

Do you see any nice solution how I can store the contents of the ELF file together with the parsed representation (using goblin) inside the same structure? I would also accept if the solution would need a few lines of unsafe code...

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
flammi88
  • 381
  • 2
  • 14
  • [`ouroboros`](https://docs.rs/ouroboros/latest/ouroboros/attr.self_referencing.html) seems like it'd be pretty good for your use case. – Aplet123 Jul 26 '22 at 20:38
  • An easy way to get around this is to require the caller read the file and pass in the `&'a [u8]` to `new` instead. – PitaJ Jul 26 '22 at 21:09

0 Answers0