Skip to main content

wazabin_binary/
lib.rs

1//! Binary container formats and the [`BinaryFormat`] trait.
2//!
3//! This is a leaf crate below `qcode`: it holds the [`Arch`] enum, the
4//! [`TargetOs`] enum, and the ELF/PE/LE/blob container parsers behind a single
5//! [`BinaryFormat`] trait. `qcode` re-exports [`TargetOs`] and (in Stage 2b)
6//! implements [`BinaryFormat`] for its serializable `MemoryImage`; `harbinger`
7//! re-exports this crate as `harbinger::format` and `harbinger::arch::Arch`.
8
9mod arch;
10mod symbols;
11mod target_os;
12
13pub mod blob;
14pub mod eh_frame;
15pub mod elf;
16pub mod le;
17pub mod pe;
18
19pub use arch::Arch;
20pub use target_os::TargetOs;
21
22/// The byte order a container was parsed with.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum Endian {
25    Little,
26    Big,
27}
28
29/// A container format this crate can parse, as sniffed from a file's magic.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum Format {
32    /// `\x7fELF`.
33    Elf,
34    /// An `MZ` stub whose `e_lfanew` points at a `PE\0\0` signature.
35    Pe,
36    /// An `MZ` stub whose `e_lfanew` points at an `LE` header: a DOS-extended
37    /// (DOS/4GW) program or a VxD.
38    Le,
39}
40
41impl Format {
42    /// Sniff the container format from the start of a file, or `None` when
43    /// the bytes match none (a raw blob, a bare DOS `MZ` executable, or an
44    /// `LX`/`NE` one).
45    pub fn detect(bytes: &[u8]) -> Option<Format> {
46        if bytes.starts_with(b"\x7fELF") {
47            return Some(Format::Elf);
48        }
49        if bytes.starts_with(b"MZ") {
50            let e_lfanew = bytes.get(0x3c..0x40)?;
51            let at = u32::from_le_bytes(e_lfanew.try_into().ok()?) as usize;
52            if bytes.get(at..at + 4) == Some(b"PE\0\0") {
53                return Some(Format::Pe);
54            }
55            if bytes.get(at..at + 2) == Some(b"LE") {
56                return Some(Format::Le);
57            }
58        }
59        None
60    }
61}
62
63impl std::fmt::Display for Format {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        f.write_str(match self {
66            Format::Elf => "elf",
67            Format::Pe => "pe",
68            Format::Le => "le",
69        })
70    }
71}
72
73/// Why [`load`] could not produce a binary.
74#[derive(Debug)]
75pub enum LoadError {
76    /// The bytes are not ELF, PE or LE; callers that accept raw images can
77    /// fall back to [`blob::Blob`] with a load address of their choosing.
78    UnknownFormat,
79    Elf(elf::ElfError),
80    Pe(pe::PeError),
81    Le(le::LeError),
82}
83
84impl std::fmt::Display for LoadError {
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        match self {
87            LoadError::UnknownFormat => write!(f, "not an ELF, PE or LE file"),
88            LoadError::Elf(e) => write!(f, "failed to parse ELF: {e}"),
89            LoadError::Pe(e) => write!(f, "failed to parse PE: {e}"),
90            LoadError::Le(e) => write!(f, "failed to parse LE: {e}"),
91        }
92    }
93}
94
95impl std::error::Error for LoadError {
96    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
97        match self {
98            LoadError::UnknownFormat => None,
99            LoadError::Elf(e) => Some(e),
100            LoadError::Pe(e) => Some(e),
101            LoadError::Le(e) => Some(e),
102        }
103    }
104}
105
106/// Detect the container format of `bytes` and parse it.
107///
108/// This is the entry point for callers that do not care which container
109/// they were handed: the result answers every [`BinaryFormat`] query. Match
110/// on [`Format::detect`] and call [`elf::ElfBinary::parse`],
111/// [`pe::PeBinary::parse`] or [`le::LeBinary::parse`] directly to keep the
112/// concrete type.
113pub fn load(bytes: &[u8]) -> Result<Box<dyn BinaryFormat>, LoadError> {
114    match Format::detect(bytes).ok_or(LoadError::UnknownFormat)? {
115        Format::Elf => elf::ElfBinary::parse(bytes)
116            .map(|b| Box::new(b) as Box<dyn BinaryFormat>)
117            .map_err(LoadError::Elf),
118        Format::Pe => pe::PeBinary::parse(bytes)
119            .map(|b| Box::new(b) as Box<dyn BinaryFormat>)
120            .map_err(LoadError::Pe),
121        Format::Le => le::LeBinary::parse(bytes)
122            .map(|b| Box::new(b) as Box<dyn BinaryFormat>)
123            .map_err(LoadError::Le),
124    }
125}
126
127/// A named region of the image, as the container's own layout table lists
128/// it: an ELF section header or a PE section. Returned by
129/// [`BinaryFormat::sections`].
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct Section {
132    /// The name from the container's string table, e.g. `.text`.
133    pub name: String,
134    /// Link-time virtual address of the first byte.
135    pub address: u64,
136    /// Size in memory, zero-filled tail (`.bss`) included.
137    pub size: u64,
138    /// The container's writable flag (`SHF_WRITE`, `IMAGE_SCN_MEM_WRITE`).
139    pub writable: bool,
140    /// The container's executable flag (`SHF_EXECINSTR`,
141    /// `IMAGE_SCN_MEM_EXECUTE`).
142    pub executable: bool,
143}
144
145/// A named function symbol, as returned by [`BinaryFormat::symbols`].
146#[derive(Debug, Clone, PartialEq, Eq)]
147pub struct Symbol {
148    pub name: String,
149    /// Link-time virtual address of the function's first byte.
150    pub address: u64,
151    /// The function's size in bytes, when the container records one (ELF
152    /// `st_size`, a PE exception-directory entry). `None` when it does not,
153    /// or records zero.
154    pub size: Option<u64>,
155    /// Whether this is an import stub (PLT entry, IAT thunk) rather than a
156    /// function defined in the image.
157    pub is_external: bool,
158    /// For an import stub, the library it resolves to, when known.
159    pub library: Option<String>,
160}
161
162/// Map a byte to its printable ASCII representation.
163///
164/// Returns `b` unchanged for bytes in the printable ASCII range (0x20–0x7e),
165/// and `b'.'` for everything else. Used by hex viewers for the ASCII column.
166pub const fn printable_byte(b: u8) -> u8 {
167    if b >= 0x20 && b <= 0x7e { b } else { b'.' }
168}
169
170/// Return `true` when `b` is a printable ASCII byte.
171///
172/// This intentionally excludes ASCII control characters such as newline and
173/// tab. It is meant for filtering C strings while solving binaries, where
174/// accepting control bytes tends to produce noisy false positives.
175pub const fn is_printable_ascii_byte(b: u8) -> bool {
176    b >= 0x20 && b <= 0x7e
177}
178
179/// A trait representing a loaded binary image with one or more mapped regions
180/// and one or more known entry points.
181///
182/// Both [`blob::Blob`] (raw bytes) and [`elf::ElfBinary`] implement this trait
183/// so that arch disassemblers can accept either format through a single
184/// interface, even when the backing image is sparse.
185///
186/// Impls are immutable after parse, so the trait carries `Send + Sync` bounds:
187/// a parsed binary is shared by reference (`Arc<dyn BinaryFormat>`) across the
188/// analysis pipeline's worker threads.
189pub trait BinaryFormat: Send + Sync {
190    /// The lowest virtual address mapped by this binary image.
191    fn load_address(&self) -> u64;
192
193    /// Return the byte mapped at `addr`, or `None` if the address is unmapped.
194    fn byte_at(&self, addr: u64) -> Option<u8>;
195
196    /// Return the contiguous bytes available at `addr`.
197    ///
198    /// The returned slice covers the current mapped region from `addr` onward.
199    /// Implementations may return an owned buffer when the region is backed by
200    /// implicit zero-fill rather than file bytes.
201    fn bytes_at(&self, addr: u64) -> Option<&[u8]>;
202
203    /// Known entry points into this binary (entrypoint, symbol table functions, etc.).
204    /// The recursive disassembler should be seeded with these addresses.
205    fn entry_points(&self) -> Vec<u64>;
206
207    /// The binary's primary entry point (e.g. the ELF `e_entry`), if the format
208    /// designates one. Unlike [`entry_points`], this is the single address where
209    /// execution begins. Returns `None` for formats with no distinguished entry.
210    ///
211    /// [`entry_points`]: Self::entry_points
212    fn entrypoint(&self) -> Option<u64> {
213        None
214    }
215
216    /// Name of the architecture, should use embedded information from known binary
217    /// format, or raw values from the blob.
218    fn architecture(&self) -> Arch;
219
220    /// The byte order the container declares (ELF `EI_DATA`); PE is always
221    /// little-endian. Defaults to little-endian for formats that record none.
222    fn endianness(&self) -> Endian {
223        Endian::Little
224    }
225
226    /// The container's word size in bits, 32 or 64 (ELF `EI_CLASS`, PE32 vs
227    /// PE32+). Defaults to 64 for formats that record none.
228    fn bits(&self) -> u32 {
229        64
230    }
231
232    /// The operating system this binary targets, inferred from the container
233    /// format. Defaults to [`TargetOs::Unknown`]; PE returns Windows, ELF Linux.
234    fn os(&self) -> TargetOs {
235        TargetOs::Unknown
236    }
237
238    /// Library names this binary links against: ELF `DT_NEEDED` sonames,
239    /// PE import-directory DLL names (original case; matching is
240    /// case-insensitive). Empty when the format has no such notion (Blob).
241    fn linked_libraries(&self) -> Vec<String> {
242        Vec::new()
243    }
244
245    /// The container's layout table, in address order: an ELF file's
246    /// allocated section headers, a PE file's sections. Coarser than
247    /// [`mapped_regions`] for ELF (one `PT_LOAD` holds several sections) and
248    /// finer-named. Empty for formats with no such table (Blob).
249    ///
250    /// [`mapped_regions`]: Self::mapped_regions
251    fn sections(&self) -> Vec<Section> {
252        Vec::new()
253    }
254
255    /// Every named function symbol, in address order: what
256    /// [`symbol_name`](Self::symbol_name) would answer for each address, with
257    /// the size and import provenance the container records. Empty for
258    /// formats with no symbol information.
259    fn symbols(&self) -> Vec<Symbol> {
260        Vec::new()
261    }
262
263    /// Return the symbol name for the function starting at `addr`, if the
264    /// binary format has one (e.g. from an ELF symbol table).
265    /// Returns `None` for formats with no symbol information.
266    ///
267    /// `addr` is a link-time address, as [`load_address`] and [`entry_points`]
268    /// report them: for a position-independent executable or shared object
269    /// the loader adds a base of its choosing, so subtract that base from a
270    /// run-time address before asking. The ELF and PE implementations answer
271    /// from an index built at parse time rather than scanning their function
272    /// table, so a caller may ask per address. The inverse lookup is
273    /// [`symbol_address`].
274    ///
275    /// [`load_address`]: Self::load_address
276    /// [`entry_points`]: Self::entry_points
277    /// [`symbol_address`]: Self::symbol_address
278    fn symbol_name(&self, _addr: u64) -> Option<&str> {
279        None
280    }
281
282    /// Return the address of the function symbol called `name`, if the binary
283    /// format has one (e.g. `main` from an ELF `.symtab`, or an import stub
284    /// named after the function it resolves to).
285    /// Returns `None` for formats with no symbol information.
286    ///
287    /// The address is the link-time one, as [`load_address`] and
288    /// [`entry_points`] report them: for a position-independent executable or
289    /// shared object it is relative to whatever base the loader picks, so add
290    /// that base to reach the function at run time. When several functions
291    /// share a name, a defined function is preferred over an import stub, and
292    /// otherwise the lowest address is returned. The ELF and PE
293    /// implementations answer from an index built at parse time rather than
294    /// scanning their function table. The inverse lookup is [`symbol_name`].
295    ///
296    /// [`load_address`]: Self::load_address
297    /// [`entry_points`]: Self::entry_points
298    /// [`symbol_name`]: Self::symbol_name
299    fn symbol_address(&self, _name: &str) -> Option<u64> {
300        None
301    }
302
303    /// Returns `true` if `addr` is an external (imported) function stub,
304    /// e.g. a PLT thunk.  The recursive disassembler will not lift the body
305    /// of external functions.  Defaults to `false`.
306    fn is_external_symbol(&self, _addr: u64) -> bool {
307        false
308    }
309
310    /// Return the name of the library providing the external function stub at
311    /// `addr`: the PE import-directory DLL, or the ELF `.gnu.version_r` soname
312    /// the symbol's version requirement points at. `None` when the format does
313    /// not record a per-symbol source library (e.g. an unversioned ELF import).
314    fn import_library(&self, _addr: u64) -> Option<&str> {
315        None
316    }
317
318    /// Return the imported symbol whose resolver slot lives at `addr`, if any.
319    ///
320    /// ELF uses this for GOT / PLT relocation slots such as `R_X86_64_GLOB_DAT`
321    /// and `R_X86_64_JUMP_SLOT`.
322    fn import_symbol_name(&self, _addr: u64) -> Option<&str> {
323        None
324    }
325
326    /// Return rows of bytes suitable for a hex viewer.
327    ///
328    /// The first row is aligned down to the nearest `width`-byte boundary.
329    /// Each row is `(row_address, bytes)` where a byte is `None` when the
330    /// address is unmapped (e.g. a hole in a sparse ELF image).
331    ///
332    /// # Panics
333    /// Panics if `width` is zero.
334    fn hex_rows(&self, addr: u64, len: usize, width: usize) -> Vec<(u64, Vec<Option<u8>>)> {
335        assert!(width > 0, "hex row width must be non-zero");
336        let row_start = addr - addr % width as u64;
337        let end = addr.saturating_add(len as u64);
338        let mut rows = Vec::new();
339        let mut cur = row_start;
340        while cur < end {
341            let bytes = (0..width as u64).map(|i| self.byte_at(cur + i)).collect();
342            rows.push((cur, bytes));
343            cur = cur.saturating_add(width as u64);
344        }
345        rows
346    }
347
348    /// Return `true` if `addr` is mapped by this binary image.
349    fn contains(&self, addr: u64) -> bool {
350        self.byte_at(addr).is_some()
351    }
352
353    /// Enumerate the binary's mapped regions as
354    /// `(start, bytes, executable, writable)`.
355    ///
356    /// At snapshot-save time the persistence layer copies these into a
357    /// serializable `MemoryImage` so a reloaded session is self-describing.
358    /// Each region's `bytes` should cover its full in-memory size (zero-filled
359    /// tail included), mirroring [`byte_at`].
360    ///
361    /// Defaults to empty for formats that do not expose their segments.
362    ///
363    /// [`byte_at`]: Self::byte_at
364    fn mapped_regions(&self) -> Vec<(u64, Vec<u8>, bool, bool)> {
365        Vec::new()
366    }
367
368    /// Return `true` if `addr` lies in an executable region of this binary
369    /// image. Defaults to "mapped" for formats that don't track per-region
370    /// permissions; formats with permission information (e.g. ELF segment
371    /// flags) should override this.
372    fn is_executable(&self, addr: u64) -> bool {
373        self.contains(addr)
374    }
375
376    /// The `[start, end)` bounds of the mapped region containing `addr`, if
377    /// any. Used to key per-segment facts (e.g. executability propositions)
378    /// so repeated queries in one region collapse to a single entry. Defaults
379    /// to `None` for formats that do not expose their segments.
380    fn segment_bounds(&self, _addr: u64) -> Option<(u64, u64)> {
381        None
382    }
383
384    /// Return `true` only if `addr` lies in a region *known* to be writable
385    /// (from the container's segment flags). Passes that fold a value out of
386    /// initialized memory use this to refuse mutable memory — e.g. a GOT slot
387    /// the dynamic linker overwrites at load time. Defaults to `false`
388    /// ("not proven writable"); `Blob` keeps the default.
389    fn is_known_writable(&self, _addr: u64) -> bool {
390        false
391    }
392
393    /// Return `true` only if `addr` lies in a region *proven* read-only (mapped,
394    /// and the container's own permission data says the region is not writable).
395    ///
396    /// This is **not** the negation of [`is_known_writable`](Self::is_known_writable): a format that
397    /// records no permissions answers `false` to both, which reads as "unknown"
398    /// rather than "read-only". Consumers that reconstruct a *value* out of
399    /// initialized memory — the decompiler rendering a `.rodata` string constant
400    /// as a named object — need the positive proof, because a writable byte may
401    /// be a different byte at run time.
402    ///
403    /// Defaults to `false` ("not proven read-only"); `Blob` and `PeBinary` keep
404    /// the default, the latter because it does not parse section permissions.
405    fn is_known_read_only(&self, _addr: u64) -> bool {
406        false
407    }
408
409    /// Read `n` bytes at virtual address `addr`.
410    ///
411    /// Returns `None` if any byte in the requested range is unmapped.
412    fn read_bytes(&self, addr: u64, n: usize) -> Option<Vec<u8>> {
413        let mut out = Vec::with_capacity(n);
414        for offset in 0..n {
415            out.push(self.byte_at(addr.checked_add(offset as u64)?)?);
416        }
417        Some(out)
418    }
419
420    /// Read a little-endian unsigned integer of `size` bytes (1..=8) at `addr`.
421    ///
422    /// Returns `None` if the size is out of range or any byte is unmapped.
423    fn read_uint(&self, addr: u64, size: usize) -> Option<u64> {
424        if size == 0 || size > 8 {
425            return None;
426        }
427        let bytes = self.read_bytes(addr, size)?;
428        let mut value = 0u64;
429        for (i, &b) in bytes.iter().enumerate() {
430            value |= (b as u64) << (i * 8);
431        }
432        Some(value)
433    }
434
435    /// Read a null-terminated C string at virtual address `addr`, returning the
436    /// bytes up to (but not including) the null terminator.
437    ///
438    /// If `max_len` is `Some(limit)`, only the first `limit` bytes are searched
439    /// for the null terminator. Returns `None` if the address is out of range or
440    /// no null terminator is found within the (optionally limited) region.
441    fn read_cstring(&self, addr: u64, max_len: Option<usize>) -> Option<Vec<u8>> {
442        let limit = max_len.unwrap_or(usize::MAX);
443        let mut out = Vec::new();
444        for offset in 0..limit {
445            let byte = self.byte_at(addr.checked_add(offset as u64)?)?;
446            if byte == 0 {
447                return Some(out);
448            }
449            out.push(byte);
450        }
451        None
452    }
453
454    /// Read a null-terminated C string at virtual address `addr`, requiring
455    /// every byte before the null terminator to be printable ASCII.
456    ///
457    /// Printable bytes are in the inclusive range `0x20..=0x7e`. Returns
458    /// `None` if the address is out of range, no null terminator is found
459    /// within the optional search window, or a non-printable byte appears
460    /// before the terminator.
461    fn read_printable_cstring(&self, addr: u64, max_len: Option<usize>) -> Option<Vec<u8>> {
462        let limit = max_len.unwrap_or(usize::MAX);
463        let mut out = Vec::new();
464        for offset in 0..limit {
465            let byte = self.byte_at(addr.checked_add(offset as u64)?)?;
466            if byte == 0 {
467                return Some(out);
468            }
469            if !is_printable_ascii_byte(byte) {
470                return None;
471            }
472            out.push(byte);
473        }
474        None
475    }
476}
477
478#[cfg(test)]
479mod tests {
480    use super::{BinaryFormat, Endian, Format, LoadError, blob::Blob, load};
481
482    #[test]
483    fn detects_elf_by_magic() {
484        assert_eq!(Format::detect(b"\x7fELF\x02\x01\x01"), Some(Format::Elf));
485        assert_eq!(Format::detect(b"\x7fEL"), None);
486    }
487
488    #[test]
489    fn detects_pe_only_behind_a_pe_signature() {
490        let mut pe = vec![0u8; 0x80];
491        pe[..2].copy_from_slice(b"MZ");
492        pe[0x3c..0x40].copy_from_slice(&0x40u32.to_le_bytes());
493        assert_eq!(Format::detect(&pe), None);
494        pe[0x40..0x44].copy_from_slice(b"PE\0\0");
495        assert_eq!(Format::detect(&pe), Some(Format::Pe));
496
497        // A bare DOS executable, or an `MZ` too short to hold `e_lfanew`.
498        assert_eq!(Format::detect(b"MZ\x90\x00"), None);
499        let mut dos = vec![0u8; 0x80];
500        dos[..2].copy_from_slice(b"MZ");
501        assert_eq!(Format::detect(&dos), None);
502
503        // `LE` behind the stub; `LX` is not claimed.
504        dos[0x3c..0x40].copy_from_slice(&0x40u32.to_le_bytes());
505        dos[0x40..0x42].copy_from_slice(b"LE");
506        assert_eq!(Format::detect(&dos), Some(Format::Le));
507        dos[0x40..0x42].copy_from_slice(b"LX");
508        assert_eq!(Format::detect(&dos), None);
509    }
510
511    #[test]
512    fn detects_nothing_in_a_blob() {
513        assert_eq!(Format::detect(b""), None);
514        assert_eq!(Format::detect(&[0x55, 0x48, 0x89, 0xe5]), None);
515        assert!(matches!(load(b"\x90\x90"), Err(LoadError::UnknownFormat)));
516    }
517
518    #[test]
519    fn blob_keeps_the_trait_defaults() {
520        let blob = Blob::new(0x1000, vec![0x90]);
521        assert_eq!(blob.endianness(), Endian::Little);
522        assert_eq!(blob.bits(), 64);
523        assert!(blob.sections().is_empty());
524        assert!(blob.symbols().is_empty());
525    }
526
527    #[test]
528    fn read_printable_cstring_accepts_printable_ascii() {
529        let blob = Blob::new(0x1000, b"hello, world!\0next".to_vec());
530
531        assert_eq!(
532            blob.read_printable_cstring(0x1000, None),
533            Some(b"hello, world!".to_vec())
534        );
535    }
536
537    #[test]
538    fn read_printable_cstring_rejects_control_bytes() {
539        let blob = Blob::new(0x1000, b"line\nbreak\0".to_vec());
540
541        assert_eq!(
542            blob.read_cstring(0x1000, None),
543            Some(b"line\nbreak".to_vec())
544        );
545        assert_eq!(blob.read_printable_cstring(0x1000, None), None);
546    }
547
548    #[test]
549    fn read_printable_cstring_rejects_non_ascii_bytes() {
550        let blob = Blob::new(0x1000, b"caf\xe9\0".to_vec());
551
552        assert_eq!(blob.read_printable_cstring(0x1000, None), None);
553    }
554
555    #[test]
556    fn read_printable_cstring_honors_max_len() {
557        let blob = Blob::new(0x1000, b"hello\0".to_vec());
558
559        assert_eq!(blob.read_printable_cstring(0x1000, Some(3)), None);
560        assert_eq!(
561            blob.read_printable_cstring(0x1000, Some(6)),
562            Some(b"hello".to_vec())
563        );
564    }
565}