Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

unsafe xmas_elf::ElfFile::new_from_ptr(ptr: *const u8) constructor #81

Open
krh opened this issue Apr 10, 2023 · 1 comment
Open

unsafe xmas_elf::ElfFile::new_from_ptr(ptr: *const u8) constructor #81

krh opened this issue Apr 10, 2023 · 1 comment

Comments

@krh
Copy link

krh commented Apr 10, 2023

Sometimes they don't give you the length 😢

Parses header and scans program header, section header and sections for largest offset. Creates a slice from raw parts and calls ::new...

@krh
Copy link
Author

krh commented Apr 11, 2023

// xmas_elf wants a slice, not a pointer, so we have to try to figure out how
// big the ELF data is from just the pointer.  We do this by first creating a
// slice for just the Elf64 header size.  From that we can see where the
// section headers end and extend the slice to cover those.  Since ELF doesn't
// guaranetee any ordering of section header vs sections, we scan the section
// headers to see where the last section ends, and if that's past the section
// headers, we further extend the slice and recreate the ELF one last time.
unsafe fn elf_from_ptr<'a>(image: *const c_void) -> Result<xmas_elf::ElfFile<'a>, &'static str> {
    let image = image.cast::<u8>();
    const ELF64_HEADER_SIZE: usize = 64;
    let slice = unsafe { std::slice::from_raw_parts(image, ELF64_HEADER_SIZE) };
    let elf = xmas_elf::ElfFile::new(slice)?;

    let section_header_end = elf.header.pt2.sh_offset() as usize
        + elf.header.pt2.sh_count() as usize * elf.header.pt2.sh_entry_size() as usize;

    let slice = unsafe { std::slice::from_raw_parts(image, section_header_end) };
    let elf = xmas_elf::ElfFile::new(slice)?;

    let last_section_end = elf
        .section_iter()
        .map(|s| s.offset() + s.size())
        .max()
        .ok_or(Err("no sections in ELF"))? as usize;
    if sh_end > end {
        let slice = unsafe { std::slice::from_raw_parts(image, std::cmp::max(end, last_section_end)) };
        xmas_elf::ElfFile::new(slice)
    } else {
        Ok(elf)
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant