Skip to main content

wazabin_binary/
elf.rs

1use elf::{
2    ElfBytes,
3    abi::{
4        DT_NEEDED, EM_386, EM_X86_64, ET_CORE, ET_DYN, ET_EXEC, ET_REL, PF_W, PF_X, PT_LOAD,
5        PT_PHDR, PT_TLS, R_X86_64_GLOB_DAT, R_X86_64_JUMP_SLOT, SHF_ALLOC, SHF_EXECINSTR,
6        SHF_WRITE, SHT_DYNSYM, SHT_NOBITS, SHT_REL, SHT_RELA, SHT_SYMTAB, STT_FUNC,
7    },
8    endian::{AnyEndian, EndianParse},
9};
10
11use crate::{Arch, BinaryFormat, Endian, Section, Symbol};
12
13use crate::symbols::SymbolIndex;
14
15/// A known function start address extracted from an ELF symbol table.
16#[derive(Debug, Clone)]
17pub struct FunctionSymbol {
18    /// Virtual address of the function.
19    pub address: u64,
20    /// Name from the string table, if present.
21    pub name: Option<String>,
22    /// `st_size` when the symbol table records a non-zero one. `None` for
23    /// PLT stubs, `.eh_frame` starts, and assembly symbols with no `.size`.
24    pub size: Option<u64>,
25    /// Whether this is an external (imported) function stub (e.g. a PLT thunk).
26    pub is_external: bool,
27    /// For an external stub, the shared library its symbol-version requirement
28    /// (`.gnu.version_r`) names, e.g. `libc.so.6`. `None` for unversioned
29    /// imports (the format does not tie those to a specific `DT_NEEDED` entry).
30    pub library: Option<String>,
31}
32
33/// A resolver slot for an imported function.
34#[derive(Debug, Clone)]
35pub struct ImportSymbol {
36    /// Virtual address of the GOT / PLT relocation slot.
37    pub address: u64,
38    /// Imported function name.
39    pub name: String,
40    /// The shared library the symbol's version requirement (`.gnu.version_r`)
41    /// names, e.g. `libc.so.6`. `None` for unversioned imports.
42    pub library: Option<String>,
43}
44
45/// Results of the ELF analysis passes.
46#[derive(Debug, Clone)]
47pub struct ElfAnalysis {
48    /// The binary entry point (`e_entry` from the ELF header).
49    pub entrypoint: u64,
50    /// Function start addresses discovered via `.symtab` / `.dynsym`.
51    pub known_functions: Vec<FunctionSymbol>,
52    /// Imported functions keyed by resolver slot address.
53    pub imported_symbols: Vec<ImportSymbol>,
54}
55
56#[derive(Debug, Clone)]
57pub struct LoadSegment {
58    pub start: u64,
59    pub mem_size: u64,
60    pub data: Vec<u8>,
61    /// Whether the segment is executable (`PF_X` set in `p_flags`).
62    pub executable: bool,
63    /// Whether the segment is writable (`PF_W` set in `p_flags`).
64    pub writable: bool,
65    /// The segment's alignment (`p_align`); zero or one means none.
66    pub align: u64,
67}
68
69/// An allocated section header (`SHF_ALLOC` set): a named slice of the
70/// loaded image such as `.text` or `.bss`. Absent from a file whose section
71/// table was stripped, which loaders never need.
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct ElfSection {
74    /// The name from `.shstrtab`.
75    pub name: String,
76    /// `sh_addr`.
77    pub address: u64,
78    /// `sh_size`.
79    pub size: u64,
80    /// `SHF_WRITE`.
81    pub writable: bool,
82    /// `SHF_EXECINSTR`.
83    pub executable: bool,
84    /// `SHT_NOBITS`: the section occupies no file bytes and is zero-filled
85    /// by the loader (`.bss`, `.tbss`).
86    pub nobits: bool,
87}
88
89/// The file type from `e_type`: what kind of object this is, and so whether
90/// a loader may place it where it likes.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum ElfKind {
93    /// `ET_EXEC`: linked to run at its segments' addresses.
94    Executable,
95    /// `ET_DYN`: a shared object or a position-independent executable; the
96    /// loader chooses the base and adds it to every address.
97    SharedObject,
98    /// `ET_REL`: an unlinked object file.
99    Relocatable,
100    /// `ET_CORE`: a core dump.
101    Core,
102    /// Anything else, with the raw `e_type`.
103    Other(u16),
104}
105
106impl ElfKind {
107    fn from_e_type(value: u16) -> Self {
108        match value {
109            ET_EXEC => ElfKind::Executable,
110            ET_DYN => ElfKind::SharedObject,
111            ET_REL => ElfKind::Relocatable,
112            ET_CORE => ElfKind::Core,
113            other => ElfKind::Other(other),
114        }
115    }
116}
117
118/// Where the program header table is, in the file and, when a segment
119/// covers it, in memory. A loader passes the virtual address to the program
120/// as `AT_PHDR`; libc startup and the dynamic linker walk the table from
121/// there.
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub struct ProgramHeaderTable {
124    /// `e_phoff`.
125    pub offset: u64,
126    /// `e_phentsize`.
127    pub entry_size: u16,
128    /// `e_phnum`.
129    pub count: u16,
130    /// The table's unrelocated virtual address: what `PT_PHDR` names, else
131    /// the address inside the `PT_LOAD` segment whose file bytes cover
132    /// `offset`. `None` when no segment maps it.
133    pub vaddr: Option<u64>,
134}
135
136/// The `PT_TLS` segment: the thread-local storage template a runtime copies
137/// for each thread. At most one per file.
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub struct TlsSegment {
140    /// Unrelocated virtual address of the template.
141    pub vaddr: u64,
142    /// Bytes of the template that come from the file (`.tdata`).
143    pub file_size: u64,
144    /// Total size, the tail being zero-filled (`.tbss`).
145    pub mem_size: u64,
146    /// `p_align`.
147    pub align: u64,
148}
149
150impl LoadSegment {
151    fn end(&self) -> u64 {
152        self.start + self.mem_size
153    }
154
155    fn contains(&self, addr: u64) -> bool {
156        addr >= self.start && addr < self.end()
157    }
158
159    fn byte_at(&self, addr: u64) -> Option<u8> {
160        if !self.contains(addr) {
161            return None;
162        }
163        let offset = (addr - self.start) as usize;
164        Some(self.data.get(offset).copied().unwrap_or(0))
165    }
166
167    fn bytes_at(&self, addr: u64) -> Option<&[u8]> {
168        if !self.contains(addr) {
169            return None;
170        }
171
172        let offset = (addr - self.start) as usize;
173
174        self.data.get(offset..)
175    }
176}
177
178/// A parsed and loaded ELF binary.
179///
180/// Every `PT_LOAD` segment is recorded as a mapped region. File-backed bytes
181/// are preserved per segment, and any `p_memsz > p_filesz` tail is modeled as
182/// implicit zero-fill rather than materialized up front.
183///
184/// [`ElfBinary::analysis`] is populated by two analysis passes run at parse
185/// time:
186/// - **Entrypoint**: `e_entry` from the ELF header.
187/// - **Known functions**: all `STT_FUNC` symbols found in `.symtab` or
188///   `.dynsym`, PLT stubs, and every `.eh_frame` FDE start (nameless, but
189///   they survive `strip`).
190///
191/// `known_functions` and `imported_symbols` are sorted by address with one
192/// entry per address, and a name index is built alongside them, which is
193/// what the [`BinaryFormat::symbol_name`] / [`BinaryFormat::symbol_address`]
194/// lookups search. Both hold once parsing returns; mutating the tables
195/// afterwards is not supported.
196#[derive(Debug, Clone)]
197pub struct ElfBinary {
198    pub load_address: u64,
199    pub segments: Vec<LoadSegment>,
200    pub analysis: ElfAnalysis,
201    /// Function names -> addresses, over `analysis.known_functions`.
202    symbols: SymbolIndex,
203    pub architecture: Arch,
204    /// `EI_DATA`: the byte order every multi-byte field was read with.
205    pub endian: Endian,
206    /// `EI_CLASS`: `true` for ELF64, `false` for ELF32.
207    pub is_64: bool,
208    /// The allocated section headers in address order, empty when the
209    /// section table was stripped. What [`BinaryFormat::sections`] reports.
210    pub sections: Vec<ElfSection>,
211    /// Shared-library sonames from the `.dynamic` section's `DT_NEEDED` entries,
212    /// in link order (e.g. `libc.so.6`).
213    pub needed_libraries: Vec<String>,
214    /// The file type.
215    pub kind: ElfKind,
216    /// The program header table's location.
217    pub program_headers: ProgramHeaderTable,
218    /// The thread-local storage template, if the file has one.
219    pub tls: Option<TlsSegment>,
220}
221
222/// Errors that can occur while parsing an ELF binary.
223#[derive(Debug)]
224pub enum ElfError {
225    /// The underlying `elf` crate returned an error.
226    Parse(elf::ParseError),
227    /// The ELF file contains no loadable (`PT_LOAD`) segment.
228    NoLoadableSegment,
229    /// The ELF file header number does not match any arch
230    UnknownArch,
231}
232
233impl std::fmt::Display for ElfError {
234    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235        match self {
236            ElfError::Parse(e) => write!(f, "ELF parse error: {e}"),
237            ElfError::NoLoadableSegment => write!(f, "ELF contains no PT_LOAD segment"),
238            ElfError::UnknownArch => write!(f, "ELF has an unknown arch"),
239        }
240    }
241}
242
243impl std::error::Error for ElfError {}
244
245impl From<elf::ParseError> for ElfError {
246    fn from(e: elf::ParseError) -> Self {
247        ElfError::Parse(e)
248    }
249}
250
251impl ElfBinary {
252    /// Parse an ELF binary from raw file bytes.
253    ///
254    /// Records every `PT_LOAD` segment as a mapped region, reads the entrypoint
255    /// from the ELF header, and collects all `STT_FUNC` symbols from `.symtab`
256    /// and `.dynsym`.
257    pub fn parse(file_bytes: &[u8]) -> Result<Self, ElfError> {
258        let elf = ElfBytes::<AnyEndian>::minimal_parse(file_bytes)?;
259
260        // --- Load the first PT_LOAD segment ---------------------------------
261        let segments = elf.segments().ok_or(ElfError::NoLoadableSegment)?;
262
263        let mut load_segments: Vec<_> = segments
264            .iter()
265            .filter(|p| p.p_type == PT_LOAD && p.p_memsz > 0)
266            .map(|p| {
267                let offset = p.p_offset as usize;
268                let filesz = p.p_filesz as usize;
269                let data = file_bytes
270                    .get(offset..offset + filesz)
271                    .unwrap_or(&[])
272                    .to_vec();
273                LoadSegment {
274                    start: p.p_vaddr,
275                    mem_size: p.p_memsz,
276                    data,
277                    executable: p.p_flags & PF_X != 0,
278                    writable: p.p_flags & PF_W != 0,
279                    align: p.p_align,
280                }
281            })
282            .collect();
283
284        if load_segments.is_empty() {
285            return Err(ElfError::NoLoadableSegment);
286        }
287        load_segments.sort_by_key(|s| s.start);
288        let load_address = load_segments[0].start;
289
290        // --- Analysis pass 1: entrypoint ------------------------------------
291        let entrypoint = elf.ehdr.e_entry;
292
293        // --- Analysis pass 2: known function starts -------------------------
294        let mut known_functions: Vec<FunctionSymbol> = Vec::new();
295        collect_func_symbols(&elf, SHT_SYMTAB, &mut known_functions);
296        collect_func_symbols(&elf, SHT_DYNSYM, &mut known_functions);
297
298        // --- Analysis pass 3: PLT stub names -----------------------------------
299        collect_plt_symbols(&elf, &mut known_functions);
300
301        // --- Analysis pass 4: GOT / PLT resolver slots -------------------------
302        let mut imported_symbols = Vec::new();
303        collect_import_symbols(&elf, &mut imported_symbols);
304
305        // --- Analysis pass 5: DT_NEEDED shared-library sonames -----------------
306        let needed_libraries = collect_needed_libraries(&elf);
307
308        // --- Analysis pass 6: `.eh_frame` FDE starts ---------------------------
309        // Pushed last so a named symbol at the same address wins the dedup
310        // below. Skipped for the PLT stub tables (their FDE covers the whole
311        // table, and the stubs are already listed by name) and for anything
312        // outside executable memory (a stale FDE in a hand-edited binary).
313        let plt_ranges = plt_section_ranges(&elf);
314        for addr in crate::eh_frame::function_starts(&elf, file_bytes) {
315            let in_plt = plt_ranges.iter().any(|(s, e)| addr >= *s && addr < *e);
316            let executable = load_segments
317                .iter()
318                .any(|seg| seg.executable && seg.contains(addr));
319            if !in_plt && executable {
320                known_functions.push(FunctionSymbol {
321                    address: addr,
322                    name: None,
323                    size: None,
324                    is_external: false,
325                    library: None,
326                });
327            }
328        }
329
330        // --- Analysis pass 7: constructor / destructor entry points -----------
331        // The crt functions `frame_dummy` and `__do_global_dtors_aux` have no
332        // FDE, but the loader reaches them through `.init_array` /
333        // `.fini_array` (and `DT_INIT` / `DT_FINI`), so those pointer tables
334        // are function starts too.
335        for addr in init_fini_entries(&elf, &load_segments) {
336            let executable = load_segments
337                .iter()
338                .any(|seg| seg.executable && seg.contains(addr));
339            if executable {
340                known_functions.push(FunctionSymbol {
341                    address: addr,
342                    name: None,
343                    size: None,
344                    is_external: false,
345                    library: None,
346                });
347            }
348        }
349
350        // --- The section table, for callers that want names -------------------
351        let sections = collect_sections(&elf);
352
353        // --- What a loader needs beyond the segments ---------------------------
354        let endian = if elf.ehdr.endianness.is_little() {
355            Endian::Little
356        } else {
357            Endian::Big
358        };
359        let is_64 = matches!(elf.ehdr.class, elf::file::Class::ELF64);
360        let kind = ElfKind::from_e_type(elf.ehdr.e_type);
361        let phoff = elf.ehdr.e_phoff;
362        let phdr_vaddr = segments
363            .iter()
364            .find(|p| p.p_type == PT_PHDR)
365            .map(|p| p.p_vaddr)
366            .or_else(|| {
367                segments
368                    .iter()
369                    .filter(|p| p.p_type == PT_LOAD)
370                    .find(|p| phoff >= p.p_offset && phoff < p.p_offset + p.p_filesz)
371                    .map(|p| p.p_vaddr + (phoff - p.p_offset))
372            });
373        let program_headers = ProgramHeaderTable {
374            offset: phoff,
375            entry_size: elf.ehdr.e_phentsize,
376            count: elf.ehdr.e_phnum,
377            vaddr: phdr_vaddr,
378        };
379        let tls = segments
380            .iter()
381            .find(|p| p.p_type == PT_TLS)
382            .map(|p| TlsSegment {
383                vaddr: p.p_vaddr,
384                file_size: p.p_filesz,
385                mem_size: p.p_memsz,
386                align: p.p_align,
387            });
388
389        // Deduplicate by address (symtab may overlap dynsym). The sorted
390        // order is what `function_at` / `import_at` binary-search.
391        known_functions.sort_by_key(|f| f.address);
392        known_functions.dedup_by_key(|f| f.address);
393        imported_symbols.sort_by_key(|f| f.address);
394        imported_symbols.dedup_by_key(|f| f.address);
395        let symbols = SymbolIndex::build(
396            known_functions
397                .iter()
398                .map(|f| (f.name.as_deref(), f.address, f.is_external)),
399        );
400
401        Ok(ElfBinary {
402            load_address,
403            segments: load_segments,
404            analysis: ElfAnalysis {
405                entrypoint,
406                known_functions,
407                imported_symbols,
408            },
409            symbols,
410            architecture: from_elf_machine(elf.ehdr.e_machine).ok_or(ElfError::UnknownArch)?,
411            endian,
412            is_64,
413            sections,
414            needed_libraries,
415            kind,
416            program_headers,
417            tls,
418        })
419    }
420
421    /// The known function starting at `addr`, by binary search over the
422    /// address-sorted table.
423    fn function_at(&self, addr: u64) -> Option<&FunctionSymbol> {
424        let functions = &self.analysis.known_functions;
425        let idx = functions.binary_search_by_key(&addr, |f| f.address).ok()?;
426        Some(&functions[idx])
427    }
428
429    /// The imported symbol whose resolver slot is at `addr`, by binary search
430    /// over the address-sorted table.
431    fn import_at(&self, addr: u64) -> Option<&ImportSymbol> {
432        let imports = &self.analysis.imported_symbols;
433        let idx = imports.binary_search_by_key(&addr, |f| f.address).ok()?;
434        Some(&imports[idx])
435    }
436}
437
438/// The `SHF_ALLOC` section headers with a name, in address order. Empty when
439/// the file has no section table or no `.shstrtab`.
440fn collect_sections(elf: &ElfBytes<AnyEndian>) -> Vec<ElfSection> {
441    let (shdrs, shstrtab) = match elf.section_headers_with_strtab() {
442        Ok((Some(s), Some(st))) => (s, st),
443        _ => return Vec::new(),
444    };
445    let mut out: Vec<ElfSection> = shdrs
446        .iter()
447        .filter(|s| s.sh_flags & u64::from(SHF_ALLOC) != 0)
448        .filter_map(|s| {
449            let name = shstrtab.get(s.sh_name as usize).ok()?;
450            Some(ElfSection {
451                name: name.to_owned(),
452                address: s.sh_addr,
453                size: s.sh_size,
454                writable: s.sh_flags & u64::from(SHF_WRITE) != 0,
455                executable: s.sh_flags & u64::from(SHF_EXECINSTR) != 0,
456                nobits: s.sh_type == SHT_NOBITS,
457            })
458        })
459        .collect();
460    out.sort_by_key(|s| s.address);
461    out
462}
463
464/// `[start, end)` virtual ranges of the PLT stub tables (`.plt`, `.plt.sec`,
465/// `.plt.got`), for excluding their FDEs from function discovery.
466fn plt_section_ranges(elf: &ElfBytes<AnyEndian>) -> Vec<(u64, u64)> {
467    let (shdrs, shstrtab) = match elf.section_headers_with_strtab() {
468        Ok((Some(s), Some(st))) => (s, st),
469        _ => return Vec::new(),
470    };
471    shdrs
472        .iter()
473        .filter(|s| {
474            matches!(
475                shstrtab.get(s.sh_name as usize).ok(),
476                Some(".plt" | ".plt.sec" | ".plt.got")
477            )
478        })
479        .map(|s| (s.sh_addr, s.sh_addr + s.sh_size))
480        .collect()
481}
482
483/// Function pointers stored in `.preinit_array` / `.init_array` /
484/// `.fini_array`, plus the `DT_INIT` / `DT_FINI` dynamic entries. Read from
485/// the loaded image, so a non-PIE binary yields absolute addresses and a PIE
486/// (whose slots hold `R_X86_64_RELATIVE` addends) its link-time ones.
487fn init_fini_entries(elf: &ElfBytes<AnyEndian>, segments: &[LoadSegment]) -> Vec<u64> {
488    let ptr_size = match elf.ehdr.class {
489        elf::file::Class::ELF32 => 4,
490        elf::file::Class::ELF64 => 8,
491    };
492    let read_ptr = |addr: u64| -> Option<u64> {
493        let seg = segments.iter().find(|s| s.contains(addr))?;
494        let bytes = seg.bytes_at(addr)?;
495        match ptr_size {
496            4 => Some(u64::from(u32::from_le_bytes(bytes.get(..4)?.try_into().ok()?))),
497            _ => Some(u64::from_le_bytes(bytes.get(..8)?.try_into().ok()?)),
498        }
499    };
500    let mut out = Vec::new();
501    if let Ok((Some(shdrs), Some(shstrtab))) = elf.section_headers_with_strtab() {
502        for shdr in shdrs.iter() {
503            if !matches!(
504                shstrtab.get(shdr.sh_name as usize).ok(),
505                Some(".preinit_array" | ".init_array" | ".fini_array")
506            ) {
507                continue;
508            }
509            let mut slot = shdr.sh_addr;
510            let end = shdr.sh_addr.saturating_add(shdr.sh_size);
511            while slot + ptr_size as u64 <= end {
512                match read_ptr(slot) {
513                    // `0` and `-1` are the linker's empty / sentinel slots.
514                    Some(0) | Some(u64::MAX) | None => {}
515                    Some(target) => out.push(target),
516                }
517                slot += ptr_size as u64;
518            }
519        }
520    }
521    if let Ok(Some(dynamic)) = elf.dynamic() {
522        for entry in dynamic.iter() {
523            if (entry.d_tag == elf::abi::DT_INIT || entry.d_tag == elf::abi::DT_FINI)
524                && entry.d_ptr() != 0
525            {
526                out.push(entry.d_ptr());
527            }
528        }
529    }
530    out
531}
532
533/// Collect `DT_NEEDED` shared-library sonames from the `.dynamic` section,
534/// resolving each entry's string-table offset against `.dynstr`. Returns an
535/// empty vector for statically linked binaries (no dynamic section).
536fn collect_needed_libraries(elf: &ElfBytes<AnyEndian>) -> Vec<String> {
537    let mut out = Vec::new();
538    let Some((_symtab, dynstr)) = elf.dynamic_symbol_table().ok().flatten() else {
539        return out;
540    };
541    let Ok(Some(dynamic)) = elf.dynamic() else {
542        return out;
543    };
544    for entry in dynamic.iter() {
545        if entry.d_tag == DT_NEEDED
546            && let Ok(name) = dynstr.get(entry.d_val() as usize)
547            && !name.is_empty()
548        {
549            out.push(name.to_owned());
550        }
551    }
552    out
553}
554
555/// Collect all `STT_FUNC` symbols from the section matching `section_type`
556/// (either `SHT_SYMTAB` or `SHT_DYNSYM`) into `out`.
557fn collect_func_symbols(
558    elf: &ElfBytes<AnyEndian>,
559    section_type: u32,
560    out: &mut Vec<FunctionSymbol>,
561) {
562    if section_type == SHT_SYMTAB {
563        let Ok(Some((symtab, strtab))) = elf.symbol_table() else {
564            return;
565        };
566        for sym in symtab.iter() {
567            if sym.st_symtype() == STT_FUNC && sym.st_value != 0 {
568                let name = strtab.get(sym.st_name as usize).ok().map(str::to_owned);
569                out.push(FunctionSymbol {
570                    address: sym.st_value,
571                    name,
572                    size: (sym.st_size != 0).then_some(sym.st_size),
573                    is_external: false,
574                    library: None,
575                });
576            }
577        }
578    } else if section_type == SHT_DYNSYM {
579        let Ok(Some((dynsymtab, dynstrtab))) = elf.dynamic_symbol_table() else {
580            return;
581        };
582        for sym in dynsymtab.iter() {
583            if sym.st_symtype() == STT_FUNC && sym.st_value != 0 {
584                let name = dynstrtab.get(sym.st_name as usize).ok().map(str::to_owned);
585                out.push(FunctionSymbol {
586                    address: sym.st_value,
587                    name,
588                    size: (sym.st_size != 0).then_some(sym.st_size),
589                    is_external: false,
590                    library: None,
591                });
592            }
593        }
594    }
595}
596
597/// Collect PLT stub addresses and names from `.rel[a].plt` + `.dynsym`.
598///
599/// Each relocation entry at index `i` (0-based) corresponds to the PLT stub at
600/// `plt_start + (i + 1) * entry_size`. The stub is named after the imported
601/// symbol, not `symbol@plt`, so direct calls render as calls to the external.
602fn collect_plt_symbols(elf: &ElfBytes<AnyEndian>, out: &mut Vec<FunctionSymbol>) {
603    let _ = collect_plt_symbols_inner(elf, out);
604}
605
606fn collect_plt_symbols_inner(
607    elf: &ElfBytes<AnyEndian>,
608    out: &mut Vec<FunctionSymbol>,
609) -> Option<()> {
610    let (shdrs, shstrtab) = match elf.section_headers_with_strtab() {
611        Ok((Some(s), Some(st))) => (s, st),
612        _ => return None,
613    };
614
615    let section_addr = |name: &str| {
616        shdrs
617            .iter()
618            .find(|s| shstrtab.get(s.sh_name as usize).ok() == Some(name))
619            .map(|s| s.sh_addr)
620    };
621
622    let plt_start = section_addr(".plt")?;
623    let plt_entry_size = plt_entry_size(elf.ehdr.e_machine)?;
624    // CET-enabled binaries emit a second, parallel stub table `.plt.sec`: one
625    // 16-byte `endbr64; bnd jmp *GOT` entry per import (no reserved entry 0), in
626    // the same order as `.rela.plt`. Direct `call`s go through `.plt.sec`, while
627    // `.plt` is reached only by the lazy resolver — so when it exists, the import
628    // name belongs on the `.plt.sec` stub the callers reference.
629    let plt_sec_start = section_addr(".plt.sec");
630
631    let (dynsymtab, dynstrtab) = elf.dynamic_symbol_table().ok().flatten()?;
632    // Symbol-version table (`.gnu.version` / `.gnu.version_r`): maps a dynsym
633    // index to the shared library its version requirement names. Absent in
634    // unversioned binaries, in which case imports carry no library.
635    let version_table = elf.symbol_version_table().ok().flatten();
636    let import_library = |sym_idx: u32| {
637        version_table
638            .as_ref()
639            .and_then(|vt| vt.get_requirement(sym_idx as usize).ok().flatten())
640            .map(|req| req.file.to_string())
641    };
642
643    // Import relocations from `.rela.plt` (x86-64 / RELA) or `.rel.plt`
644    // (x86-32 / REL), as `(index, symbol_name, library)` tuples in section order.
645    let mut import_relocs: Vec<(usize, Option<String>, Option<String>)> = Vec::new();
646    if let Some(rela_plt_shdr) = shdrs
647        .iter()
648        .find(|s| shstrtab.get(s.sh_name as usize).ok() == Some(".rela.plt"))
649    {
650        for (i, rela) in elf.section_data_as_relas(&rela_plt_shdr).ok()?.enumerate() {
651            if is_import_relocation(elf.ehdr.e_machine, rela.r_type) {
652                let name = dyn_symbol_name(&dynsymtab, &dynstrtab, rela.r_sym).map(str::to_string);
653                import_relocs.push((i, name, import_library(rela.r_sym)));
654            }
655        }
656    } else if let Some(rel_plt_shdr) = shdrs
657        .iter()
658        .find(|s| shstrtab.get(s.sh_name as usize).ok() == Some(".rel.plt"))
659    {
660        for (i, rel) in elf.section_data_as_rels(&rel_plt_shdr).ok()?.enumerate() {
661            if is_import_relocation(elf.ehdr.e_machine, rel.r_type) {
662                let name = dyn_symbol_name(&dynsymtab, &dynstrtab, rel.r_sym).map(str::to_string);
663                import_relocs.push((i, name, import_library(rel.r_sym)));
664            }
665        }
666    }
667
668    for (i, name, library) in import_relocs {
669        // `.plt` stub for relocation `i` sits after the reserved entry 0.
670        let plt_stub_addr = plt_start + ((i + 1) as u64) * plt_entry_size;
671        match plt_sec_start {
672            // With a `.plt.sec`, that stub bears the import name (callers target
673            // it); the `.plt` stub stays external but nameless, so it is not
674            // mistaken for a pure local — and so its name does not collide with
675            // the `.plt.sec` stub's.
676            Some(sec_start) => {
677                out.push(FunctionSymbol {
678                    address: sec_start + (i as u64) * plt_entry_size,
679                    name,
680                    size: None,
681                    is_external: true,
682                    library: library.clone(),
683                });
684                out.push(FunctionSymbol {
685                    address: plt_stub_addr,
686                    name: None,
687                    size: None,
688                    is_external: true,
689                    library,
690                });
691            }
692            None => out.push(FunctionSymbol {
693                address: plt_stub_addr,
694                name,
695                size: None,
696                is_external: true,
697                library,
698            }),
699        }
700    }
701
702    Some(())
703}
704
705fn dyn_symbol_name<'a>(
706    dynsymtab: &elf::symbol::SymbolTable<'a, AnyEndian>,
707    dynstrtab: &elf::string_table::StringTable<'a>,
708    sym_idx: u32,
709) -> Option<&'a str> {
710    let sym = dynsymtab.get(sym_idx as usize).ok()?;
711    let name = dynstrtab.get(sym.st_name as usize).ok()?;
712    if name.is_empty() { None } else { Some(name) }
713}
714
715fn is_import_relocation(machine: u16, r_type: u32) -> bool {
716    match machine {
717        EM_386 | EM_X86_64 => r_type == R_X86_64_JUMP_SLOT,
718        _ => false,
719    }
720}
721
722fn plt_entry_size(machine: u16) -> Option<u64> {
723    match machine {
724        EM_386 | EM_X86_64 => Some(16),
725        _ => None,
726    }
727}
728
729fn collect_import_symbols(elf: &ElfBytes<AnyEndian>, out: &mut Vec<ImportSymbol>) {
730    let _ = collect_import_symbols_inner(elf, out);
731}
732
733fn collect_import_symbols_inner(
734    elf: &ElfBytes<AnyEndian>,
735    out: &mut Vec<ImportSymbol>,
736) -> Option<()> {
737    let (shdrs, _) = match elf.section_headers_with_strtab() {
738        Ok((Some(s), _)) => (s, ()),
739        _ => return None,
740    };
741
742    let (dynsymtab, dynstrtab) = elf.dynamic_symbol_table().ok().flatten()?;
743    let version_table = elf.symbol_version_table().ok().flatten();
744    let import_library = |sym_idx: u32| {
745        version_table
746            .as_ref()
747            .and_then(|vt| vt.get_requirement(sym_idx as usize).ok().flatten())
748            .map(|req| req.file.to_string())
749    };
750
751    for shdr in shdrs.iter() {
752        match shdr.sh_type {
753            SHT_RELA => {
754                let relas = elf.section_data_as_relas(&shdr).ok()?;
755                for rela in relas {
756                    if !is_got_import_relocation(rela.r_type) {
757                        continue;
758                    }
759                    let sym = dynsymtab.get(rela.r_sym as usize).ok()?;
760                    let name = dynstrtab.get(sym.st_name as usize).ok()?.to_owned();
761                    out.push(ImportSymbol {
762                        address: rela.r_offset,
763                        name,
764                        library: import_library(rela.r_sym),
765                    });
766                }
767            }
768            SHT_REL => {
769                let rels = elf.section_data_as_rels(&shdr).ok()?;
770                for rel in rels {
771                    if !is_got_import_relocation(rel.r_type) {
772                        continue;
773                    }
774                    let sym = dynsymtab.get(rel.r_sym as usize).ok()?;
775                    let name = dynstrtab.get(sym.st_name as usize).ok()?.to_owned();
776                    out.push(ImportSymbol {
777                        address: rel.r_offset,
778                        name,
779                        library: import_library(rel.r_sym),
780                    });
781                }
782            }
783            _ => {}
784        }
785    }
786
787    Some(())
788}
789
790fn is_got_import_relocation(r_type: u32) -> bool {
791    matches!(r_type, R_X86_64_GLOB_DAT | R_X86_64_JUMP_SLOT)
792}
793
794impl BinaryFormat for ElfBinary {
795    fn load_address(&self) -> u64 {
796        self.load_address
797    }
798
799    fn architecture(&self) -> Arch {
800        self.architecture
801    }
802
803    fn os(&self) -> crate::TargetOs {
804        crate::TargetOs::Linux
805    }
806
807    fn endianness(&self) -> Endian {
808        self.endian
809    }
810
811    fn bits(&self) -> u32 {
812        if self.is_64 { 64 } else { 32 }
813    }
814
815    /// The allocated section headers, or, for a file whose section table
816    /// was stripped, the `PT_LOAD` segments named `LOAD0`, `LOAD1`, … so the
817    /// layout is still enumerable.
818    fn sections(&self) -> Vec<Section> {
819        if !self.sections.is_empty() {
820            return self
821                .sections
822                .iter()
823                .map(|s| Section {
824                    name: s.name.clone(),
825                    address: s.address,
826                    size: s.size,
827                    writable: s.writable,
828                    executable: s.executable,
829                })
830                .collect();
831        }
832        self.segments
833            .iter()
834            .enumerate()
835            .map(|(i, seg)| Section {
836                name: format!("LOAD{i}"),
837                address: seg.start,
838                size: seg.mem_size,
839                writable: seg.writable,
840                executable: seg.executable,
841            })
842            .collect()
843    }
844
845    fn symbols(&self) -> Vec<Symbol> {
846        self.analysis
847            .known_functions
848            .iter()
849            .filter_map(|f| {
850                let name = f.name.as_deref().filter(|n| !n.is_empty())?;
851                Some(Symbol {
852                    name: name.to_owned(),
853                    address: f.address,
854                    size: f.size,
855                    is_external: f.is_external,
856                    library: f.library.clone(),
857                })
858            })
859            .collect()
860    }
861
862    fn byte_at(&self, addr: u64) -> Option<u8> {
863        self.segments
864            .iter()
865            .find(|segment| segment.contains(addr))
866            .and_then(|segment| segment.byte_at(addr))
867    }
868
869    fn bytes_at(&self, addr: u64) -> Option<&[u8]> {
870        self.segments
871            .iter()
872            .find(|segment| segment.contains(addr))
873            .and_then(|segment| segment.bytes_at(addr))
874    }
875
876    fn is_executable(&self, addr: u64) -> bool {
877        self.segments
878            .iter()
879            .any(|segment| segment.executable && segment.contains(addr))
880    }
881
882    fn segment_bounds(&self, addr: u64) -> Option<(u64, u64)> {
883        self.segments
884            .iter()
885            .find(|segment| segment.contains(addr))
886            .map(|segment| (segment.start, segment.end()))
887    }
888
889    fn is_known_writable(&self, addr: u64) -> bool {
890        self.segments
891            .iter()
892            .any(|segment| segment.writable && segment.contains(addr))
893    }
894
895    /// ELF program headers carry `PF_W`, so a mapped segment without it is
896    /// proven read-only for the lifetime of the process.
897    fn is_known_read_only(&self, addr: u64) -> bool {
898        self.segments
899            .iter()
900            .any(|segment| !segment.writable && segment.contains(addr))
901    }
902
903    fn linked_libraries(&self) -> Vec<String> {
904        self.needed_libraries.clone()
905    }
906
907    fn mapped_regions(&self) -> Vec<(u64, Vec<u8>, bool, bool)> {
908        self.segments
909            .iter()
910            .map(|seg| {
911                // Materialize the `p_memsz > p_filesz` zero-fill tail so reads
912                // line up with `byte_at` (which returns 0 there).
913                let mut bytes = seg.data.clone();
914                bytes.resize(seg.mem_size as usize, 0);
915                (seg.start, bytes, seg.executable, seg.writable)
916            })
917            .collect()
918    }
919
920    fn symbol_name(&self, addr: u64) -> Option<&str> {
921        self.function_at(addr)
922            .and_then(|f| f.name.as_deref())
923            .filter(|name| !name.is_empty())
924            .or_else(|| {
925                (addr == self.analysis.entrypoint && self.is_executable(addr)).then_some("_start")
926            })
927    }
928
929    /// The inverse of [`symbol_name`](BinaryFormat::symbol_name), including
930    /// the synthetic `_start` it gives an unnamed entrypoint.
931    fn symbol_address(&self, name: &str) -> Option<u64> {
932        self.symbols.address(name).or_else(|| {
933            let entry = self.analysis.entrypoint;
934            (name == "_start" && self.symbol_name(entry) == Some("_start")).then_some(entry)
935        })
936    }
937
938    fn is_external_symbol(&self, addr: u64) -> bool {
939        self.function_at(addr).is_some_and(|f| f.is_external)
940    }
941
942    fn import_symbol_name(&self, addr: u64) -> Option<&str> {
943        self.import_at(addr).map(|f| f.name.as_str())
944    }
945
946    fn import_library(&self, addr: u64) -> Option<&str> {
947        // Externals are minted either at a PLT stub's address or (for GOT-
948        // indirect calls with no PLT stub) at the relocation slot itself.
949        self.function_at(addr)
950            .and_then(|f| f.library.as_deref())
951            .or_else(|| self.import_at(addr).and_then(|f| f.library.as_deref()))
952    }
953
954    /// Entry points are the ELF entrypoint plus all known function starts.
955    fn entry_points(&self) -> Vec<u64> {
956        let mut entries = vec![self.analysis.entrypoint];
957        for f in &self.analysis.known_functions {
958            entries.push(f.address);
959        }
960        entries.sort();
961        entries.dedup();
962        entries
963    }
964
965    /// The ELF entry point (`e_entry` from the header).
966    fn entrypoint(&self) -> Option<u64> {
967        Some(self.analysis.entrypoint)
968    }
969}
970
971pub fn from_elf_machine(value: u16) -> Option<Arch> {
972    match value {
973        1 => Some(Arch::M32),
974        2 => Some(Arch::Sparc),
975        3 => Some(Arch::I386),
976        4 => Some(Arch::M68K),
977        5 => Some(Arch::M88K),
978        7 => Some(Arch::I860),
979        8 => Some(Arch::Mips),
980        9 => Some(Arch::S370),
981        10 => Some(Arch::MipsRs3Le),
982        15 => Some(Arch::PaRisc),
983        17 => Some(Arch::Vpp500),
984        18 => Some(Arch::Sparc32Plus),
985        19 => Some(Arch::I960),
986        20 => Some(Arch::Ppc),
987        21 => Some(Arch::Ppc64),
988        22 => Some(Arch::S390),
989        // 23-35 reserved
990        36 => Some(Arch::V800),
991        37 => Some(Arch::Fr20),
992        38 => Some(Arch::Rh32),
993        39 => Some(Arch::Rce),
994        40 => Some(Arch::Arm),
995        41 => Some(Arch::Alpha),
996        42 => Some(Arch::Sh),
997        43 => Some(Arch::SparcV9),
998        44 => Some(Arch::Tricore),
999        45 => Some(Arch::Arc),
1000        46 => Some(Arch::H8300),
1001        47 => Some(Arch::H8300H),
1002        48 => Some(Arch::H8S),
1003        49 => Some(Arch::H8500),
1004        50 => Some(Arch::Ia64),
1005        51 => Some(Arch::MipsX),
1006        52 => Some(Arch::ColdFire),
1007        53 => Some(Arch::M68Hc12),
1008        54 => Some(Arch::Mma),
1009        55 => Some(Arch::Pcp),
1010        56 => Some(Arch::Ncpu),
1011        57 => Some(Arch::Ndr1),
1012        58 => Some(Arch::StarCore),
1013        59 => Some(Arch::Me16),
1014        60 => Some(Arch::St100),
1015        61 => Some(Arch::TinyJ),
1016        62 => Some(Arch::X86_64),
1017        63 => Some(Arch::Pdsp),
1018        64 => Some(Arch::Pdp10),
1019        65 => Some(Arch::Pdp11),
1020        66 => Some(Arch::Fx66),
1021        67 => Some(Arch::St9Plus),
1022        68 => Some(Arch::St7),
1023        69 => Some(Arch::M68Hc16),
1024        70 => Some(Arch::M68Hc11),
1025        71 => Some(Arch::M68Hc08),
1026        72 => Some(Arch::M68Hc05),
1027        73 => Some(Arch::Svx),
1028        74 => Some(Arch::St19),
1029        75 => Some(Arch::Vax),
1030        76 => Some(Arch::Cris),
1031        77 => Some(Arch::Javelin),
1032        78 => Some(Arch::FirePath),
1033        79 => Some(Arch::Zsp),
1034        80 => Some(Arch::Mmix),
1035        81 => Some(Arch::Huany),
1036        82 => Some(Arch::Prism),
1037        83 => Some(Arch::Avr),
1038        84 => Some(Arch::Fr30),
1039        85 => Some(Arch::D10V),
1040        86 => Some(Arch::D30V),
1041        87 => Some(Arch::V850),
1042        88 => Some(Arch::M32R),
1043        89 => Some(Arch::Mn10300),
1044        90 => Some(Arch::Mn10200),
1045        91 => Some(Arch::PicoJava),
1046        92 => Some(Arch::OpenRisc),
1047        93 => Some(Arch::ArcA5),
1048        94 => Some(Arch::Xtensa),
1049        95 => Some(Arch::VideoCore),
1050        96 => Some(Arch::TmmGpp),
1051        97 => Some(Arch::Ns32K),
1052        98 => Some(Arch::Tpc),
1053        99 => Some(Arch::Snp1K),
1054        100 => Some(Arch::St200),
1055        106 => Some(Arch::Blackfin),
1056        110 => Some(Arch::Unicore),
1057        113 => Some(Arch::AlteraNios2),
1058        140 => Some(Arch::TIC6000),
1059        164 => Some(Arch::Hexagon),
1060        167 => Some(Arch::NDS32),
1061        183 => Some(Arch::AArch64),
1062        188 => Some(Arch::TILEPro),
1063        189 => Some(Arch::Microblaze),
1064        191 => Some(Arch::TILEGx),
1065        195 => Some(Arch::ARCv2),
1066        243 => Some(Arch::RISCV),
1067        247 => Some(Arch::BPF),
1068        252 => Some(Arch::CSKY),
1069        258 => Some(Arch::LoongArch),
1070        0x5441 => Some(Arch::FRV),
1071        _ => None,
1072    }
1073}