Add section header name parser

This commit is contained in:
mii
2021-11-29 20:11:53 +09:00
parent 327e8d303b
commit ab46c154ef
3 changed files with 23 additions and 7 deletions

View File

@ -1,6 +1,6 @@
use nom::{IResult, bytes::complete::{tag, take}, multi::count, number::complete::{le_u16, le_u32, le_u64}}; use nom::{combinator::not, IResult, bytes::complete::{tag, take, take_while}, character::{is_alphabetic, is_alphanumeric}, multi::count, number::complete::{le_u16, le_u32, le_u64}};
use crate::elf_struct::{Elf, ElfHeader, ProgramHeader, SectionHeader}; use crate::elf_struct::{Elf, ElfHeader, ProgramHeader, SectionHeader, Section};
pub struct ElfParser { pub struct ElfParser {
pub file: Vec<u8> pub file: Vec<u8>
@ -23,13 +23,28 @@ impl ElfParser {
&self.file[elf_header.section_header_offset as usize..] &self.file[elf_header.section_header_offset as usize..]
)?; )?;
let section_names_offset = section_headers[elf_header.section_header_name_index as usize].offset;
let section_names_bytes = &self.file[section_names_offset as usize..];
let sections = section_headers.into_iter().map(|header| Section {
name: String::from_utf8(ElfParser::take_alphabetic(&section_names_bytes[header.name as usize..]).unwrap().1.to_vec()).unwrap(),
header
}).collect::<Vec<Section>>();
Ok((input, Elf { Ok((input, Elf {
header: elf_header, header: elf_header,
program_headers, program_headers,
section_headers sections
})) }))
} }
fn take_alphabetic(input: &[u8]) -> IResult<&[u8], &[u8]> {
Ok(take_while(ElfParser::is_not_end)(input)?)
}
// 17
fn is_not_end(input: u8) -> bool {
input != b'\x00'
}
pub fn parse_section_headers(num: usize) -> impl Fn(&[u8]) -> IResult<&[u8], Vec<SectionHeader>> { pub fn parse_section_headers(num: usize) -> impl Fn(&[u8]) -> IResult<&[u8], Vec<SectionHeader>> {
move |raw: &[u8]| count(ElfParser::parse_section_header, num)(raw) move |raw: &[u8]| count(ElfParser::parse_section_header, num)(raw)
} }

View File

@ -2,12 +2,13 @@
pub struct Elf { pub struct Elf {
pub header: ElfHeader, pub header: ElfHeader,
pub program_headers: Vec<ProgramHeader>, pub program_headers: Vec<ProgramHeader>,
pub section_headers: Vec<SectionHeader> pub sections: Vec<Section>
} }
#[derive(Debug)]
pub struct Section { pub struct Section {
pub name: String, pub name: String,
pub section_header: SectionHeader pub header: SectionHeader
} }
#[derive(Debug)] #[derive(Debug)]

View File

@ -17,8 +17,8 @@ fn main() {
println!("{:?}", program_header); println!("{:?}", program_header);
} }
for section_header in elf.section_headers { for section in elf.sections {
println!("{:?}", section_header); println!("{:?}", section);
} }
}, },
Err(_) => {} Err(_) => {}