From c8a66c643afe2d0a2da55eac537b13a466c242c2 Mon Sep 17 00:00:00 2001 From: tzlil Date: Tue, 21 Mar 2023 12:56:39 +0200 Subject: reading section names --- src/main.rs | 47 ++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 40 insertions(+), 7 deletions(-) (limited to 'src/main.rs') diff --git a/src/main.rs b/src/main.rs index 3033ece..9be3a25 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,10 +1,14 @@ +// #![allow(incomplete_features)] +// #![feature(unsized_locals)] mod structs; -use crate::structs::ElfHeader; +use crate::structs::{ElfHeader, ElfSectionHeader}; +use std::io::Read; #[repr(C)] #[derive(Debug)] struct Elf { header: &'static ElfHeader, + sections: &'static [ElfSectionHeader], } impl Elf { @@ -12,22 +16,51 @@ impl Elf { let header = unsafe { &*(bytes.as_ptr() as *const ElfHeader) }; assert_eq!(&header.ident.magic, b"\x7fELF"); - Elf { - header + let sections = unsafe { + std::slice::from_raw_parts( + bytes.as_ptr().add(header.shoff as usize) as *const ElfSectionHeader, + header.shnum as usize, + ) + }; + + let strtab = §ions[header.shstrndx as usize]; + let strtab_section = unsafe { bytes.as_ptr().add(strtab.offset as usize) }; + + // let names = unsafe { + // std::slice::from_raw_parts( + // strtab_section as *const u8, + // strtab.size as usize, + // ) + // }; + // dbg!(std::str::from_utf8(&names).unwrap()); + for sec in sections { + println!("{:?}", unsafe { std::ffi::CStr::from_ptr( + strtab_section.add(sec.name as usize) as *const i8 + )}); } + // dbg!(sections[5].r#type as u32); + Elf { header, sections } } } // readelf behavior here impl std::fmt::Display for Elf { fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { - formatter.write_str("ELF Header:\n"); + formatter.write_str("ELF Header:\n")?; formatter.write_fmt(format_args!("{}", self.header)) } } fn main() { - let data = include_bytes!("../elf"); - let elf = Elf::new(&data[..]); - println!("{}", elf); + let args: Vec = std::env::args().collect(); + + let buffer = { + let mut f = std::fs::File::open(&args[1]).expect("no file found"); + let metadata = std::fs::metadata(&args[1]).expect("unable to read metadata"); + let mut buffer = vec![0; metadata.len() as usize]; + f.read(&mut buffer).expect("buffer overflow"); + buffer + }; + let elf = Elf::new(&buffer[..]); + // println!("{}", elf); } -- cgit 1.4.1