Skip to main content

wazabin_binary/
pe.rs

1use crate::Arch;
2use goblin::options::ParseMode;
3use goblin::pe::{
4    PE,
5    header::{
6        COFF_MACHINE_ARM, COFF_MACHINE_ARM64, COFF_MACHINE_ARMNT, COFF_MACHINE_X86,
7        COFF_MACHINE_X86_64,
8    },
9    options::ParseOptions,
10    symbol::Symbol as CoffSymbol,
11};
12
13use crate::symbols::SymbolIndex;
14use crate::{BinaryFormat, Endian, Section, Symbol};
15
16/// A known function start address extracted from PE metadata.
17#[derive(Debug, Clone)]
18pub struct PeFunctionSymbol {
19    /// Virtual address of the function.
20    pub address: u64,
21    /// Symbol name, if present.
22    pub name: Option<String>,
23    /// The function's size from its exception-directory (`RUNTIME_FUNCTION`)
24    /// entry. `None` when only a COFF symbol names it, or for import thunks.
25    pub size: Option<u64>,
26    /// Whether this is an external imported function.
27    pub is_external: bool,
28    /// For an import thunk, the DLL the import comes from.
29    pub library: Option<String>,
30}
31
32/// A PE import resolved from the import address table.
33#[derive(Debug, Clone)]
34pub struct PeImportSymbol {
35    /// Virtual address of the import address table slot.
36    pub iat_address: u64,
37    /// Bare imported function name used for display.
38    pub name: String,
39    /// Source DLL name.
40    pub dll: String,
41    /// Import ordinal, if present.
42    pub ordinal: Option<u16>,
43}
44
45/// Results of PE analysis.
46#[derive(Debug, Clone)]
47pub struct PeAnalysis {
48    /// Preferred image-base virtual address.
49    pub image_base: u64,
50    /// PE optional-header entrypoint VA.
51    pub entrypoint: u64,
52    /// Function start addresses discovered from COFF symbols and imports.
53    pub known_functions: Vec<PeFunctionSymbol>,
54    /// Imported functions keyed by their IAT slots.
55    pub imports: Vec<PeImportSymbol>,
56}
57
58#[derive(Debug, Clone)]
59pub struct PeSection {
60    /// The section-table name, e.g. `.text`; empty when the header has none.
61    pub name: String,
62    pub start: u64,
63    pub mem_size: u64,
64    pub data: Vec<u8>,
65    /// `IMAGE_SCN_MEM_WRITE` from the section characteristics. Read straight
66    /// from the section table, so a section without the bit is proven
67    /// read-only.
68    pub writable: bool,
69    /// `IMAGE_SCN_MEM_EXECUTE` from the section characteristics. Both
70    /// [`BinaryFormat::is_executable`] and [`BinaryFormat::mapped_regions`]
71    /// honour it, so a section without the bit is treated as data.
72    pub executable: bool,
73}
74
75/// `IMAGE_SCN_MEM_EXECUTE`: the section may be executed as code.
76const IMAGE_SCN_MEM_EXECUTE: u32 = 0x2000_0000;
77/// `IMAGE_SCN_MEM_WRITE`: the section is writable at run time.
78const IMAGE_SCN_MEM_WRITE: u32 = 0x8000_0000;
79
80impl PeSection {
81    fn end(&self) -> u64 {
82        self.start + self.mem_size
83    }
84
85    fn contains(&self, addr: u64) -> bool {
86        addr >= self.start && addr < self.end()
87    }
88
89    fn byte_at(&self, addr: u64) -> Option<u8> {
90        if !self.contains(addr) {
91            return None;
92        }
93        let offset = (addr - self.start) as usize;
94        Some(self.data.get(offset).copied().unwrap_or(0))
95    }
96
97    fn bytes_at(&self, addr: u64) -> Option<&[u8]> {
98        if !self.contains(addr) {
99            return None;
100        }
101        let offset = (addr - self.start) as usize;
102        self.data.get(offset..)
103    }
104}
105
106/// A parsed and loaded PE32/PE32+ executable image.
107///
108/// `analysis.known_functions` is sorted by address with one entry per
109/// address, and a name index is built alongside it, which is what the
110/// [`BinaryFormat::symbol_name`] / [`BinaryFormat::symbol_address`] lookups
111/// search. Both hold once parsing returns; mutating the table afterwards is
112/// not supported.
113#[derive(Debug, Clone)]
114pub struct PeBinary {
115    pub load_address: u64,
116    pub sections: Vec<PeSection>,
117    pub analysis: PeAnalysis,
118    /// Function names -> addresses, over `analysis.known_functions`.
119    symbols: SymbolIndex,
120    pub architecture: Arch,
121    pub is_64: bool,
122}
123
124/// Errors that can occur while parsing a PE binary.
125#[derive(Debug)]
126pub enum PeError {
127    Parse(goblin::error::Error),
128    NoMappedSection,
129    UnsupportedMachine(u16),
130}
131
132impl std::fmt::Display for PeError {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        match self {
135            PeError::Parse(e) => write!(f, "PE parse error: {e}"),
136            PeError::NoMappedSection => write!(f, "PE contains no mapped sections"),
137            PeError::UnsupportedMachine(machine) => {
138                write!(f, "PE has unsupported machine type 0x{machine:x}")
139            }
140        }
141    }
142}
143
144impl std::error::Error for PeError {}
145
146impl From<goblin::error::Error> for PeError {
147    fn from(e: goblin::error::Error) -> Self {
148        PeError::Parse(e)
149    }
150}
151
152impl PeBinary {
153    /// Parse a PE32/PE32+ executable from raw file bytes.
154    ///
155    /// Parsed in [`ParseMode::Permissive`]: goblin's default strict mode makes a
156    /// failure in any optional data directory fatal to the whole image, even one
157    /// this crate never reads (base relocations, say, when `.reloc` declares a
158    /// virtual size but no raw data). Permissive mode drops each directory it
159    /// cannot parse and keeps the rest; a well-formed file parses identically.
160    pub fn parse(file_bytes: &[u8]) -> Result<Self, PeError> {
161        let options = ParseOptions::default().with_parse_mode(ParseMode::Permissive);
162        let pe = PE::parse_with_opts(file_bytes, &options)?;
163        let architecture = from_pe_machine(pe.header.coff_header.machine)
164            .ok_or(PeError::UnsupportedMachine(pe.header.coff_header.machine))?;
165
166        let mut sections = pe
167            .sections
168            .iter()
169            .filter(|s| s.virtual_size > 0 || s.size_of_raw_data > 0)
170            .map(|section| {
171                let start = pe.image_base + u64::from(section.virtual_address);
172                let mem_size = u64::from(section.virtual_size.max(section.size_of_raw_data));
173                let offset = section.pointer_to_raw_data as usize;
174                let filesz = section.size_of_raw_data as usize;
175                let data = file_bytes
176                    .get(offset..offset.saturating_add(filesz))
177                    .unwrap_or(&[])
178                    .to_vec();
179                PeSection {
180                    name: section
181                        .real_name
182                        .clone()
183                        .or_else(|| section.name().ok().map(str::to_owned))
184                        .unwrap_or_default(),
185                    start,
186                    mem_size,
187                    data,
188                    writable: section.characteristics & IMAGE_SCN_MEM_WRITE != 0,
189                    executable: section.characteristics & IMAGE_SCN_MEM_EXECUTE != 0,
190                }
191            })
192            .filter(|s| s.mem_size > 0)
193            .collect::<Vec<_>>();
194
195        if sections.is_empty() {
196            return Err(PeError::NoMappedSection);
197        }
198        sections.sort_by_key(|s| s.start);
199        let load_address = sections[0].start;
200
201        let entrypoint = pe.image_base + u64::from(pe.entry);
202        let mut known_functions = Vec::new();
203        collect_coff_function_symbols(&pe, file_bytes, &mut known_functions);
204        let imports: Vec<_> = pe
205            .imports
206            .iter()
207            .map(|import| {
208                let name = import.name.to_string();
209                PeImportSymbol {
210                    iat_address: pe.image_base + import.offset as u64,
211                    name,
212                    dll: import.dll.to_string(),
213                    ordinal: (import.ordinal != 0).then_some(import.ordinal),
214                }
215            })
216            .collect();
217        mark_import_thunks(&mut known_functions, &sections, &imports, pe.is_64);
218        collect_exception_function_symbols(&pe, &sections, &mut known_functions);
219        uniquify_function_names(&mut known_functions);
220
221        // The sorted order is what `function_at` binary-searches. A COFF
222        // symbol and an exception-directory entry for the same function
223        // collapse into the symbol's entry, which inherits the entry's size.
224        known_functions.sort_by_key(|f| (f.address, !f.is_external, f.name.is_none()));
225        known_functions.dedup_by(|dropped, kept| {
226            if dropped.address != kept.address {
227                return false;
228            }
229            if kept.size.is_none() {
230                kept.size = dropped.size;
231            }
232            true
233        });
234        let symbols = SymbolIndex::build(
235            known_functions
236                .iter()
237                .map(|f| (f.name.as_deref(), f.address, f.is_external)),
238        );
239
240        Ok(Self {
241            load_address,
242            sections,
243            analysis: PeAnalysis {
244                image_base: pe.image_base,
245                entrypoint,
246                known_functions,
247                imports,
248            },
249            symbols,
250            architecture,
251            is_64: pe.is_64,
252        })
253    }
254
255    /// The known function starting at `addr`, by binary search over the
256    /// address-sorted table.
257    fn function_at(&self, addr: u64) -> Option<&PeFunctionSymbol> {
258        let functions = &self.analysis.known_functions;
259        let idx = functions.binary_search_by_key(&addr, |f| f.address).ok()?;
260        Some(&functions[idx])
261    }
262
263    fn import_at_iat(&self, addr: u64) -> Option<&PeImportSymbol> {
264        self.analysis
265            .imports
266            .iter()
267            .find(|import| import.iat_address == addr)
268    }
269}
270
271fn collect_exception_function_symbols(
272    pe: &PE<'_>,
273    sections: &[PeSection],
274    out: &mut Vec<PeFunctionSymbol>,
275) {
276    let Some(exception_data) = pe.exception_data.as_ref() else {
277        return;
278    };
279
280    for function in exception_data.functions().flatten() {
281        if function.begin_address == 0 || function.end_address <= function.begin_address {
282            continue;
283        }
284
285        let address = pe.image_base + u64::from(function.begin_address);
286        if !sections.iter().any(|section| section.contains(address)) {
287            continue;
288        }
289
290        out.push(PeFunctionSymbol {
291            address,
292            name: None,
293            size: Some(u64::from(function.end_address - function.begin_address)),
294            is_external: false,
295            library: None,
296        });
297    }
298}
299
300fn collect_coff_function_symbols(pe: &PE<'_>, file_bytes: &[u8], out: &mut Vec<PeFunctionSymbol>) {
301    let Ok(Some(symbols)) = pe.header.coff_header.symbols(file_bytes) else {
302        return;
303    };
304    let strings = pe.header.coff_header.strings(file_bytes).ok().flatten();
305
306    for (_index, inline_name, symbol) in symbols.iter() {
307        if !symbol.is_function_definition() {
308            continue;
309        }
310        let section_index = (symbol.section_number - 1) as usize;
311        let Some(section) = pe.sections.get(section_index) else {
312            continue;
313        };
314        let Some(name) = symbol_name(&symbol, inline_name, strings.as_ref()) else {
315            continue;
316        };
317        let address = pe.image_base + u64::from(section.virtual_address) + u64::from(symbol.value);
318        out.push(PeFunctionSymbol {
319            address,
320            name: Some(name),
321            size: None,
322            is_external: false,
323            library: None,
324        });
325    }
326}
327
328fn symbol_name(
329    symbol: &CoffSymbol,
330    inline_name: Option<&str>,
331    strings: Option<&goblin::strtab::Strtab<'_>>,
332) -> Option<String> {
333    if let Some(name) = inline_name
334        && !name.is_empty()
335    {
336        return Some(normalize_coff_name(name));
337    }
338
339    if let Some(strings) = strings
340        && let Ok(name) = symbol.name(strings)
341        && !name.is_empty()
342    {
343        return Some(normalize_coff_name(name));
344    }
345
346    let end = symbol
347        .name
348        .iter()
349        .position(|&b| b == 0)
350        .unwrap_or(symbol.name.len());
351    let name = std::str::from_utf8(&symbol.name[..end]).ok()?;
352    (!name.is_empty()).then(|| normalize_coff_name(name))
353}
354
355fn normalize_coff_name(name: &str) -> String {
356    name.strip_prefix('_').unwrap_or(name).to_string()
357}
358
359fn mark_import_thunks(
360    functions: &mut [PeFunctionSymbol],
361    sections: &[PeSection],
362    imports: &[PeImportSymbol],
363    is_64: bool,
364) {
365    for function in functions {
366        let Some(iat_address) = import_thunk_iat(sections, function.address, is_64) else {
367            continue;
368        };
369        let Some(import) = imports
370            .iter()
371            .find(|import| import.iat_address == iat_address)
372        else {
373            continue;
374        };
375
376        function.name = Some(import.name.clone());
377        function.is_external = true;
378        function.library = Some(import.dll.clone());
379    }
380}
381
382fn import_thunk_iat(sections: &[PeSection], address: u64, is_64: bool) -> Option<u64> {
383    let bytes = sections
384        .iter()
385        .find(|section| section.contains(address))
386        .and_then(|section| section.bytes_at(address))?;
387
388    if bytes.len() < 6 || bytes[0] != 0xff || bytes[1] != 0x25 {
389        return None;
390    }
391
392    let operand = [bytes[2], bytes[3], bytes[4], bytes[5]];
393    if is_64 {
394        let disp = i32::from_le_bytes(operand) as i64;
395        Some((address as i64 + 6 + disp) as u64)
396    } else {
397        Some(u32::from_le_bytes(operand) as u64)
398    }
399}
400
401fn uniquify_function_names(functions: &mut [PeFunctionSymbol]) {
402    functions.sort_by_key(|function| {
403        (
404            function.name.clone(),
405            !function.is_external,
406            function.address,
407        )
408    });
409
410    let mut names = std::collections::HashSet::new();
411    for function in functions {
412        let Some(name) = function.name.as_mut() else {
413            continue;
414        };
415        if names.insert(name.clone()) {
416            continue;
417        }
418
419        let base = name.clone();
420        let mut candidate = format!("{base}_{:x}", function.address);
421        let mut suffix = 1;
422        while !names.insert(candidate.clone()) {
423            candidate = format!("{base}_{:x}_{suffix}", function.address);
424            suffix += 1;
425        }
426        *name = candidate;
427    }
428}
429
430impl BinaryFormat for PeBinary {
431    fn load_address(&self) -> u64 {
432        self.load_address
433    }
434
435    fn architecture(&self) -> Arch {
436        self.architecture
437    }
438
439    fn os(&self) -> crate::TargetOs {
440        crate::TargetOs::Windows
441    }
442
443    /// PE is little-endian on every machine this crate maps.
444    fn endianness(&self) -> Endian {
445        Endian::Little
446    }
447
448    fn bits(&self) -> u32 {
449        if self.is_64 { 64 } else { 32 }
450    }
451
452    /// The section table, with the real `IMAGE_SCN_MEM_EXECUTE` bit.
453    fn sections(&self) -> Vec<Section> {
454        self.sections
455            .iter()
456            .map(|s| Section {
457                name: s.name.clone(),
458                address: s.start,
459                size: s.mem_size,
460                writable: s.writable,
461                executable: s.executable,
462            })
463            .collect()
464    }
465
466    fn symbols(&self) -> Vec<Symbol> {
467        self.analysis
468            .known_functions
469            .iter()
470            .filter_map(|f| {
471                let name = f.name.as_deref().filter(|n| !n.is_empty())?;
472                Some(Symbol {
473                    name: name.to_owned(),
474                    address: f.address,
475                    size: f.size,
476                    is_external: f.is_external,
477                    library: f.library.clone(),
478                })
479            })
480            .collect()
481    }
482
483    /// Import-directory DLL names in first-seen order, deduplicated
484    /// case-insensitively but reported in their original case.
485    fn linked_libraries(&self) -> Vec<String> {
486        let mut seen: Vec<String> = Vec::new();
487        for import in &self.analysis.imports {
488            if !seen.iter().any(|dll| dll.eq_ignore_ascii_case(&import.dll)) {
489                seen.push(import.dll.clone());
490            }
491        }
492        seen
493    }
494
495    fn byte_at(&self, addr: u64) -> Option<u8> {
496        self.sections
497            .iter()
498            .find(|section| section.contains(addr))
499            .and_then(|section| section.byte_at(addr))
500    }
501
502    fn bytes_at(&self, addr: u64) -> Option<&[u8]> {
503        self.sections
504            .iter()
505            .find(|section| section.contains(addr))
506            .and_then(|section| section.bytes_at(addr))
507    }
508
509    fn mapped_regions(&self) -> Vec<(u64, Vec<u8>, bool, bool)> {
510        self.sections
511            .iter()
512            .map(|sec| {
513                let mut bytes = sec.data.clone();
514                bytes.resize(sec.mem_size as usize, 0);
515                // Both flags are the section table's own, so a snapshot built
516                // from these regions answers `is_executable` and
517                // `is_known_read_only` exactly as the live binary does.
518                (sec.start, bytes, sec.executable, sec.writable)
519            })
520            .collect()
521    }
522
523    /// Only a section with `IMAGE_SCN_MEM_EXECUTE` is executable; an address in
524    /// any other section, or in no section, is not. Without this override the
525    /// trait default answers "mapped", and a bogus branch target in `.data` is
526    /// decoded as code.
527    fn is_executable(&self, addr: u64) -> bool {
528        self.sections
529            .iter()
530            .any(|section| section.executable && section.contains(addr))
531    }
532
533    /// A mapped section without `IMAGE_SCN_MEM_WRITE` is proven read-only.
534    /// (There is deliberately no `is_known_writable` override: flipping that
535    /// predicate would change which constants the folding passes trust, which is
536    /// a separate question from proving a region immutable.)
537    fn is_known_read_only(&self, addr: u64) -> bool {
538        self.sections
539            .iter()
540            .any(|section| !section.writable && section.contains(addr))
541    }
542
543    fn segment_bounds(&self, addr: u64) -> Option<(u64, u64)> {
544        self.sections
545            .iter()
546            .find(|section| section.contains(addr))
547            .map(|section| (section.start, section.end()))
548    }
549
550    fn symbol_name(&self, addr: u64) -> Option<&str> {
551        self.function_at(addr)
552            .and_then(|f| f.name.as_deref())
553            .filter(|name| !name.is_empty())
554            .or_else(|| (addr == self.analysis.entrypoint).then_some("_start"))
555    }
556
557    /// The inverse of [`symbol_name`](BinaryFormat::symbol_name), including
558    /// the synthetic `_start` it gives an unnamed entrypoint.
559    fn symbol_address(&self, name: &str) -> Option<u64> {
560        self.symbols.address(name).or_else(|| {
561            let entry = self.analysis.entrypoint;
562            (name == "_start" && self.symbol_name(entry) == Some("_start")).then_some(entry)
563        })
564    }
565
566    fn is_external_symbol(&self, addr: u64) -> bool {
567        self.function_at(addr).is_some_and(|f| f.is_external)
568    }
569
570    fn entry_points(&self) -> Vec<u64> {
571        let mut entries = vec![self.analysis.entrypoint];
572        let has_named_code_symbols = self
573            .analysis
574            .known_functions
575            .iter()
576            .any(|f| !f.is_external && f.name.is_some());
577
578        for f in &self.analysis.known_functions {
579            if f.is_external {
580                continue;
581            }
582
583            if (!has_named_code_symbols && f.name.is_none())
584                || f.name.as_deref().is_some_and(is_primary_pe_function_name)
585            {
586                entries.push(f.address);
587            }
588        }
589        entries.sort();
590        entries.dedup();
591        entries
592    }
593
594    fn entrypoint(&self) -> Option<u64> {
595        Some(self.analysis.entrypoint)
596    }
597
598    fn import_symbol_name(&self, addr: u64) -> Option<&str> {
599        self.import_at_iat(addr).map(|import| import.name.as_str())
600    }
601
602    fn import_library(&self, addr: u64) -> Option<&str> {
603        // Externals are minted either at an import thunk's address or (for
604        // direct `call [iat]` sites with no thunk) at the IAT slot itself.
605        self.import_at_iat(addr)
606            .map(|import| import.dll.as_str())
607            .or_else(|| self.function_at(addr).and_then(|f| f.library.as_deref()))
608    }
609}
610
611fn is_primary_pe_function_name(name: &str) -> bool {
612    matches!(name, "main" | "WinMain" | "wmain" | "wWinMain")
613}
614
615pub fn from_pe_machine(value: u16) -> Option<Arch> {
616    match value {
617        COFF_MACHINE_X86 => Some(Arch::I386),
618        COFF_MACHINE_X86_64 => Some(Arch::X86_64),
619        COFF_MACHINE_ARM | COFF_MACHINE_ARMNT => Some(Arch::Arm),
620        COFF_MACHINE_ARM64 => Some(Arch::AArch64),
621        _ => None,
622    }
623}
624
625#[cfg(test)]
626mod tests {
627    use super::*;
628
629    /// A minimal PE32 with two sections, whose `.reloc` declares a virtual size but carries no
630    /// raw data, and whose base relocation directory points into it.
631    ///
632    /// This is a truncated or stripped image: the section table still describes `.reloc`, the
633    /// optional header still points a data directory at it, and the bytes are simply not in the
634    /// file. Built here rather than checked in as a fixture so the shape is visible and the test
635    /// needs no binary.
636    fn pe32_with_unbacked_reloc_directory() -> Vec<u8> {
637        const PE_OFF: usize = 0x40;
638        const OPT_OFF: usize = PE_OFF + 4 + 20;
639        const OPT_SIZE: usize = 224;
640        const SEC_OFF: usize = OPT_OFF + OPT_SIZE;
641        const HEADERS: usize = 0x200;
642        const TEXT_RAW: usize = 0x200;
643
644        let mut b = vec![0u8; HEADERS + TEXT_RAW];
645        b[0..2].copy_from_slice(b"MZ");
646        b[0x3c..0x40].copy_from_slice(&(PE_OFF as u32).to_le_bytes());
647        b[PE_OFF..PE_OFF + 4].copy_from_slice(b"PE\0\0");
648
649        let coff = PE_OFF + 4;
650        b[coff..coff + 2].copy_from_slice(&COFF_MACHINE_X86.to_le_bytes()); // Machine
651        b[coff + 2..coff + 4].copy_from_slice(&2u16.to_le_bytes()); // NumberOfSections
652        b[coff + 16..coff + 18].copy_from_slice(&(OPT_SIZE as u16).to_le_bytes());
653        b[coff + 18..coff + 20].copy_from_slice(&0x0102u16.to_le_bytes()); // Characteristics
654
655        let mut w32 = |off: usize, v: u32| b[off..off + 4].copy_from_slice(&v.to_le_bytes());
656        w32(OPT_OFF, 0x0000_010b); // Magic = PE32 (low half), linker version in the high half
657        w32(OPT_OFF + 16, 0x1000); // AddressOfEntryPoint
658        w32(OPT_OFF + 20, 0x1000); // BaseOfCode
659        w32(OPT_OFF + 24, 0x2000); // BaseOfData
660        w32(OPT_OFF + 28, 0x0040_0000); // ImageBase
661        w32(OPT_OFF + 32, 0x1000); // SectionAlignment
662        w32(OPT_OFF + 36, 0x200); // FileAlignment
663        w32(OPT_OFF + 56, 0x3000); // SizeOfImage
664        w32(OPT_OFF + 60, HEADERS as u32); // SizeOfHeaders
665        w32(OPT_OFF + 68, 3); // Subsystem = console
666        w32(OPT_OFF + 92, 16); // NumberOfRvaAndSizes
667        // Data directory 5 is the base relocation table: it points at `.reloc`, which has no
668        // bytes in the file. This one directory is what strict parsing rejects the image for.
669        w32(OPT_OFF + 96 + 5 * 8, 0x2000);
670        w32(OPT_OFF + 96 + 5 * 8 + 4, 0x10);
671
672        // Section header `i`: name, then (field offset, value) pairs.
673        let section = |b: &mut Vec<u8>, i: usize, name: &[u8], fields: [(usize, u32); 5]| {
674            let o = SEC_OFF + i * 40;
675            b[o..o + name.len()].copy_from_slice(name);
676            for (k, v) in fields {
677                b[o + k..o + k + 4].copy_from_slice(&v.to_le_bytes());
678            }
679        };
680        // Offsets: 8 VirtualSize, 12 VirtualAddress, 16 SizeOfRawData,
681        // 20 PointerToRawData, 36 Characteristics.
682        section(
683            &mut b,
684            0,
685            b".text",
686            [
687                (8, 0x10),
688                (12, 0x1000),
689                (16, TEXT_RAW as u32),
690                (20, HEADERS as u32),
691                (36, 0x6000_0020),
692            ],
693        );
694        // .reloc: a virtual size, and NO raw data.
695        section(
696            &mut b,
697            1,
698            b".reloc",
699            [
700                (8, 0x1000),
701                (12, 0x2000),
702                (16, 0),
703                (20, 0),
704                (36, 0x4200_0040),
705            ],
706        );
707        b
708    }
709
710    #[test]
711    fn parses_an_image_whose_reloc_directory_has_no_raw_data() {
712        let bytes = pe32_with_unbacked_reloc_directory();
713
714        // The hazard this guards, stated as an assertion: goblin's default (strict) mode makes a
715        // failure in ANY optional data directory fatal to the image. Should this ever start
716        // succeeding, the permissive option in `PeBinary::parse` has become unnecessary rather
717        // than wrong — and the doc comment there needs revisiting.
718        assert!(
719            PE::parse(&bytes).is_err(),
720            "strict parsing is expected to reject the unbacked base relocation directory"
721        );
722
723        let pe = PeBinary::parse(&bytes).expect("an unbacked .reloc must not reject the image");
724        assert_eq!(pe.architecture, Arch::I386);
725        assert_eq!(pe.entrypoint(), Some(0x0040_1000));
726        assert_eq!(pe.load_address, 0x0040_1000);
727        // Both sections are kept: `.reloc` is mapped, with no bytes behind it.
728        assert_eq!(pe.sections.len(), 2);
729        assert!(
730            pe.sections
731                .iter()
732                .any(|s| s.start == 0x0040_2000 && s.data.is_empty())
733        );
734    }
735
736    /// A section-less image around `analysis`, indexed the way `parse` does it.
737    fn binary(mut analysis: PeAnalysis) -> PeBinary {
738        analysis
739            .known_functions
740            .sort_by_key(|f| (f.address, !f.is_external, f.name.is_none()));
741        analysis.known_functions.dedup_by_key(|f| f.address);
742        let symbols = SymbolIndex::build(
743            analysis
744                .known_functions
745                .iter()
746                .map(|f| (f.name.as_deref(), f.address, f.is_external)),
747        );
748        PeBinary {
749            load_address: 0x400000,
750            sections: vec![],
751            analysis,
752            symbols,
753            architecture: Arch::I386,
754            is_64: false,
755        }
756    }
757
758    fn function(address: u64, name: &str, library: Option<&str>) -> PeFunctionSymbol {
759        PeFunctionSymbol {
760            address,
761            name: Some(name.to_string()),
762            size: None,
763            is_external: library.is_some(),
764            library: library.map(str::to_string),
765        }
766    }
767
768    #[test]
769    fn import_symbol_name_returns_iat_import_name() {
770        let pe = binary(PeAnalysis {
771            image_base: 0x400000,
772            entrypoint: 0x401000,
773            known_functions: vec![],
774            imports: vec![PeImportSymbol {
775                iat_address: 0x404000,
776                name: "ExitProcess".to_string(),
777                dll: "KERNEL32.DLL".to_string(),
778                ordinal: None,
779            }],
780        });
781
782        assert_eq!(pe.import_symbol_name(0x404000), Some("ExitProcess"));
783        assert_eq!(pe.import_symbol_name(0x404004), None);
784    }
785
786    #[test]
787    fn entrypoint_returns_primary_pe_entrypoint() {
788        let pe = binary(PeAnalysis {
789            image_base: 0x400000,
790            entrypoint: 0x401000,
791            known_functions: vec![function(0x402000, "main", None)],
792            imports: vec![],
793        });
794
795        assert_eq!(pe.entrypoint(), Some(0x401000));
796        assert!(pe.entry_points().contains(&0x401000));
797    }
798
799    #[test]
800    fn symbol_lookup_by_name_and_address_are_inverses() {
801        let pe = binary(PeAnalysis {
802            image_base: 0x400000,
803            entrypoint: 0x401000,
804            known_functions: vec![
805                function(0x402000, "main", None),
806                function(0x401100, "helper", None),
807                function(0x403000, "ExitProcess", Some("KERNEL32.DLL")),
808            ],
809            imports: vec![],
810        });
811
812        assert_eq!(pe.symbol_address("main"), Some(0x402000));
813        assert_eq!(pe.symbol_address("helper"), Some(0x401100));
814        assert_eq!(pe.symbol_address("ExitProcess"), Some(0x403000));
815        assert_eq!(pe.symbol_address("missing"), None);
816        assert_eq!(pe.symbol_name(0x402000), Some("main"));
817        assert_eq!(pe.symbol_name(0x401100), Some("helper"));
818        assert_eq!(pe.symbol_name(0x403000), Some("ExitProcess"));
819        assert_eq!(pe.symbol_name(0x402001), None);
820        assert!(pe.is_external_symbol(0x403000));
821        assert!(!pe.is_external_symbol(0x402000));
822        assert_eq!(pe.import_library(0x403000), Some("KERNEL32.DLL"));
823
824        // The unnamed entrypoint reads as `_start` both ways.
825        assert_eq!(pe.symbol_name(0x401000), Some("_start"));
826        assert_eq!(pe.symbol_address("_start"), Some(0x401000));
827    }
828
829    #[test]
830    fn enumerates_sections_and_named_symbols() {
831        let mut pe = binary(PeAnalysis {
832            image_base: 0x400000,
833            entrypoint: 0x401000,
834            known_functions: vec![
835                function(0x402000, "main", None),
836                PeFunctionSymbol {
837                    address: 0x402100,
838                    name: None,
839                    size: Some(0x40),
840                    is_external: false,
841                    library: None,
842                },
843                function(0x403000, "ExitProcess", Some("KERNEL32.DLL")),
844            ],
845            imports: vec![],
846        });
847        pe.sections = vec![
848            PeSection {
849                name: ".text".to_string(),
850                start: 0x401000,
851                mem_size: 0x1000,
852                data: vec![],
853                writable: false,
854                executable: true,
855            },
856            PeSection {
857                name: ".data".to_string(),
858                start: 0x404000,
859                mem_size: 0x200,
860                data: vec![],
861                writable: true,
862                executable: false,
863            },
864        ];
865
866        assert_eq!(
867            pe.sections(),
868            vec![
869                Section {
870                    name: ".text".to_string(),
871                    address: 0x401000,
872                    size: 0x1000,
873                    writable: false,
874                    executable: true,
875                },
876                Section {
877                    name: ".data".to_string(),
878                    address: 0x404000,
879                    size: 0x200,
880                    writable: true,
881                    executable: false,
882                },
883            ]
884        );
885        // The nameless exception-directory entry is a function start, not
886        // a symbol.
887        assert_eq!(
888            pe.symbols(),
889            vec![
890                Symbol {
891                    name: "main".to_string(),
892                    address: 0x402000,
893                    size: None,
894                    is_external: false,
895                    library: None,
896                },
897                Symbol {
898                    name: "ExitProcess".to_string(),
899                    address: 0x403000,
900                    size: None,
901                    is_external: true,
902                    library: Some("KERNEL32.DLL".to_string()),
903                },
904            ]
905        );
906        assert_eq!(pe.bits(), 32);
907        assert_eq!(pe.endianness(), Endian::Little);
908    }
909
910    #[test]
911    fn only_sections_with_the_execute_bit_are_executable() {
912        let mut pe = binary(PeAnalysis {
913            image_base: 0x400000,
914            entrypoint: 0x401000,
915            known_functions: vec![],
916            imports: vec![],
917        });
918        let section = |name: &str, start: u64, executable: bool| PeSection {
919            name: name.to_string(),
920            start,
921            mem_size: 0x200,
922            data: vec![0x90; 0x10],
923            writable: !executable,
924            executable,
925        };
926        pe.sections = vec![
927            section(".text", 0x401000, true),
928            section(".data", 0x402000, false),
929        ];
930
931        assert!(pe.is_executable(0x401000));
932        assert!(!pe.is_executable(0x402000), ".data has no execute bit");
933        assert!(!pe.is_executable(0x500000), "unmapped");
934        // A snapshot built from the mapped regions must agree.
935        let flags: Vec<(u64, bool)> = pe
936            .mapped_regions()
937            .iter()
938            .map(|(start, _, exec, _)| (*start, *exec))
939            .collect();
940        assert_eq!(flags, vec![(0x401000, true), (0x402000, false)]);
941    }
942
943    #[test]
944    fn named_entrypoint_is_not_also_start() {
945        let pe = binary(PeAnalysis {
946            image_base: 0x400000,
947            entrypoint: 0x401000,
948            known_functions: vec![function(0x401000, "mainCRTStartup", None)],
949            imports: vec![],
950        });
951
952        assert_eq!(pe.symbol_name(0x401000), Some("mainCRTStartup"));
953        assert_eq!(pe.symbol_address("mainCRTStartup"), Some(0x401000));
954        assert_eq!(pe.symbol_address("_start"), None);
955    }
956}