summary refs log tree commit diff
path: root/src/main.rs
blob: 9be3a257132b28f7eeb60f0412c54d0b419f3c14 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// #![allow(incomplete_features)]
// #![feature(unsized_locals)]
mod structs;
use crate::structs::{ElfHeader, ElfSectionHeader};
use std::io::Read;

#[repr(C)]
#[derive(Debug)]
struct Elf {
    header: &'static ElfHeader,
    sections: &'static [ElfSectionHeader],
}

impl Elf {
    pub fn new(bytes: &[u8]) -> Elf {
        let header = unsafe { &*(bytes.as_ptr() as *const ElfHeader) };
        assert_eq!(&header.ident.magic, b"\x7fELF");
        
        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 = &sections[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_fmt(format_args!("{}", self.header))
    }
}

fn main() {
    let args: Vec<String> = 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);
}