| // Copyright 2026 The Fuchsia Authors | |
| // | |
| // Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 | |
| // <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT | |
| // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. | |
| // This file may not be copied, modified, or distributed except according to | |
| // those terms. | |
| //! Safe, zero-dependency ELF64 little-endian parser for `EM_X86_64` and | |
| //! `EM_AARCH64` objects (`ET_REL`) and linked images (`ET_EXEC` / `ET_DYN`). | |
| use std::fmt; | |
| use serde::Serialize; | |
| // ELF identification and header constants. | |
| const ELF_MAGIC: [u8; 4] = [0x7f, b'E', b'L', b'F']; | |
| const ELFCLASS64: u8 = 2; | |
| const ELFDATA2LSB: u8 = 1; | |
| const EV_CURRENT: u8 = 1; | |
| const ELF64_EHDR_SIZE: u16 = 64; | |
| const ELF64_PHDR_SIZE: u16 = 56; | |
| const ELF64_SHDR_SIZE: u16 = 64; | |
| const ELF64_SYM_SIZE: usize = 24; | |
| const ELF64_RELA_SIZE: usize = 24; | |
| const ELF64_REL_SIZE: usize = 16; | |
| const ELF64_DYN_SIZE: usize = 16; | |
| const PN_XNUM: u16 = 0xffff; | |
| pub const SHN_XINDEX: u16 = 0xffff; | |
| pub const ET_REL: u16 = 1; | |
| pub const ET_EXEC: u16 = 2; | |
| pub const ET_DYN: u16 = 3; | |
| pub const EM_X86_64: u16 = 62; | |
| pub const EM_AARCH64: u16 = 183; | |
| // Program header types and flags. | |
| pub const PT_LOAD: u32 = 1; | |
| pub const PT_DYNAMIC: u32 = 2; | |
| pub const PT_GNU_STACK: u32 = 0x6474_e551; | |
| pub const PT_GNU_RELRO: u32 = 0x6474_e552; | |
| pub const PT_GNU_PROPERTY: u32 = 0x6474_e553; | |
| pub const PF_X: u32 = 1; | |
| pub const PF_W: u32 = 2; | |
| pub const PF_R: u32 = 4; | |
| // Section header types and flags. | |
| pub const SHT_PROGBITS: u32 = 1; | |
| pub const SHT_SYMTAB: u32 = 2; | |
| pub const SHT_STRTAB: u32 = 3; | |
| pub const SHT_RELA: u32 = 4; | |
| pub const SHT_NOTE: u32 = 7; | |
| pub const SHT_REL: u32 = 9; | |
| pub const SHT_DYNSYM: u32 = 11; | |
| pub const SHT_SYMTAB_SHNDX: u32 = 18; | |
| pub const SHT_RELR: u32 = 19; | |
| pub const SHT_CREL: u32 = 0x4000_0014; | |
| pub const SHT_LLVM_LTO: u32 = 0x6fff_4c0c; | |
| pub const SHF_WRITE: u64 = 0x1; | |
| pub const SHF_ALLOC: u64 = 0x2; | |
| pub const SHF_EXECINSTR: u64 = 0x4; | |
| pub const SHF_MERGE: u64 = 0x10; | |
| pub const SHF_STRINGS: u64 = 0x20; | |
| pub const SHF_COMPRESSED: u64 = 0x800; | |
| // Special section indices and symbol types. | |
| pub const SHN_UNDEF: u32 = 0; | |
| pub const SHN_LORESERVE: u32 = 0xff00; | |
| pub const STT_NOTYPE: u8 = 0; | |
| pub const STT_FUNC: u8 = 2; | |
| pub const STT_SECTION: u8 = 3; | |
| pub const STT_FILE: u8 = 4; | |
| pub const STT_GNU_IFUNC: u8 = 10; | |
| pub const STB_LOCAL: u8 = 0; | |
| pub const STV_INTERNAL: u8 = 1; | |
| pub const STV_HIDDEN: u8 = 2; | |
| // Dynamic table tags (`Elf64_Dyn.d_tag`) and flags. | |
| const DT_NULL: i64 = 0; | |
| const DT_PLTRELSZ: i64 = 2; | |
| const DT_PLTGOT: i64 = 3; | |
| const DT_HASH: i64 = 4; | |
| const DT_STRTAB: i64 = 5; | |
| const DT_SYMTAB: i64 = 6; | |
| const DT_RELA: i64 = 7; | |
| const DT_RELASZ: i64 = 8; | |
| const DT_RELAENT: i64 = 9; | |
| const DT_STRSZ: i64 = 10; | |
| const DT_SYMENT: i64 = 11; | |
| const DT_REL: i64 = 17; | |
| const DT_RELSZ: i64 = 18; | |
| const DT_RELENT: i64 = 19; | |
| const DT_PLTREL: i64 = 20; | |
| const DT_TEXTREL: i64 = 22; | |
| const DT_JMPREL: i64 = 23; | |
| const DT_BIND_NOW: i64 = 24; | |
| const DT_FLAGS: i64 = 30; | |
| const DT_RELRSZ: i64 = 35; | |
| const DT_RELR: i64 = 36; | |
| const DT_RELRENT: i64 = 37; | |
| const DT_ANDROID_REL: i64 = 0x6000_000f; | |
| const DT_ANDROID_RELSZ: i64 = 0x6000_0010; | |
| const DT_ANDROID_RELA: i64 = 0x6000_0011; | |
| const DT_ANDROID_RELASZ: i64 = 0x6000_0012; | |
| const DT_ANDROID_RELR: i64 = 0x6fff_e000; | |
| const DT_ANDROID_RELRSZ: i64 = 0x6fff_e001; | |
| const DT_ANDROID_RELRENT: i64 = 0x6fff_e003; | |
| const DT_ANDROID_RELRCOUNT: i64 = 0x6fff_e005; | |
| const DT_GNU_HASH: i64 = 0x6fff_fef5; | |
| const DT_TLSDESC_GOT: i64 = 0x6fff_fef7; | |
| const DT_FLAGS_1: i64 = 0x6fff_fffb; | |
| const DF_TEXTREL: u64 = 0x4; | |
| const DF_BIND_NOW: u64 = 0x8; | |
| const DF_1_NOW: u64 = 0x1; | |
| // x86-64 relocation types. | |
| pub const R_X86_64_PC32: u32 = 2; | |
| pub const R_X86_64_PLT32: u32 = 4; | |
| pub const R_X86_64_COPY: u32 = 5; | |
| pub const R_X86_64_GLOB_DAT: u32 = 6; | |
| pub const R_X86_64_JUMP_SLOT: u32 = 7; | |
| pub const R_X86_64_RELATIVE: u32 = 8; | |
| pub const R_X86_64_GOTPCREL: u32 = 9; | |
| pub const R_X86_64_GOTTPOFF: u32 = 22; | |
| pub const R_X86_64_TLSDESC: u32 = 36; | |
| pub const R_X86_64_IRELATIVE: u32 = 37; | |
| pub const R_X86_64_GOTPCRELX: u32 = 41; | |
| pub const R_X86_64_REX_GOTPCRELX: u32 = 42; | |
| // AArch64 relocation types. | |
| pub const R_AARCH64_ADR_PREL_PG_HI21: u32 = 275; | |
| pub const R_AARCH64_ADD_ABS_LO12_NC: u32 = 277; | |
| pub const R_AARCH64_JUMP26: u32 = 282; | |
| pub const R_AARCH64_CALL26: u32 = 283; | |
| pub const R_AARCH64_COPY: u32 = 1024; | |
| pub const R_AARCH64_RELATIVE: u32 = 1027; | |
| pub const R_AARCH64_TLSDESC: u32 = 1031; | |
| pub const R_AARCH64_IRELATIVE: u32 = 1032; | |
| // GNU property note constants (`NT_GNU_PROPERTY_TYPE_0`). | |
| pub const NT_GNU_PROPERTY_TYPE_0: u32 = 5; | |
| pub const GNU_PROPERTY_AARCH64_FEATURE_1_AND: u32 = 0xc000_0000; | |
| pub const GNU_PROPERTY_X86_FEATURE_1_AND: u32 = 0xc000_0002; | |
| pub const GNU_PROPERTY_X86_FEATURE_1_IBT: u32 = 0x1; | |
| pub const GNU_PROPERTY_X86_FEATURE_1_SHSTK: u32 = 0x2; | |
| pub const GNU_PROPERTY_AARCH64_FEATURE_1_BTI: u32 = 0x1; | |
| pub const GNU_PROPERTY_AARCH64_FEATURE_1_PAC: u32 = 0x2; | |
| #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] | |
| #[serde(rename_all = "kebab-case")] | |
| pub enum Arch { | |
| X86_64, | |
| AArch64, | |
| } | |
| impl fmt::Display for Arch { | |
| fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
| match self { | |
| Arch::X86_64 => f.write_str("x86-64"), | |
| Arch::AArch64 => f.write_str("aarch64"), | |
| } | |
| } | |
| } | |
| #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] | |
| #[serde(rename_all = "UPPERCASE")] | |
| pub enum ElfType { | |
| Rel, | |
| Exec, | |
| Dyn, | |
| } | |
| #[derive(Debug, Clone)] | |
| pub struct Elf64Header { | |
| pub e_type: ElfType, | |
| pub arch: Arch, | |
| pub e_entry: u64, | |
| pub e_phoff: u64, | |
| pub e_shoff: u64, | |
| pub e_phnum: u32, | |
| pub e_shnum: u32, | |
| pub e_shstrndx: u32, | |
| } | |
| #[derive(Debug, Clone, Copy)] | |
| pub struct ProgramHeader { | |
| pub index: usize, | |
| pub p_type: u32, | |
| pub p_flags: u32, | |
| pub p_offset: u64, | |
| pub p_vaddr: u64, | |
| pub p_filesz: u64, | |
| pub p_memsz: u64, | |
| pub p_align: u64, | |
| } | |
| #[derive(Debug, Clone)] | |
| pub struct SectionHeader { | |
| pub index: usize, | |
| pub name: String, | |
| pub sh_type: u32, | |
| pub sh_flags: u64, | |
| pub sh_addr: u64, | |
| pub sh_offset: u64, | |
| pub sh_size: u64, | |
| pub sh_link: u32, | |
| pub sh_info: u32, | |
| pub sh_entsize: u64, | |
| } | |
| #[derive(Debug, Clone)] | |
| pub struct Symbol { | |
| pub index: usize, | |
| pub name: String, | |
| pub st_info: u8, | |
| pub st_other: u8, | |
| pub raw_shndx: u16, | |
| pub st_shndx: u32, | |
| pub st_value: u64, | |
| pub st_size: u64, | |
| } | |
| impl Symbol { | |
| pub fn bind(&self) -> u8 { | |
| self.st_info >> 4 | |
| } | |
| pub fn sym_type(&self) -> u8 { | |
| self.st_info & 0x0f | |
| } | |
| /// True if the symbol is defined in a concrete section (including | |
| /// `SHN_XINDEX`-resolved section indices `>= SHN_LORESERVE`). | |
| pub fn is_defined(&self) -> bool { | |
| if self.raw_shndx == SHN_XINDEX { | |
| self.st_shndx != SHN_UNDEF | |
| } else { | |
| self.st_shndx != SHN_UNDEF && self.st_shndx < SHN_LORESERVE | |
| } | |
| } | |
| } | |
| #[derive(Debug, Clone, Copy)] | |
| pub struct Rela { | |
| pub r_offset: u64, | |
| pub r_sym: u32, | |
| pub r_type: u32, | |
| pub r_addend: i64, | |
| } | |
| #[derive(Debug, Clone)] | |
| pub struct RelaSection { | |
| pub sh_name: String, | |
| pub sh_link: u32, | |
| pub target_sec: usize, | |
| pub entries: Vec<Rela>, | |
| } | |
| /// Full symbol metadata resolved from `DT_SYMTAB`/`DT_STRTAB` (or linked | |
| /// relocation section symbol tables). | |
| #[derive(Debug, Clone, PartialEq, Eq)] | |
| pub struct DynSymInfo { | |
| pub name: Option<String>, | |
| pub st_info: u8, | |
| pub st_other: u8, | |
| pub st_shndx: u16, | |
| pub st_value: u64, | |
| pub st_size: u64, | |
| } | |
| impl DynSymInfo { | |
| pub fn bind(&self) -> u8 { | |
| self.st_info >> 4 | |
| } | |
| pub fn sym_type(&self) -> u8 { | |
| self.st_info & 0x0f | |
| } | |
| /// True if the dynamic symbol is defined in a concrete section (not | |
| /// `SHN_UNDEF` and not a reserved/special section index). | |
| pub fn is_defined(&self) -> bool { | |
| self.st_shndx != 0 && u32::from(self.st_shndx) < SHN_LORESERVE | |
| } | |
| } | |
| /// Parsed dynamic relocation entry from `PT_DYNAMIC` or allocatable linked | |
| /// relocation sections. | |
| #[derive(Debug, Clone)] | |
| pub struct DynReloc { | |
| pub r_offset: u64, | |
| pub r_type: u32, | |
| pub r_addend: i64, | |
| pub width: u64, | |
| pub from_relr: bool, | |
| pub sym_info: Option<DynSymInfo>, | |
| pub source: String, | |
| } | |
| /// Parsed dynamic linking metadata and load-time relocations. | |
| /// | |
| /// `runtime_relocs` comes strictly from `PT_LOAD`-mapped `PT_DYNAMIC` tables | |
| /// (trusted for positive GOT/PLT binding); `section_relocs` holds allocatable | |
| /// section-header relocation tables (used only for negative overlap/conflict | |
| /// detection, never to satisfy positive GOT/PLT bindings). | |
| #[derive(Debug, Clone, Default)] | |
| pub struct DynamicInfo { | |
| pub has_pt_dynamic: bool, | |
| pub pt_dynamic_phdr: Option<ProgramHeader>, | |
| pub has_textrel: bool, | |
| pub has_bind_now: bool, | |
| pub dt_pltgot: Option<u64>, | |
| pub dt_tlsdesc_got: Option<u64>, | |
| pub runtime_relocs: Vec<DynReloc>, | |
| pub section_relocs: Vec<DynReloc>, | |
| } | |
| impl DynamicInfo { | |
| /// Iterator over both runtime (`PT_DYNAMIC`) and section-header relocs for | |
| /// negative overlap and conflict detection. | |
| pub fn all_relocs(&self) -> impl Iterator<Item = &DynReloc> { | |
| self.runtime_relocs.iter().chain(self.section_relocs.iter()) | |
| } | |
| /// Virtual address ranges written directly by `ld.so` runtime setup | |
| /// (`DT_PLTGOT[0..3]` reserved header words and `DT_TLSDESC_GOT` resolver | |
| /// slot) outside explicit `DT_RELA`/`DT_JMPREL`/`DT_RELR` entries. | |
| pub fn loader_write_ranges(&self) -> Vec<(u64, u64, &'static str)> { | |
| let mut ranges = Vec::new(); | |
| if let Some(pltgot) = self.dt_pltgot { | |
| ranges.push((pltgot, pltgot.saturating_add(24), "DT_PLTGOT[0..3]")); | |
| } | |
| if let Some(tlsdesc_got) = self.dt_tlsdesc_got { | |
| ranges.push((tlsdesc_got, tlsdesc_got.saturating_add(8), "DT_TLSDESC_GOT")); | |
| } | |
| ranges | |
| } | |
| } | |
| #[derive(Debug, Clone, Default, Serialize)] | |
| pub struct GnuProperties { | |
| pub present: bool, | |
| pub pt_gnu_property_present: bool, | |
| pub x86_ibt: bool, | |
| pub x86_shstk: bool, | |
| pub aarch64_bti: bool, | |
| pub aarch64_pac: bool, | |
| } | |
| #[derive(Debug, Clone, Serialize)] | |
| pub struct StackSizeEntry { | |
| pub func_addr: u64, | |
| pub stack_bytes: u64, | |
| pub symbol: Option<String>, | |
| } | |
| #[derive(Debug, Clone)] | |
| pub struct Elf64<'a> { | |
| bytes: &'a [u8], | |
| pub header: Elf64Header, | |
| pub phdrs: Vec<ProgramHeader>, | |
| pub shdrs: Vec<SectionHeader>, | |
| pub symbols: Vec<Symbol>, | |
| pub dynsyms: Vec<Symbol>, | |
| pub rela_sections: Vec<RelaSection>, | |
| } | |
| fn read_u16(bytes: &[u8], off: usize) -> Result<u16, String> { | |
| let slice = bytes | |
| .get(off..off.checked_add(2).ok_or("u16 offset overflow")?) | |
| .ok_or_else(|| format!("truncated u16 at offset 0x{off:x}"))?; | |
| Ok(u16::from_le_bytes([slice[0], slice[1]])) | |
| } | |
| fn read_u32(bytes: &[u8], off: usize) -> Result<u32, String> { | |
| let slice = bytes | |
| .get(off..off.checked_add(4).ok_or("u32 offset overflow")?) | |
| .ok_or_else(|| format!("truncated u32 at offset 0x{off:x}"))?; | |
| Ok(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]])) | |
| } | |
| fn read_u64(bytes: &[u8], off: usize) -> Result<u64, String> { | |
| let slice = bytes | |
| .get(off..off.checked_add(8).ok_or("u64 offset overflow")?) | |
| .ok_or_else(|| format!("truncated u64 at offset 0x{off:x}"))?; | |
| Ok(u64::from_le_bytes([ | |
| slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7], | |
| ])) | |
| } | |
| fn read_i64(bytes: &[u8], off: usize) -> Result<i64, String> { | |
| Ok(read_u64(bytes, off)? as i64) | |
| } | |
| fn slice_u64(bytes: &[u8], off: u64, len: u64) -> Result<&[u8], String> { | |
| let start = usize::try_from(off).map_err(|_| format!("offset 0x{off:x} exceeds usize"))?; | |
| let size = usize::try_from(len).map_err(|_| format!("size 0x{len:x} exceeds usize"))?; | |
| let end = start.checked_add(size).ok_or("byte range overflow")?; | |
| bytes | |
| .get(start..end) | |
| .ok_or_else(|| format!("slice [0x{off:x}..+0x{len:x}) exceeds file length")) | |
| } | |
| fn read_cstr(strtab: &[u8], off: u32) -> Result<String, String> { | |
| let start = usize::try_from(off).map_err(|_| "string offset exceeds usize")?; | |
| let tail = | |
| strtab.get(start..).ok_or_else(|| format!("string offset 0x{off:x} out of bounds"))?; | |
| let nul = tail | |
| .iter() | |
| .position(|&b| b == 0) | |
| .ok_or_else(|| format!("unterminated string at offset 0x{off:x}"))?; | |
| String::from_utf8(tail[..nul].to_vec()) | |
| .map_err(|_| format!("non-UTF-8 string at offset 0x{off:x}")) | |
| } | |
| fn align_up(val: usize, align: usize) -> Result<usize, String> { | |
| let rem = val % align; | |
| if rem == 0 { | |
| Ok(val) | |
| } else { | |
| val.checked_add(align - rem).ok_or_else(|| "alignment overflow".to_owned()) | |
| } | |
| } | |
| impl<'a> Elf64<'a> { | |
| /// Parse a little-endian ELF64 object or linked binary fail-closed. | |
| pub fn parse(bytes: &'a [u8]) -> Result<Self, String> { | |
| if bytes.len() < usize::from(ELF64_EHDR_SIZE) { | |
| return Err("file shorter than 64-byte ELF64 header".to_owned()); | |
| } | |
| if bytes[0..4] != ELF_MAGIC { | |
| return Err("invalid ELF magic".to_owned()); | |
| } | |
| if bytes[4] != ELFCLASS64 { | |
| return Err(format!("unsupported ELF class {} (need ELFCLASS64)", bytes[4])); | |
| } | |
| if bytes[5] != ELFDATA2LSB { | |
| return Err(format!("unsupported ELF endianness {} (need LSB)", bytes[5])); | |
| } | |
| if bytes[6] != EV_CURRENT { | |
| return Err(format!("unsupported EI_VERSION {}", bytes[6])); | |
| } | |
| let e_type = match read_u16(bytes, 16)? { | |
| ET_REL => ElfType::Rel, | |
| ET_EXEC => ElfType::Exec, | |
| ET_DYN => ElfType::Dyn, | |
| other => return Err(format!("unsupported e_type {other}")), | |
| }; | |
| let arch = match read_u16(bytes, 18)? { | |
| EM_X86_64 => Arch::X86_64, | |
| EM_AARCH64 => Arch::AArch64, | |
| other => return Err(format!("unsupported e_machine {other}")), | |
| }; | |
| let e_version = read_u32(bytes, 20)?; | |
| if e_version != 1 { | |
| return Err(format!("unsupported e_version {e_version}")); | |
| } | |
| let e_entry = read_u64(bytes, 24)?; | |
| let e_phoff = read_u64(bytes, 32)?; | |
| let e_shoff = read_u64(bytes, 40)?; | |
| let e_ehsize = read_u16(bytes, 52)?; | |
| if e_ehsize != ELF64_EHDR_SIZE { | |
| return Err(format!("unexpected e_ehsize {e_ehsize}")); | |
| } | |
| let e_phentsize = read_u16(bytes, 54)?; | |
| let raw_phnum = read_u16(bytes, 56)?; | |
| let e_shentsize = read_u16(bytes, 58)?; | |
| let raw_shnum = read_u16(bytes, 60)?; | |
| let raw_shstrndx = read_u16(bytes, 62)?; | |
| // Resolve extended section/program header counts from shdr[0] if used. | |
| let mut e_shnum = u32::from(raw_shnum); | |
| let mut e_shstrndx = u32::from(raw_shstrndx); | |
| let mut e_phnum = u32::from(raw_phnum); | |
| if e_shoff != 0 { | |
| if e_shentsize != ELF64_SHDR_SIZE { | |
| return Err(format!("unexpected e_shentsize {e_shentsize}")); | |
| } | |
| let sh0 = slice_u64(bytes, e_shoff, u64::from(ELF64_SHDR_SIZE))?; | |
| if raw_shnum == 0 { | |
| let sz = read_u64(sh0, 32)?; | |
| e_shnum = u32::try_from(sz).map_err(|_| "extended e_shnum exceeds u32")?; | |
| } | |
| if raw_shstrndx == SHN_XINDEX { | |
| e_shstrndx = read_u32(sh0, 40)?; | |
| } | |
| if raw_phnum == PN_XNUM { | |
| e_phnum = read_u32(sh0, 44)?; | |
| } | |
| } else if raw_shnum != 0 || raw_phnum == PN_XNUM { | |
| return Err("section headers required for non-zero e_shnum or PN_XNUM".to_owned()); | |
| } | |
| // Parse program headers; validate table bounds before allocating. | |
| let mut phdrs = Vec::new(); | |
| if e_phnum > 0 { | |
| if e_phentsize != ELF64_PHDR_SIZE { | |
| return Err(format!("unexpected e_phentsize {e_phentsize}")); | |
| } | |
| let total = u64::from(e_phnum) | |
| .checked_mul(u64::from(ELF64_PHDR_SIZE)) | |
| .ok_or("program header table size overflow")?; | |
| let table = slice_u64(bytes, e_phoff, total)?; | |
| let count = usize::try_from(e_phnum).map_err(|_| "e_phnum exceeds usize")?; | |
| phdrs.reserve(count); | |
| for i in 0..count { | |
| let off = i * usize::from(ELF64_PHDR_SIZE); | |
| phdrs.push(ProgramHeader { | |
| index: i, | |
| p_type: read_u32(table, off)?, | |
| p_flags: read_u32(table, off + 4)?, | |
| p_offset: read_u64(table, off + 8)?, | |
| p_vaddr: read_u64(table, off + 16)?, | |
| p_filesz: read_u64(table, off + 32)?, | |
| p_memsz: read_u64(table, off + 40)?, | |
| p_align: read_u64(table, off + 48)?, | |
| }); | |
| } | |
| } | |
| // Parse section headers; validate table bounds before allocating. | |
| let mut raw_shdrs = Vec::new(); | |
| if e_shnum > 0 { | |
| let total = u64::from(e_shnum) | |
| .checked_mul(u64::from(ELF64_SHDR_SIZE)) | |
| .ok_or("section header table size overflow")?; | |
| let table = slice_u64(bytes, e_shoff, total)?; | |
| let count = usize::try_from(e_shnum).map_err(|_| "e_shnum exceeds usize")?; | |
| raw_shdrs.reserve(count); | |
| for i in 0..count { | |
| let off = i * usize::from(ELF64_SHDR_SIZE); | |
| raw_shdrs.push(( | |
| read_u32(table, off)?, | |
| read_u32(table, off + 4)?, | |
| read_u64(table, off + 8)?, | |
| read_u64(table, off + 16)?, | |
| read_u64(table, off + 24)?, | |
| read_u64(table, off + 32)?, | |
| read_u32(table, off + 40)?, | |
| read_u32(table, off + 44)?, | |
| read_u64(table, off + 56)?, | |
| )); | |
| } | |
| } | |
| let shstrtab: &[u8] = if e_shnum > 0 { | |
| let idx = usize::try_from(e_shstrndx).map_err(|_| "e_shstrndx exceeds usize")?; | |
| let sh = raw_shdrs | |
| .get(idx) | |
| .ok_or_else(|| format!("e_shstrndx {e_shstrndx} out of bounds"))?; | |
| if sh.1 != SHT_STRTAB { | |
| return Err(format!("section {idx} (.shstrtab) is not SHT_STRTAB")); | |
| } | |
| if (sh.2 & SHF_COMPRESSED) != 0 { | |
| return Err(".shstrtab is compressed".to_owned()); | |
| } | |
| slice_u64(bytes, sh.4, sh.5)? | |
| } else { | |
| &[] | |
| }; | |
| let mut shdrs = Vec::with_capacity(raw_shdrs.len()); | |
| for (i, sh) in raw_shdrs.into_iter().enumerate() { | |
| let name = read_cstr(shstrtab, sh.0)?; | |
| shdrs.push(SectionHeader { | |
| index: i, | |
| name, | |
| sh_type: sh.1, | |
| sh_flags: sh.2, | |
| sh_addr: sh.3, | |
| sh_offset: sh.4, | |
| sh_size: sh.5, | |
| sh_link: sh.6, | |
| sh_info: sh.7, | |
| sh_entsize: sh.8, | |
| }); | |
| } | |
| let header = | |
| Elf64Header { e_type, arch, e_entry, e_phoff, e_shoff, e_phnum, e_shnum, e_shstrndx }; | |
| let symbols = parse_symtab_kind(bytes, &shdrs, SHT_SYMTAB)?; | |
| let dynsyms = parse_symtab_kind(bytes, &shdrs, SHT_DYNSYM)?; | |
| let rela_sections = parse_relas(bytes, &shdrs, e_type)?; | |
| Ok(Self { bytes, header, phdrs, shdrs, symbols, dynsyms, rela_sections }) | |
| } | |
| pub fn raw_bytes(&self) -> &'a [u8] { | |
| self.bytes | |
| } | |
| pub fn section_bytes(&self, sh: &SectionHeader) -> Result<&'a [u8], String> { | |
| section_bytes_raw(self.bytes, sh) | |
| } | |
| pub fn section_by_name(&self, name: &str) -> Option<&SectionHeader> { | |
| self.shdrs.iter().find(|s| s.name == name) | |
| } | |
| pub fn relas_for_section(&self, sec_idx: usize) -> Option<&[Rela]> { | |
| self.rela_sections.iter().find(|s| s.target_sec == sec_idx).map(|s| s.entries.as_slice()) | |
| } | |
| /// Resolve `[va, va + len)` inside a unique `PT_LOAD` file-backed range, | |
| /// failing closed if zero or multiple `PT_LOAD` segments cover it. | |
| pub fn va_to_segment_slice( | |
| &self, | |
| va: u64, | |
| len: u64, | |
| ) -> Result<(&'a [u8], ProgramHeader), String> { | |
| let va_end = va.checked_add(len).ok_or("VA range overflow")?; | |
| let mut found: Option<(&'a [u8], ProgramHeader)> = None; | |
| for ph in &self.phdrs { | |
| if ph.p_type != PT_LOAD { | |
| continue; | |
| } | |
| let seg_file_end = | |
| ph.p_vaddr.checked_add(ph.p_filesz).ok_or("PT_LOAD file range overflow")?; | |
| if va >= ph.p_vaddr && va_end <= seg_file_end { | |
| let delta = va - ph.p_vaddr; | |
| let file_off = | |
| ph.p_offset.checked_add(delta).ok_or("PT_LOAD file offset overflow")?; | |
| let slice = slice_u64(self.bytes, file_off, len)?; | |
| if found.is_some() { | |
| return Err(format!( | |
| "VA range [0x{va:x}..0x{va_end:x}) mapped by multiple PT_LOAD segments" | |
| )); | |
| } | |
| found = Some((slice, *ph)); | |
| } | |
| } | |
| found.ok_or_else(|| { | |
| format!("VA range [0x{va:x}..0x{va_end:x}) not mapped by any file-backed PT_LOAD") | |
| }) | |
| } | |
| /// Resolve the file-backed tail of the unique `PT_LOAD` segment containing | |
| /// `va`, returning `(tail_slice, file_offset_of_va, segment)`. | |
| pub fn va_to_segment_tail(&self, va: u64) -> Result<(&'a [u8], u64, ProgramHeader), String> { | |
| let mut found: Option<(&'a [u8], u64, ProgramHeader)> = None; | |
| for ph in &self.phdrs { | |
| if ph.p_type != PT_LOAD { | |
| continue; | |
| } | |
| let seg_file_end = | |
| ph.p_vaddr.checked_add(ph.p_filesz).ok_or("PT_LOAD file range overflow")?; | |
| if va >= ph.p_vaddr && va < seg_file_end { | |
| let delta = va - ph.p_vaddr; | |
| let file_off = | |
| ph.p_offset.checked_add(delta).ok_or("PT_LOAD file offset overflow")?; | |
| let rem = seg_file_end - va; | |
| let slice = slice_u64(self.bytes, file_off, rem)?; | |
| if found.is_some() { | |
| return Err(format!("VA 0x{va:x} mapped by multiple PT_LOAD segments")); | |
| } | |
| found = Some((slice, file_off, *ph)); | |
| } | |
| } | |
| found.ok_or_else(|| format!("VA 0x{va:x} not mapped by any file-backed PT_LOAD")) | |
| } | |
| /// Resolve `[va, va + len)` from the unique file-backed read-only | |
| /// (`PF_R && !PF_W`) `PT_LOAD` segment so dynamic loader metadata cannot | |
| /// be mutated by earlier relocations before RELRO protection. | |
| fn va_to_ro_segment_slice( | |
| &self, | |
| va: u64, | |
| len: u64, | |
| label: &str, | |
| ) -> Result<(&'a [u8], ProgramHeader), String> { | |
| let (slice, seg) = self.va_to_segment_slice(va, len)?; | |
| if (seg.p_flags & PF_R) == 0 || (seg.p_flags & PF_W) != 0 { | |
| return Err(format!( | |
| "{label} at 0x{va:x} is mapped in non-RO PT_LOAD[{}] (p_flags=0x{:x})", | |
| seg.index, seg.p_flags | |
| )); | |
| } | |
| Ok((slice, seg)) | |
| } | |
| /// Resolve the file-backed tail from the unique read-only (`PF_R && !PF_W`) | |
| /// `PT_LOAD` segment containing `va`. | |
| fn va_to_ro_segment_tail( | |
| &self, | |
| va: u64, | |
| label: &str, | |
| ) -> Result<(&'a [u8], u64, ProgramHeader), String> { | |
| let (slice, file_off, seg) = self.va_to_segment_tail(va)?; | |
| if (seg.p_flags & PF_R) == 0 || (seg.p_flags & PF_W) != 0 { | |
| return Err(format!( | |
| "{label} at 0x{va:x} is mapped in non-RO PT_LOAD[{}] (p_flags=0x{:x})", | |
| seg.index, seg.p_flags | |
| )); | |
| } | |
| Ok((slice, file_off, seg)) | |
| } | |
| /// Parse runtime-enforced `PT_GNU_PROPERTY` program header via its | |
| /// `PT_LOAD`-mapped `p_vaddr`, checking consistency against `p_offset` and | |
| /// `.note.gnu.property` when present. | |
| pub fn parse_gnu_properties(&self) -> Result<GnuProperties, String> { | |
| let prop_phdrs: Vec<&ProgramHeader> = | |
| self.phdrs.iter().filter(|p| p.p_type == PT_GNU_PROPERTY).collect(); | |
| if prop_phdrs.len() > 1 { | |
| return Err(format!( | |
| "found {} PT_GNU_PROPERTY program headers (expected at most 1)", | |
| prop_phdrs.len() | |
| )); | |
| } | |
| let sec_data = match self | |
| .shdrs | |
| .iter() | |
| .find(|s| s.name == ".note.gnu.property" && s.sh_type == SHT_NOTE) | |
| { | |
| Some(sh) => Some(self.section_bytes(sh)?), | |
| None => None, | |
| }; | |
| let Some(ph) = prop_phdrs.first() else { | |
| return Ok(GnuProperties { | |
| present: sec_data.is_some(), | |
| pt_gnu_property_present: false, | |
| ..GnuProperties::default() | |
| }); | |
| }; | |
| if ph.p_align != 8 || !ph.p_vaddr.is_multiple_of(8) || !ph.p_offset.is_multiple_of(8) { | |
| return Err(format!( | |
| "PT_GNU_PROPERTY requires p_align == 8 and 8-byte aligned p_vaddr/p_offset \ | |
| (got p_align={}, p_vaddr=0x{:x}, p_offset=0x{:x})", | |
| ph.p_align, ph.p_vaddr, ph.p_offset | |
| )); | |
| } | |
| if ph.p_filesz != ph.p_memsz { | |
| return Err("PT_GNU_PROPERTY p_filesz != p_memsz".to_owned()); | |
| } | |
| let (vaddr_data, seg) = self.va_to_segment_slice(ph.p_vaddr, ph.p_filesz)?; | |
| if (seg.p_flags & PF_R) == 0 || (seg.p_flags & PF_W) != 0 { | |
| return Err(format!( | |
| "PT_GNU_PROPERTY mapped in PT_LOAD[{}] with non-RO flags 0x{:x}", | |
| seg.index, seg.p_flags | |
| )); | |
| } | |
| let offset_data = slice_u64(self.bytes, ph.p_offset, ph.p_filesz)?; | |
| if vaddr_data != offset_data { | |
| return Err( | |
| "PT_GNU_PROPERTY p_offset bytes conflict with PT_LOAD-mapped p_vaddr".to_owned() | |
| ); | |
| } | |
| if let Some(sec_bytes) = sec_data { | |
| if sec_bytes != vaddr_data { | |
| return Err( | |
| "PT_GNU_PROPERTY payload conflicts with .note.gnu.property section".to_owned() | |
| ); | |
| } | |
| } | |
| let mut props = GnuProperties { | |
| present: true, | |
| pt_gnu_property_present: true, | |
| ..GnuProperties::default() | |
| }; | |
| parse_gnu_property_notes(vaddr_data, &mut props)?; | |
| Ok(props) | |
| } | |
| /// Parse all `.stack_sizes` sections `(u64 LE addr, ULEB128 frame_bytes)`. | |
| pub fn parse_stack_sizes(&self) -> Result<Option<Vec<StackSizeEntry>>, String> { | |
| let sections: Vec<&SectionHeader> = | |
| self.shdrs.iter().filter(|s| s.name == ".stack_sizes").collect(); | |
| if sections.is_empty() { | |
| return Ok(None); | |
| } | |
| let mut entries = Vec::new(); | |
| for sh in sections { | |
| let data = self.section_bytes(sh)?; | |
| let mut off = 0usize; | |
| while off < data.len() { | |
| if off + 8 > data.len() { | |
| return Err("truncated function address in .stack_sizes".to_owned()); | |
| } | |
| let func_addr = read_u64(data, off)?; | |
| off += 8; | |
| let (stack_bytes, consumed) = decode_uleb128(&data[off..])?; | |
| off += consumed; | |
| let symbol = self | |
| .symbols | |
| .iter() | |
| .find(|s| s.is_defined() && s.sym_type() == STT_FUNC && s.st_value == func_addr) | |
| .map(|s| s.name.clone()); | |
| entries.push(StackSizeEntry { func_addr, stack_bytes, symbol }); | |
| } | |
| } | |
| Ok(Some(entries)) | |
| } | |
| /// Parse `PT_DYNAMIC` from its `PT_LOAD`-mapped `p_vaddr` (requiring | |
| /// `DT_NULL`, `p_offset` parity, and `DT_SYMTAB`/`DT_STRTAB` lookup) plus | |
| /// allocatable section relocation tables for negative overlap checks. | |
| pub fn parse_dynamic_info(&self) -> Result<DynamicInfo, String> { | |
| let mut info = DynamicInfo::default(); | |
| let dyn_phdrs: Vec<&ProgramHeader> = | |
| self.phdrs.iter().filter(|p| p.p_type == PT_DYNAMIC).collect(); | |
| if dyn_phdrs.len() > 1 { | |
| return Err(format!( | |
| "found {} PT_DYNAMIC program headers (expected at most 1)", | |
| dyn_phdrs.len() | |
| )); | |
| } | |
| if let Some(&dyn_ph) = dyn_phdrs.first() { | |
| info.has_pt_dynamic = true; | |
| info.pt_dynamic_phdr = Some(*dyn_ph); | |
| // Walk PT_DYNAMIC from PT_LOAD-mapped p_vaddr until DT_NULL (like | |
| // ld.so), and verify p_offset/p_filesz consistency. | |
| let (dyn_tail, mapped_off, dyn_seg) = self.va_to_segment_tail(dyn_ph.p_vaddr)?; | |
| if (dyn_seg.p_flags & PF_R) == 0 { | |
| return Err(format!( | |
| "PT_DYNAMIC at 0x{:x} is mapped in non-readable PT_LOAD[{}] \ | |
| (p_flags=0x{:x})", | |
| dyn_ph.p_vaddr, dyn_seg.index, dyn_seg.p_flags | |
| )); | |
| } | |
| if dyn_ph.p_offset != mapped_off { | |
| return Err(format!( | |
| "PT_DYNAMIC p_offset 0x{:x} disagrees with PT_LOAD mapping 0x{mapped_off:x}", | |
| dyn_ph.p_offset | |
| )); | |
| } | |
| if !dyn_ph.p_filesz.is_multiple_of(ELF64_DYN_SIZE as u64) | |
| || dyn_ph.p_filesz > dyn_ph.p_memsz | |
| { | |
| return Err("PT_DYNAMIC p_filesz/p_memsz invalid".to_owned()); | |
| } | |
| let set_singleton = | |
| |slot: &mut Option<u64>, val: u64, tag_name: &str| -> Result<(), String> { | |
| if slot.is_some() { | |
| return Err(format!("duplicate singleton {tag_name} entry in PT_DYNAMIC")); | |
| } | |
| *slot = Some(val); | |
| Ok(()) | |
| }; | |
| let mut dt_textrel = None; | |
| let mut dt_bind_now = None; | |
| let mut dt_flags = None; | |
| let mut dt_flags_1 = None; | |
| let mut dt_pltgot = None; | |
| let mut dt_tlsdesc_got = None; | |
| let mut dt_hash = None; | |
| let mut dt_gnu_hash = None; | |
| let mut dt_rela = None; | |
| let mut dt_relasz = None; | |
| let mut dt_relaent = None; | |
| let mut dt_jmprel = None; | |
| let mut dt_pltrelsz = None; | |
| let mut dt_pltrel = None; | |
| let mut dt_relr = None; | |
| let mut dt_relrsz = None; | |
| let mut dt_relrent = None; | |
| let mut dt_symtab = None; | |
| let mut dt_strtab = None; | |
| let mut dt_strsz = None; | |
| let mut dt_syment = None; | |
| let mut saw_null = false; | |
| let mut bytes_walked = 0u64; | |
| for chunk in dyn_tail.as_chunks::<16>().0 { | |
| bytes_walked += 16; | |
| let d_tag = i64::from_le_bytes([ | |
| chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7], | |
| ]); | |
| let d_val = u64::from_le_bytes([ | |
| chunk[8], chunk[9], chunk[10], chunk[11], chunk[12], chunk[13], chunk[14], | |
| chunk[15], | |
| ]); | |
| match d_tag { | |
| DT_NULL => { | |
| saw_null = true; | |
| break; | |
| } | |
| DT_TEXTREL => set_singleton(&mut dt_textrel, d_val, "DT_TEXTREL")?, | |
| DT_BIND_NOW => set_singleton(&mut dt_bind_now, d_val, "DT_BIND_NOW")?, | |
| DT_FLAGS => set_singleton(&mut dt_flags, d_val, "DT_FLAGS")?, | |
| DT_FLAGS_1 => set_singleton(&mut dt_flags_1, d_val, "DT_FLAGS_1")?, | |
| DT_PLTGOT => set_singleton(&mut dt_pltgot, d_val, "DT_PLTGOT")?, | |
| DT_TLSDESC_GOT => set_singleton(&mut dt_tlsdesc_got, d_val, "DT_TLSDESC_GOT")?, | |
| DT_HASH => set_singleton(&mut dt_hash, d_val, "DT_HASH")?, | |
| DT_GNU_HASH => set_singleton(&mut dt_gnu_hash, d_val, "DT_GNU_HASH")?, | |
| DT_RELA => set_singleton(&mut dt_rela, d_val, "DT_RELA")?, | |
| DT_RELASZ => set_singleton(&mut dt_relasz, d_val, "DT_RELASZ")?, | |
| DT_RELAENT => set_singleton(&mut dt_relaent, d_val, "DT_RELAENT")?, | |
| DT_JMPREL => set_singleton(&mut dt_jmprel, d_val, "DT_JMPREL")?, | |
| DT_PLTRELSZ => set_singleton(&mut dt_pltrelsz, d_val, "DT_PLTRELSZ")?, | |
| DT_PLTREL => set_singleton(&mut dt_pltrel, d_val, "DT_PLTREL")?, | |
| DT_REL | DT_RELSZ | DT_RELENT => { | |
| return Err(format!( | |
| "unsupported DT_REL* tag 0x{d_tag:x} in PT_DYNAMIC \ | |
| (x86-64/AArch64 ld.so require Elf64_Rela)" | |
| )); | |
| } | |
| DT_ANDROID_REL | DT_ANDROID_RELSZ | DT_ANDROID_RELA | DT_ANDROID_RELASZ | |
| | DT_ANDROID_RELR | DT_ANDROID_RELRSZ | DT_ANDROID_RELRENT | |
| | DT_ANDROID_RELRCOUNT => { | |
| return Err(format!( | |
| "unsupported packed relocation tag 0x{d_tag:x} in PT_DYNAMIC" | |
| )); | |
| } | |
| DT_RELR => set_singleton(&mut dt_relr, d_val, "DT_RELR")?, | |
| DT_RELRSZ => set_singleton(&mut dt_relrsz, d_val, "DT_RELRSZ")?, | |
| DT_RELRENT => set_singleton(&mut dt_relrent, d_val, "DT_RELRENT")?, | |
| DT_SYMTAB => set_singleton(&mut dt_symtab, d_val, "DT_SYMTAB")?, | |
| DT_STRTAB => set_singleton(&mut dt_strtab, d_val, "DT_STRTAB")?, | |
| DT_STRSZ => set_singleton(&mut dt_strsz, d_val, "DT_STRSZ")?, | |
| DT_SYMENT => set_singleton(&mut dt_syment, d_val, "DT_SYMENT")?, | |
| _ => {} | |
| } | |
| } | |
| if !saw_null { | |
| return Err("PT_DYNAMIC lacks DT_NULL terminator inside PT_LOAD".to_owned()); | |
| } | |
| if bytes_walked > dyn_ph.p_filesz { | |
| return Err(format!( | |
| "PT_DYNAMIC runtime entries ({bytes_walked} B) exceed p_filesz ({} B)", | |
| dyn_ph.p_filesz | |
| )); | |
| } | |
| info.has_textrel = | |
| dt_textrel.is_some() || dt_flags.is_some_and(|v| (v & DF_TEXTREL) != 0); | |
| info.has_bind_now = dt_bind_now.is_some() | |
| || dt_flags.is_some_and(|v| (v & DF_BIND_NOW) != 0) | |
| || dt_flags_1.is_some_and(|v| (v & DF_1_NOW) != 0); | |
| if let Some(pltgot) = dt_pltgot { | |
| if pltgot.checked_add(24).is_none() { | |
| return Err("DT_PLTGOT address overflow".to_owned()); | |
| } | |
| info.dt_pltgot = Some(pltgot); | |
| } | |
| if let Some(tlsdesc_got) = dt_tlsdesc_got { | |
| if tlsdesc_got.checked_add(8).is_none() { | |
| return Err("DT_TLSDESC_GOT address overflow".to_owned()); | |
| } | |
| info.dt_tlsdesc_got = Some(tlsdesc_got); | |
| } | |
| // When `DT_SYMTAB` is present, verify `SHT_DYNSYM` and its linked | |
| // `.dynstr` match runtime `PT_LOAD`-mapped `DT_SYMTAB`/`DT_STRTAB` | |
| // in address, file offset, size, hash-table bounds, and raw bytes | |
| // so spoofed or truncated section headers cannot hide aliases. | |
| let dynsym_sh = self.shdrs.iter().find(|s| s.sh_type == SHT_DYNSYM); | |
| let mut dynsym_sec_size: Option<u64> = None; | |
| if let Some(symtab_va) = dt_symtab { | |
| let Some(dynsym_sh) = dynsym_sh else { | |
| return Err( | |
| "PT_DYNAMIC specifies DT_SYMTAB without a matching SHT_DYNSYM section" | |
| .to_owned(), | |
| ); | |
| }; | |
| if dynsym_sh.sh_addr != symtab_va { | |
| return Err(format!( | |
| "SHT_DYNSYM sh_addr 0x{:x} disagrees with DT_SYMTAB 0x{symtab_va:x}", | |
| dynsym_sh.sh_addr | |
| )); | |
| } | |
| let (_, mapped_sym_off, _) = self.va_to_ro_segment_tail(symtab_va, "DT_SYMTAB")?; | |
| if dynsym_sh.sh_offset != mapped_sym_off { | |
| return Err(format!( | |
| "SHT_DYNSYM sh_offset 0x{:x} disagrees with PT_LOAD mapping 0x{mapped_sym_off:x}", | |
| dynsym_sh.sh_offset | |
| )); | |
| } | |
| let (mapped_sym_bytes, _) = | |
| self.va_to_ro_segment_slice(symtab_va, dynsym_sh.sh_size, "DT_SYMTAB")?; | |
| if mapped_sym_bytes != self.section_bytes(dynsym_sh)? { | |
| return Err( | |
| "SHT_DYNSYM bytes disagree with PT_LOAD-mapped DT_SYMTAB".to_owned() | |
| ); | |
| } | |
| let dynsym_count = dynsym_sh.sh_size / (ELF64_SYM_SIZE as u64); | |
| dynsym_sec_size = Some(dynsym_sh.sh_size); | |
| // Bound `SHT_DYNSYM` entry count against `DT_HASH` (`nchain`, | |
| // `bucket[]`, and `chain[]`) and `DT_GNU_HASH`. | |
| if let Some(hash_va) = dt_hash { | |
| self.validate_sysv_hash(hash_va, dynsym_count)?; | |
| } | |
| if let Some(ghash_va) = dt_gnu_hash { | |
| let min_syms = self.gnu_hash_min_dynsym_count(ghash_va)?; | |
| if dynsym_count < min_syms { | |
| return Err(format!( | |
| "SHT_DYNSYM count {dynsym_count} is truncated below DT_GNU_HASH minimum {min_syms}" | |
| )); | |
| } | |
| } | |
| let strtab_va = | |
| dt_strtab.ok_or("PT_DYNAMIC specifies DT_SYMTAB without DT_STRTAB")?; | |
| let strsz = dt_strsz.ok_or("PT_DYNAMIC specifies DT_STRTAB without DT_STRSZ")?; | |
| let Some(str_sh) = self.shdrs.get(dynsym_sh.sh_link as usize) else { | |
| return Err("SHT_DYNSYM sh_link out of bounds".to_owned()); | |
| }; | |
| if str_sh.sh_addr != strtab_va { | |
| return Err(format!( | |
| "SHT_DYNSYM strtab sh_addr 0x{:x} disagrees with DT_STRTAB 0x{strtab_va:x}", | |
| str_sh.sh_addr | |
| )); | |
| } | |
| let (_, mapped_str_off, _) = self.va_to_ro_segment_tail(strtab_va, "DT_STRTAB")?; | |
| if str_sh.sh_offset != mapped_str_off { | |
| return Err(format!( | |
| "SHT_DYNSYM strtab sh_offset 0x{:x} disagrees with PT_LOAD mapping 0x{mapped_str_off:x}", | |
| str_sh.sh_offset | |
| )); | |
| } | |
| if str_sh.sh_size != strsz { | |
| return Err(format!( | |
| "SHT_DYNSYM strtab sh_size {} disagrees with DT_STRSZ {strsz}", | |
| str_sh.sh_size | |
| )); | |
| } | |
| let (mapped_str_bytes, _) = | |
| self.va_to_ro_segment_slice(strtab_va, strsz, "DT_STRTAB")?; | |
| if mapped_str_bytes != self.section_bytes(str_sh)? { | |
| return Err( | |
| "SHT_DYNSYM strtab bytes disagree with PT_LOAD-mapped DT_STRTAB".to_owned() | |
| ); | |
| } | |
| } | |
| // Resolve dynamic symbols strictly from PT_LOAD-mapped DT_SYMTAB / | |
| // DT_STRTAB (matching ld.so, with full sym metadata). | |
| let resolve_runtime_sym = |r_sym: u32| -> Result<Option<DynSymInfo>, String> { | |
| if r_sym == 0 { | |
| return Ok(None); | |
| } | |
| let symtab_va = | |
| dt_symtab.ok_or("dynamic relocation references symbol without DT_SYMTAB")?; | |
| let strtab_va = | |
| dt_strtab.ok_or("dynamic relocation references symbol without DT_STRTAB")?; | |
| let strsz = | |
| dt_strsz.ok_or("dynamic relocation references symbol without DT_STRSZ")?; | |
| let syment = dt_syment.unwrap_or(ELF64_SYM_SIZE as u64); | |
| if syment != ELF64_SYM_SIZE as u64 { | |
| return Err(format!("unexpected DT_SYMENT {syment}")); | |
| } | |
| let sym_off = | |
| u64::from(r_sym).checked_mul(syment).ok_or("DT_SYMTAB index overflow")?; | |
| let sym_end = sym_off.checked_add(syment).ok_or("DT_SYMTAB end overflow")?; | |
| if let Some(sec_sz) = dynsym_sec_size { | |
| if sym_end > sec_sz { | |
| return Err(format!( | |
| "dynamic relocation symbol index {r_sym} exceeds SHT_DYNSYM size {sec_sz}" | |
| )); | |
| } | |
| } | |
| let sym_va = symtab_va.checked_add(sym_off).ok_or("DT_SYMTAB VA overflow")?; | |
| let (sym_slice, _) = self.va_to_ro_segment_slice(sym_va, syment, "DT_SYMTAB")?; | |
| let st_name = read_u32(sym_slice, 0)?; | |
| let st_info = sym_slice[4]; | |
| let st_other = sym_slice[5]; | |
| let st_shndx = read_u16(sym_slice, 6)?; | |
| let st_value = read_u64(sym_slice, 8)?; | |
| let st_size = read_u64(sym_slice, 16)?; | |
| let (str_slice, _) = self.va_to_ro_segment_slice(strtab_va, strsz, "DT_STRTAB")?; | |
| let name = read_cstr(str_slice, st_name)?; | |
| Ok(Some(DynSymInfo { | |
| name: (!name.is_empty()).then_some(name), | |
| st_info, | |
| st_other, | |
| st_shndx, | |
| st_value, | |
| st_size, | |
| })) | |
| }; | |
| if let Some(rela_va) = dt_rela { | |
| let sz = dt_relasz.ok_or("PT_DYNAMIC has DT_RELA without DT_RELASZ")?; | |
| let ent = dt_relaent.unwrap_or(ELF64_RELA_SIZE as u64); | |
| if ent != ELF64_RELA_SIZE as u64 || !sz.is_multiple_of(ent) { | |
| return Err("invalid DT_RELAENT or DT_RELASZ in PT_DYNAMIC".to_owned()); | |
| } | |
| let (data, _) = self.va_to_ro_segment_slice(rela_va, sz, "DT_RELA")?; | |
| parse_dyn_rela_slice( | |
| data, | |
| "DT_RELA", | |
| self.header.arch, | |
| &resolve_runtime_sym, | |
| &mut info.runtime_relocs, | |
| )?; | |
| } | |
| if let Some(jmp_va) = dt_jmprel { | |
| let sz = dt_pltrelsz.ok_or("PT_DYNAMIC has DT_JMPREL without DT_PLTRELSZ")?; | |
| let kind = dt_pltrel.ok_or("PT_DYNAMIC has DT_JMPREL without DT_PLTREL")?; | |
| if kind != DT_RELA as u64 { | |
| return Err(format!( | |
| "unsupported DT_PLTREL kind {kind} (x86-64/AArch64 require DT_RELA)" | |
| )); | |
| } | |
| if !sz.is_multiple_of(ELF64_RELA_SIZE as u64) { | |
| return Err("invalid DT_PLTRELSZ for DT_RELA".to_owned()); | |
| } | |
| let (data, _) = self.va_to_ro_segment_slice(jmp_va, sz, "DT_JMPREL")?; | |
| parse_dyn_rela_slice( | |
| data, | |
| "DT_JMPREL", | |
| self.header.arch, | |
| &resolve_runtime_sym, | |
| &mut info.runtime_relocs, | |
| )?; | |
| } | |
| if let Some(relr_va) = dt_relr { | |
| let sz = dt_relrsz.ok_or("PT_DYNAMIC has DT_RELR without DT_RELRSZ")?; | |
| let ent = dt_relrent.unwrap_or(8); | |
| if ent != 8 || !sz.is_multiple_of(8) { | |
| return Err("invalid DT_RELRENT or DT_RELRSZ in PT_DYNAMIC".to_owned()); | |
| } | |
| let (data, _) = self.va_to_ro_segment_slice(relr_va, sz, "DT_RELR")?; | |
| parse_dyn_relr_slice(data, "DT_RELR", self.header.arch, &mut info.runtime_relocs)?; | |
| } | |
| } | |
| // Also scan allocatable relocation sections into `section_relocs` | |
| // (for static-PIE `.rela.iplt` and negative overlap checks only). | |
| for sh in &self.shdrs { | |
| if (sh.sh_flags & SHF_ALLOC) == 0 { | |
| continue; | |
| } | |
| match sh.sh_type { | |
| SHT_RELA => { | |
| let data = self.section_bytes(sh)?; | |
| if !data.len().is_multiple_of(ELF64_RELA_SIZE) { | |
| return Err(format!("section `{}` size not a multiple of 24", sh.name)); | |
| } | |
| let linked_syms = self.symbols_for_link(sh.sh_link); | |
| let resolve = |r_sym: u32| -> Result<Option<DynSymInfo>, String> { | |
| if r_sym == 0 { | |
| return Ok(None); | |
| } | |
| Ok(linked_syms.get(r_sym as usize).map(|s| DynSymInfo { | |
| name: (!s.name.is_empty()).then(|| s.name.clone()), | |
| st_info: s.st_info, | |
| st_other: s.st_other, | |
| st_shndx: s.raw_shndx, | |
| st_value: s.st_value, | |
| st_size: s.st_size, | |
| })) | |
| }; | |
| parse_dyn_rela_slice( | |
| data, | |
| &sh.name, | |
| self.header.arch, | |
| &resolve, | |
| &mut info.section_relocs, | |
| )?; | |
| } | |
| SHT_REL => { | |
| let data = self.section_bytes(sh)?; | |
| if !data.len().is_multiple_of(ELF64_REL_SIZE) { | |
| return Err(format!("section `{}` size not a multiple of 16", sh.name)); | |
| } | |
| let linked_syms = self.symbols_for_link(sh.sh_link); | |
| let resolve = |r_sym: u32| -> Result<Option<DynSymInfo>, String> { | |
| if r_sym == 0 { | |
| return Ok(None); | |
| } | |
| Ok(linked_syms.get(r_sym as usize).map(|s| DynSymInfo { | |
| name: (!s.name.is_empty()).then(|| s.name.clone()), | |
| st_info: s.st_info, | |
| st_other: s.st_other, | |
| st_shndx: s.raw_shndx, | |
| st_value: s.st_value, | |
| st_size: s.st_size, | |
| })) | |
| }; | |
| parse_dyn_rel_slice( | |
| data, | |
| &sh.name, | |
| self.header.arch, | |
| &resolve, | |
| &mut info.section_relocs, | |
| )?; | |
| } | |
| SHT_RELR => { | |
| let data = self.section_bytes(sh)?; | |
| if !data.len().is_multiple_of(8) { | |
| return Err(format!("section `{}` size not a multiple of 8", sh.name)); | |
| } | |
| parse_dyn_relr_slice( | |
| data, | |
| &sh.name, | |
| self.header.arch, | |
| &mut info.section_relocs, | |
| )?; | |
| } | |
| _ => {} | |
| } | |
| } | |
| // Drop exact duplicates from `section_relocs` that already match a | |
| // `runtime_relocs` entry identically (preserving any conflicts!). | |
| info.section_relocs.retain(|sr| { | |
| !info.runtime_relocs.iter().any(|rr| { | |
| rr.r_offset == sr.r_offset | |
| && rr.r_type == sr.r_type | |
| && rr.r_addend == sr.r_addend | |
| && rr.width == sr.width | |
| && rr.from_relr == sr.from_relr | |
| && rr.sym_info == sr.sym_info | |
| }) | |
| }); | |
| Ok(info) | |
| } | |
| fn symbols_for_link(&self, sh_link: u32) -> &[Symbol] { | |
| match self.shdrs.get(sh_link as usize).map(|s| s.sh_type) { | |
| Some(SHT_DYNSYM) => &self.dynsyms, | |
| Some(SHT_SYMTAB) => &self.symbols, | |
| _ => &[], | |
| } | |
| } | |
| /// Validate a SysV `DT_HASH` table (`nbuckets`, `nchain`, `bucket[]`, | |
| /// `chain[]`) against `SHT_DYNSYM` count so truncated section headers | |
| /// cannot hide symbols reachable by `ld.so`. | |
| fn validate_sysv_hash(&self, hash_va: u64, dynsym_count: u64) -> Result<(), String> { | |
| let (hdr, _) = self.va_to_ro_segment_slice(hash_va, 8, "DT_HASH")?; | |
| let nbuckets = u64::from(read_u32(hdr, 0)?); | |
| if nbuckets == 0 { | |
| return Err("DT_HASH nbuckets must be non-zero".to_owned()); | |
| } | |
| let nchain = u64::from(read_u32(hdr, 4)?); | |
| if dynsym_count < nchain { | |
| return Err(format!( | |
| "SHT_DYNSYM count {dynsym_count} is truncated below DT_HASH nchain {nchain}" | |
| )); | |
| } | |
| let total_words = nbuckets.checked_add(nchain).ok_or("DT_HASH word count overflow")?; | |
| let table_bytes = total_words | |
| .checked_mul(4) | |
| .and_then(|b| b.checked_add(8)) | |
| .ok_or("DT_HASH byte size overflow")?; | |
| let (table, _) = self.va_to_ro_segment_slice(hash_va, table_bytes, "DT_HASH")?; | |
| for chunk in table[8..].as_chunks::<4>().0 { | |
| let idx = u64::from(u32::from_le_bytes(*chunk)); | |
| if idx != 0 && (idx >= dynsym_count || idx >= nchain) { | |
| return Err(format!( | |
| "DT_HASH entry {idx} exceeds SHT_DYNSYM count {dynsym_count} / nchain {nchain}" | |
| )); | |
| } | |
| } | |
| Ok(()) | |
| } | |
| /// Compute the minimum `DT_SYMTAB` entry count implied by `DT_GNU_HASH`. | |
| fn gnu_hash_min_dynsym_count(&self, gnu_hash_va: u64) -> Result<u64, String> { | |
| let (tail, _, _) = self.va_to_ro_segment_tail(gnu_hash_va, "DT_GNU_HASH")?; | |
| if tail.len() < 16 { | |
| return Err("truncated DT_GNU_HASH header".to_owned()); | |
| } | |
| let nbuckets = usize::try_from(read_u32(tail, 0)?).map_err(|_| "nbuckets overflow")?; | |
| if nbuckets == 0 { | |
| return Err("DT_GNU_HASH nbuckets must be non-zero".to_owned()); | |
| } | |
| let symoffset = read_u32(tail, 4)?; | |
| let bloom_size = usize::try_from(read_u32(tail, 8)?).map_err(|_| "bloom_size overflow")?; | |
| if bloom_size == 0 { | |
| return Err("DT_GNU_HASH bloom_size must be non-zero".to_owned()); | |
| } | |
| let bloom_bytes = bloom_size.checked_mul(8).ok_or("DT_GNU_HASH bloom size overflow")?; | |
| let buckets_off = 16usize.checked_add(bloom_bytes).ok_or("DT_GNU_HASH buckets overflow")?; | |
| let buckets_bytes = nbuckets.checked_mul(4).ok_or("DT_GNU_HASH buckets size overflow")?; | |
| let chains_off = | |
| buckets_off.checked_add(buckets_bytes).ok_or("DT_GNU_HASH chains overflow")?; | |
| let buckets_slice = | |
| tail.get(buckets_off..chains_off).ok_or("truncated DT_GNU_HASH buckets")?; | |
| let mut max_sym = 0u32; | |
| for chunk in buckets_slice.as_chunks::<4>().0 { | |
| let b = u32::from_le_bytes(*chunk); | |
| if b != 0 && b < symoffset { | |
| return Err(format!("DT_GNU_HASH bucket symbol {b} < symoffset {symoffset}")); | |
| } | |
| if b > max_sym { | |
| max_sym = b; | |
| } | |
| } | |
| if max_sym == 0 { | |
| return Ok(u64::from(symoffset)); | |
| } | |
| let chains = tail.get(chains_off..).ok_or("truncated DT_GNU_HASH chains")?; | |
| let mut idx = usize::try_from(max_sym - symoffset).map_err(|_| "chain index overflow")?; | |
| loop { | |
| let off = idx.checked_mul(4).ok_or("DT_GNU_HASH chain offset overflow")?; | |
| let entry = read_u32(chains, off)?; | |
| if (entry & 1) != 0 { | |
| let last_sym = u64::from(symoffset) | |
| .checked_add(u64::try_from(idx).map_err(|_| "chain index overflow")?) | |
| .and_then(|v| v.checked_add(1)) | |
| .ok_or("DT_GNU_HASH symbol count overflow")?; | |
| return Ok(last_sym); | |
| } | |
| idx = idx.checked_add(1).ok_or("DT_GNU_HASH chain index overflow")?; | |
| } | |
| } | |
| } | |
| fn dyn_reloc_width(arch: Arch, r_type: u32, sym: Option<&DynSymInfo>) -> Result<u64, String> { | |
| match (arch, r_type) { | |
| (Arch::X86_64, R_X86_64_TLSDESC) | (Arch::AArch64, R_AARCH64_TLSDESC) => Ok(16), | |
| (Arch::X86_64, R_X86_64_COPY) | (Arch::AArch64, R_AARCH64_COPY) => { | |
| let sz = sym.map_or(0, |s| s.st_size); | |
| if sz == 0 { | |
| return Err("COPY dynamic relocation has missing or zero symbol st_size".to_owned()); | |
| } | |
| Ok(sz) | |
| } | |
| _ => Ok(8), | |
| } | |
| } | |
| fn parse_gnu_property_notes(data: &[u8], props: &mut GnuProperties) -> Result<(), String> { | |
| let mut off = 0usize; | |
| let mut saw_gnu_prop_note = false; | |
| while off < data.len() { | |
| if off + 12 > data.len() { | |
| return Err("truncated .note.gnu.property note header".to_owned()); | |
| } | |
| let namesz = usize::try_from(read_u32(data, off)?).map_err(|_| "namesz overflow")?; | |
| let descsz = usize::try_from(read_u32(data, off + 4)?).map_err(|_| "descsz overflow")?; | |
| let ntype = read_u32(data, off + 8)?; | |
| let name_start = off + 12; | |
| let name_end = name_start.checked_add(namesz).ok_or("note name overflow")?; | |
| let name = | |
| data.get(name_start..name_end).ok_or("truncated note name in .note.gnu.property")?; | |
| let desc_start = align_up(name_end, 8)?; | |
| let desc_end = desc_start.checked_add(descsz).ok_or("note desc overflow")?; | |
| let desc = | |
| data.get(desc_start..desc_end).ok_or("truncated note desc in .note.gnu.property")?; | |
| if ntype == NT_GNU_PROPERTY_TYPE_0 && name == b"GNU\0" { | |
| if saw_gnu_prop_note { | |
| return Err("duplicate NT_GNU_PROPERTY_TYPE_0 note in PT_GNU_PROPERTY".to_owned()); | |
| } | |
| saw_gnu_prop_note = true; | |
| let mut poff = 0usize; | |
| let mut prev_pr_type: Option<u32> = None; | |
| while poff < desc.len() { | |
| if poff + 8 > desc.len() { | |
| return Err("truncated GNU property entry header".to_owned()); | |
| } | |
| let pr_type = read_u32(desc, poff)?; | |
| let pr_datasz = | |
| usize::try_from(read_u32(desc, poff + 4)?).map_err(|_| "pr_datasz overflow")?; | |
| if let Some(prev) = prev_pr_type { | |
| if pr_type <= prev { | |
| return Err(format!( | |
| "unsorted or duplicate GNU property pr_type 0x{pr_type:x} after 0x{prev:x}" | |
| )); | |
| } | |
| } | |
| prev_pr_type = Some(pr_type); | |
| let pdata_start = poff + 8; | |
| let pdata_end = | |
| pdata_start.checked_add(pr_datasz).ok_or("property data overflow")?; | |
| let pdata = | |
| desc.get(pdata_start..pdata_end).ok_or("truncated GNU property data")?; | |
| let next_poff = align_up(pdata_end, 8)?; | |
| if next_poff > desc.len() { | |
| return Err("truncated padding in GNU property entry".to_owned()); | |
| } | |
| if pr_type == GNU_PROPERTY_X86_FEATURE_1_AND { | |
| if pr_datasz != 4 { | |
| return Err(format!( | |
| "invalid GNU_PROPERTY_X86_FEATURE_1_AND pr_datasz {pr_datasz} (expected 4)" | |
| )); | |
| } | |
| let bits = read_u32(pdata, 0)?; | |
| props.x86_ibt = (bits & GNU_PROPERTY_X86_FEATURE_1_IBT) != 0; | |
| props.x86_shstk = (bits & GNU_PROPERTY_X86_FEATURE_1_SHSTK) != 0; | |
| } else if pr_type == GNU_PROPERTY_AARCH64_FEATURE_1_AND { | |
| if pr_datasz != 4 { | |
| return Err(format!( | |
| "invalid GNU_PROPERTY_AARCH64_FEATURE_1_AND pr_datasz {pr_datasz} (expected 4)" | |
| )); | |
| } | |
| let bits = read_u32(pdata, 0)?; | |
| props.aarch64_bti = (bits & GNU_PROPERTY_AARCH64_FEATURE_1_BTI) != 0; | |
| props.aarch64_pac = (bits & GNU_PROPERTY_AARCH64_FEATURE_1_PAC) != 0; | |
| } | |
| poff = next_poff; | |
| } | |
| } | |
| let next_off = align_up(desc_end, 8)?; | |
| if next_off > data.len() { | |
| return Err("truncated padding after note in PT_GNU_PROPERTY".to_owned()); | |
| } | |
| off = next_off; | |
| } | |
| Ok(()) | |
| } | |
| fn parse_dyn_rela_slice( | |
| data: &[u8], | |
| source: &str, | |
| arch: Arch, | |
| resolve: &dyn Fn(u32) -> Result<Option<DynSymInfo>, String>, | |
| out: &mut Vec<DynReloc>, | |
| ) -> Result<(), String> { | |
| let count = data.len() / ELF64_RELA_SIZE; | |
| for i in 0..count { | |
| let off = i * ELF64_RELA_SIZE; | |
| let r_offset = read_u64(data, off)?; | |
| let r_info = read_u64(data, off + 8)?; | |
| let r_addend = read_i64(data, off + 16)?; | |
| let r_sym = (r_info >> 32) as u32; | |
| let r_type = (r_info & 0xffff_ffff) as u32; | |
| if r_type == 0 { | |
| continue; | |
| } | |
| let sym = resolve(r_sym)?; | |
| let width = dyn_reloc_width(arch, r_type, sym.as_ref())?; | |
| out.push(DynReloc { | |
| r_offset, | |
| r_type, | |
| r_addend, | |
| width, | |
| from_relr: false, | |
| sym_info: sym, | |
| source: source.to_owned(), | |
| }); | |
| } | |
| Ok(()) | |
| } | |
| fn parse_dyn_rel_slice( | |
| data: &[u8], | |
| source: &str, | |
| arch: Arch, | |
| resolve: &dyn Fn(u32) -> Result<Option<DynSymInfo>, String>, | |
| out: &mut Vec<DynReloc>, | |
| ) -> Result<(), String> { | |
| let count = data.len() / ELF64_REL_SIZE; | |
| for i in 0..count { | |
| let off = i * ELF64_REL_SIZE; | |
| let r_offset = read_u64(data, off)?; | |
| let r_info = read_u64(data, off + 8)?; | |
| let r_sym = (r_info >> 32) as u32; | |
| let r_type = (r_info & 0xffff_ffff) as u32; | |
| if r_type == 0 { | |
| continue; | |
| } | |
| let sym = resolve(r_sym)?; | |
| let width = dyn_reloc_width(arch, r_type, sym.as_ref())?; | |
| out.push(DynReloc { | |
| r_offset, | |
| r_type, | |
| r_addend: 0, | |
| width, | |
| from_relr: false, | |
| sym_info: sym, | |
| source: source.to_owned(), | |
| }); | |
| } | |
| Ok(()) | |
| } | |
| fn parse_dyn_relr_slice( | |
| data: &[u8], | |
| source: &str, | |
| arch: Arch, | |
| out: &mut Vec<DynReloc>, | |
| ) -> Result<(), String> { | |
| let rel_type = match arch { | |
| Arch::X86_64 => R_X86_64_RELATIVE, | |
| Arch::AArch64 => R_AARCH64_RELATIVE, | |
| }; | |
| let mut where_va: Option<u64> = None; | |
| for chunk in data.as_chunks::<8>().0 { | |
| let entry = u64::from_le_bytes(*chunk); | |
| if (entry & 1) == 0 { | |
| out.push(DynReloc { | |
| r_offset: entry, | |
| r_type: rel_type, | |
| r_addend: 0, | |
| width: 8, | |
| from_relr: true, | |
| sym_info: None, | |
| source: source.to_owned(), | |
| }); | |
| where_va = Some(entry.checked_add(8).ok_or("DT_RELR base address overflow")?); | |
| } else { | |
| let base = where_va.ok_or("DT_RELR bitmap appeared before any base address")?; | |
| let mut bitmap = entry >> 1; | |
| for bit in 0u64..63 { | |
| if (bitmap & 1) != 0 { | |
| let slot = base.checked_add(bit * 8).ok_or("DT_RELR bitmap slot overflow")?; | |
| out.push(DynReloc { | |
| r_offset: slot, | |
| r_type: rel_type, | |
| r_addend: 0, | |
| width: 8, | |
| from_relr: true, | |
| sym_info: None, | |
| source: source.to_owned(), | |
| }); | |
| } | |
| bitmap >>= 1; | |
| } | |
| where_va = Some(base.checked_add(63 * 8).ok_or("DT_RELR cursor advance overflow")?); | |
| } | |
| } | |
| Ok(()) | |
| } | |
| fn section_bytes_raw<'a>(bytes: &'a [u8], sh: &SectionHeader) -> Result<&'a [u8], String> { | |
| if (sh.sh_flags & SHF_COMPRESSED) != 0 { | |
| return Err(format!("section `{}` is SHF_COMPRESSED (unsupported)", sh.name)); | |
| } | |
| slice_u64(bytes, sh.sh_offset, sh.sh_size) | |
| } | |
| fn parse_symtab_kind( | |
| bytes: &[u8], | |
| shdrs: &[SectionHeader], | |
| kind: u32, | |
| ) -> Result<Vec<Symbol>, String> { | |
| let symtabs: Vec<&SectionHeader> = shdrs.iter().filter(|s| s.sh_type == kind).collect(); | |
| if symtabs.is_empty() { | |
| return Ok(Vec::new()); | |
| } | |
| if symtabs.len() > 1 { | |
| return Err(format!("multiple symbol tables of type {kind}")); | |
| } | |
| let sym_sh = symtabs[0]; | |
| if usize::try_from(sym_sh.sh_entsize).unwrap_or(0) != ELF64_SYM_SIZE { | |
| return Err(format!( | |
| "unexpected symtab `{}` sh_entsize {}", | |
| sym_sh.name, sym_sh.sh_entsize | |
| )); | |
| } | |
| if !sym_sh.sh_size.is_multiple_of(ELF64_SYM_SIZE as u64) { | |
| return Err(format!("symtab `{}` size not a multiple of 24", sym_sh.name)); | |
| } | |
| let str_idx = usize::try_from(sym_sh.sh_link).map_err(|_| "sh_link exceeds usize")?; | |
| let str_sh = shdrs | |
| .get(str_idx) | |
| .ok_or_else(|| format!("symtab `{}` sh_link {str_idx} out of bounds", sym_sh.name))?; | |
| if str_sh.sh_type != SHT_STRTAB { | |
| return Err(format!("symtab `{}` sh_link is not SHT_STRTAB", sym_sh.name)); | |
| } | |
| let sym_bytes = section_bytes_raw(bytes, sym_sh)?; | |
| let str_bytes = section_bytes_raw(bytes, str_sh)?; | |
| let shndx_bytes: Option<&[u8]> = match shdrs | |
| .iter() | |
| .find(|s| s.sh_type == SHT_SYMTAB_SHNDX && s.sh_link as usize == sym_sh.index) | |
| { | |
| Some(sh) => Some(section_bytes_raw(bytes, sh)?), | |
| None => None, | |
| }; | |
| let count = sym_bytes.len() / ELF64_SYM_SIZE; | |
| let mut out = Vec::with_capacity(count); | |
| for i in 0..count { | |
| let off = i * ELF64_SYM_SIZE; | |
| let st_name = read_u32(sym_bytes, off)?; | |
| let st_info = sym_bytes[off + 4]; | |
| let st_other = sym_bytes[off + 5]; | |
| let raw_shndx = read_u16(sym_bytes, off + 6)?; | |
| let st_shndx = if raw_shndx == SHN_XINDEX { | |
| let table = | |
| shndx_bytes.ok_or("symbol uses SHN_XINDEX without SHT_SYMTAB_SHNDX section")?; | |
| read_u32(table, i * 4)? | |
| } else { | |
| u32::from(raw_shndx) | |
| }; | |
| let st_value = read_u64(sym_bytes, off + 8)?; | |
| let st_size = read_u64(sym_bytes, off + 16)?; | |
| let name = read_cstr(str_bytes, st_name)?; | |
| out.push(Symbol { | |
| index: i, | |
| name, | |
| st_info, | |
| st_other, | |
| raw_shndx, | |
| st_shndx, | |
| st_value, | |
| st_size, | |
| }); | |
| } | |
| Ok(out) | |
| } | |
| fn parse_relas( | |
| bytes: &[u8], | |
| shdrs: &[SectionHeader], | |
| e_type: ElfType, | |
| ) -> Result<Vec<RelaSection>, String> { | |
| let mut out: Vec<RelaSection> = Vec::new(); | |
| for sh in shdrs { | |
| if sh.sh_type != SHT_RELA { | |
| continue; | |
| } | |
| if usize::try_from(sh.sh_entsize).unwrap_or(0) != ELF64_RELA_SIZE { | |
| return Err(format!( | |
| "section `{}` has unexpected SHT_RELA sh_entsize {}", | |
| sh.name, sh.sh_entsize | |
| )); | |
| } | |
| if !sh.sh_size.is_multiple_of(ELF64_RELA_SIZE as u64) { | |
| return Err(format!("section `{}` size not a multiple of 24", sh.name)); | |
| } | |
| let target = usize::try_from(sh.sh_info).map_err(|_| "sh_info exceeds usize")?; | |
| if target >= shdrs.len() { | |
| return Err(format!("SHT_RELA `{}` targets out-of-bounds section {target}", sh.name)); | |
| } | |
| if e_type == ElfType::Rel && out.iter().any(|s| s.target_sec == target) { | |
| return Err(format!("duplicate SHT_RELA targeting section {target}")); | |
| } | |
| let data = section_bytes_raw(bytes, sh)?; | |
| let count = data.len() / ELF64_RELA_SIZE; | |
| let mut entries = Vec::with_capacity(count); | |
| for i in 0..count { | |
| let off = i * ELF64_RELA_SIZE; | |
| let r_offset = read_u64(data, off)?; | |
| let r_info = read_u64(data, off + 8)?; | |
| let r_addend = read_i64(data, off + 16)?; | |
| entries.push(Rela { | |
| r_offset, | |
| r_sym: (r_info >> 32) as u32, | |
| r_type: (r_info & 0xffff_ffff) as u32, | |
| r_addend, | |
| }); | |
| } | |
| out.push(RelaSection { | |
| sh_name: sh.name.clone(), | |
| sh_link: sh.sh_link, | |
| target_sec: target, | |
| entries, | |
| }); | |
| } | |
| Ok(out) | |
| } | |
| fn decode_uleb128(data: &[u8]) -> Result<(u64, usize), String> { | |
| let mut val = 0u64; | |
| let mut shift = 0u32; | |
| for (idx, &byte) in data.iter().enumerate() { | |
| let low = u64::from(byte & 0x7f); | |
| if shift >= 64 || (shift == 63 && low > 1) { | |
| return Err("ULEB128 overflow in .stack_sizes".to_owned()); | |
| } | |
| val |= low << shift; | |
| if (byte & 0x80) == 0 { | |
| return Ok((val, idx + 1)); | |
| } | |
| shift += 7; | |
| } | |
| Err("unterminated ULEB128 in .stack_sizes".to_owned()) | |
| } |