diff --git a/src/formats/elf/output.rs b/src/formats/elf/output.rs index cf7a36b..0eeef36 100644 --- a/src/formats/elf/output.rs +++ b/src/formats/elf/output.rs @@ -1,6 +1,6 @@ use std::path::PathBuf; -use elf_utilities::file::{ELF64Dumper, ELF64}; +use elf_utilities::{file::{ELF64Dumper, ELF64}, section::{Contents64, Section64, Shdr64, build_string_table}}; use crate::{ common::{Output, Section}, @@ -47,7 +47,7 @@ impl<'data> ElfOutput<'data> { } fn populate_sections(&mut self) -> Result { - use elf_utilities::section::{Contents64, Section64, Shdr64}; + let mut names = Vec::new(); for (name, sections) in self.segment_data.iter_mut() { let mut data = Vec::new(); @@ -58,14 +58,26 @@ impl<'data> ElfOutput<'data> { } } + names.push(name); let section = Section64 { name: name.into(), - header: Shdr64::default(), + header: make_section_header(&names, data.len()), contents: Contents64::Raw(data), }; self.file.add_section(section); + } + let name = ".shstrtab"; + names.push(name); + let string_table = build_string_table(&names, true); + let section = Section64 { + name: name.into(), + header: make_section_header(&names, string_table.len()), + contents: Contents64::Raw(string_table), + }; + self.file.add_section(section); + Ok(0) } @@ -146,4 +158,31 @@ fn elf_bin_from_object(other: &ELF64) -> ELF64 { elf.ehdr.e_machine = other.ehdr.e_machine; elf -} \ No newline at end of file +} + +fn make_section_header(names: &Vec<&str>, size: usize) -> Shdr64 { + use elf_utilities::section::Type; + + let mut h = Shdr64::default(); + if let Some(name) = names.last() { + if *name == ".shstrtab" { + h.set_type(Type::StrTab); + } else { + h.set_type(Type::ProgBits); + } + + // section index used for name and section indexing (currently same) + let idx = (names.len() - 1) as u32; + // name index + h.sh_name = idx; + // link index + h.sh_link = idx; + h.sh_size = size as u64; + // TODO + // h.sh_offset = offset; + + h + } else { + panic!("Unexpected nameless section"); + } +}