m4b / goblin

An impish, cross-platform binary parsing crate, written in Rust
MIT License
1.17k stars 156 forks source link

elf: Add convenient functions for symbol write #387

Closed tiann closed 5 months ago

tiann commented 6 months ago

Here is an example of modifying elf:

use goblin::elf::{section_header, sym::Sym, Elf};
use scroll::{ctx::SizeWith, Pwrite};

use anyhow::Result;
use std::fs;

fn main() -> Result<()> {
    let path = "my.elf";
    let mut buffer = fs::read(path)?;
    let elf = Elf::parse(&buffer)?;

    let ctx = elf.syms.ctx().clone();
    for (index, mut sym) in elf.syms.iter().enumerate() {
        let Some(name) = elf.strtab.get_at(sym.st_name) else {
            continue;
        };

        if name == "my_symbol" {
            let offset = elf.syms.offset() + index * Sym::size_with(elf.syms.ctx());
            println!("name: {}, offset: {}", name, offset);
            sym.st_shndx = section_header::SHN_ABS as usize;
            sym.st_value = 0xeaeaeaea;
            buffer.pwrite_with(sym, offset, ctx)?;
            break;
        }
    }

    Ok(())
}

https://github.com/m4b/goblin/issues/325#issuecomment-1288407913 shows that we can modify elf, but we can't get the underlying offset and the symbol size.

Although we can iterate the section header and find the offset, it is not so convenient, this PR exposes some useful field to make it easier.

m4b commented 5 months ago

note: non-breaking, added pub api

m4b commented 2 months ago

released in 0.8.1