Skip to main content

wazabin_binary/
le.rs

1//! Linear Executable (`LE`): the 32-bit container of DOS extenders (DOS/4GW,
2//! the Watcom toolchain's default) and of Windows 3.x VxDs.
3//!
4//! The file is an `MZ` stub (for a DOS/4GW program, the extender itself or a
5//! stub that loads it) whose `e_lfanew` points at the `LE` header. Code and
6//! data live in *objects*, each with a preferred linear base address and a run
7//! of fixed-size pages. The loader is expected to relocate every object, so the
8//! page bytes of an absolute reference hold the offset *within its target
9//! object*, not a linear address: the fixup records name each such location.
10//!
11//! [`LeBinary::parse`] maps every object at its preferred base and applies the
12//! fixups whose value it can compute (internal references, as offsets and as
13//! self-relative displacements), so the bytes it serves read as a flat 32-bit
14//! image. It keeps every fixup in [`LeBinary::fixups`] too: they are the exact
15//! set of locations that hold an address, and the selector halves (which only
16//! the run-time extender can fill) are left for the consumer.
17//!
18//! Only `LE` is handled. `LX` (OS/2 2.x) shares the header but changes the page
19//! map and allows compressed pages; it is reported as [`LeError::Lx`].
20
21use crate::{Arch, BinaryFormat, Endian, Section};
22
23/// Object flag: the object is executable.
24pub const OBJ_EXECUTABLE: u32 = 0x0004;
25/// Object flag: the object is writable.
26pub const OBJ_WRITABLE: u32 = 0x0002;
27/// Object flag: the object is readable.
28pub const OBJ_READABLE: u32 = 0x0001;
29/// Object flag ("big/default"): a 32-bit code object (USE32), or a data object
30/// addressed with 32-bit offsets.
31pub const OBJ_BIG: u32 = 0x2000;
32
33/// One object of the image, with the file's pages concatenated and the
34/// internal fixups applied.
35#[derive(Debug, Clone)]
36pub struct LeObject {
37    /// The 1-based object number fixup records and the header refer to.
38    pub number: u32,
39    /// Preferred linear base address (`reloc base addr`).
40    pub base: u64,
41    /// Size in memory. Bytes past `data.len()` are zero.
42    pub virtual_size: u64,
43    /// The object-table flags (`OBJ_*`).
44    pub flags: u32,
45    /// The object's file-backed bytes, fixups applied; at most `virtual_size`.
46    pub data: Vec<u8>,
47}
48
49impl LeObject {
50    pub fn executable(&self) -> bool {
51        self.flags & OBJ_EXECUTABLE != 0
52    }
53
54    pub fn writable(&self) -> bool {
55        self.flags & OBJ_WRITABLE != 0
56    }
57
58    /// 32-bit (USE32) rather than 16-bit.
59    pub fn big(&self) -> bool {
60        self.flags & OBJ_BIG != 0
61    }
62
63    fn end(&self) -> u64 {
64        self.base + self.virtual_size
65    }
66
67    fn contains(&self, addr: u64) -> bool {
68        addr >= self.base && addr < self.end()
69    }
70}
71
72/// What a fixup writes at its source location (the low nibble of the record's
73/// source byte).
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum LeFixupKind {
76    /// `0x0`: the low byte of the target offset.
77    Byte,
78    /// `0x2`: the target object's 16-bit selector.
79    Selector16,
80    /// `0x3`: a 16:16 far pointer (offset, then selector).
81    Pointer16_16,
82    /// `0x5`: a 16-bit offset.
83    Offset16,
84    /// `0x6`: a 16:32 far pointer (32-bit offset, then selector).
85    Pointer16_32,
86    /// `0x7`: a 32-bit offset.
87    Offset32,
88    /// `0x8`: a 32-bit displacement relative to the end of the field.
89    Relative32,
90}
91
92impl LeFixupKind {
93    fn from_nibble(n: u8) -> Option<Self> {
94        Some(match n {
95            0x0 => LeFixupKind::Byte,
96            0x2 => LeFixupKind::Selector16,
97            0x3 => LeFixupKind::Pointer16_16,
98            0x5 => LeFixupKind::Offset16,
99            0x6 => LeFixupKind::Pointer16_32,
100            0x7 => LeFixupKind::Offset32,
101            0x8 => LeFixupKind::Relative32,
102            _ => return None,
103        })
104    }
105
106    /// Whether the fixup's value includes the target's selector, which only
107    /// the run-time extender knows.
108    pub fn has_selector(self) -> bool {
109        matches!(
110            self,
111            LeFixupKind::Selector16 | LeFixupKind::Pointer16_16 | LeFixupKind::Pointer16_32
112        )
113    }
114}
115
116/// What a fixup refers to.
117#[derive(Debug, Clone, PartialEq, Eq)]
118pub enum LeFixupTarget {
119    /// An offset in one of this module's objects. `offset` is 0 for a
120    /// [`LeFixupKind::Selector16`] fixup, which names only the object.
121    Internal { object: u32, offset: u32 },
122    /// An export of an imported module, by ordinal. `module` is 1-based into
123    /// [`LeBinary::import_modules`].
124    ImportOrdinal {
125        module: u16,
126        ordinal: u32,
127        additive: u32,
128    },
129    /// An export of an imported module, by name.
130    ImportName {
131        module: u16,
132        name: String,
133        additive: u32,
134    },
135    /// An entry of this module's entry table.
136    Entry { ordinal: u16, additive: u32 },
137}
138
139/// One fixup: a location of the image that holds an address.
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct LeFixup {
142    /// Linear address of the first byte the fixup writes.
143    pub address: u64,
144    pub kind: LeFixupKind,
145    pub target: LeFixupTarget,
146    /// The record's "fixup to 16:16 alias" flag.
147    pub alias: bool,
148}
149
150/// A parsed `LE` image.
151#[derive(Debug, Clone)]
152pub struct LeBinary {
153    /// The header's CPU type: 1 = 286, 2 = 386, 3 = 486.
154    pub cpu: u16,
155    /// The header's target OS field. Watcom's DOS/4GW links write 1 (OS/2);
156    /// the container does not say "DOS", the stub that loads it does.
157    pub os_type: u16,
158    /// The header's module flags.
159    pub module_flags: u32,
160    pub page_size: u32,
161    /// The module name: the first entry of the resident name table.
162    pub module_name: Option<String>,
163    /// Import module names, in the order fixup records number them (1-based).
164    pub import_modules: Vec<String>,
165    /// Objects in object-table order (`objects[n - 1]` is object `n`).
166    pub objects: Vec<LeObject>,
167    /// Every fixup record, sources in ascending address order.
168    pub fixups: Vec<LeFixup>,
169    /// Linear address of the initial `EIP`.
170    pub entrypoint: Option<u64>,
171    /// Linear address of the initial `ESP`.
172    pub initial_stack: Option<u64>,
173}
174
175/// Why an `LE` image could not be parsed.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub enum LeError {
178    /// No `MZ` stub, or `e_lfanew` does not point at an `LE` signature.
179    NotLe,
180    /// The header is `LX`, which this parser does not handle.
181    Lx,
182    /// The header declares a big-endian byte or word order.
183    BigEndian,
184    /// A table or page lies past the end of the file.
185    Truncated(&'static str),
186    /// A page-map entry is iterated (`EXEPACK`) or of an unknown type.
187    UnsupportedPage { page: u32, flags: u8 },
188    /// A fixup record has a source type or target type outside the spec.
189    BadFixup { offset: usize },
190    /// A header or fixup names an object the object table does not have.
191    BadObject(u32),
192}
193
194impl std::fmt::Display for LeError {
195    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
196        match self {
197            LeError::NotLe => write!(f, "not an LE executable"),
198            LeError::Lx => write!(f, "LX executables are not supported"),
199            LeError::BigEndian => write!(f, "big-endian LE executables are not supported"),
200            LeError::Truncated(what) => write!(f, "LE {what} lies past the end of the file"),
201            LeError::UnsupportedPage { page, flags } => {
202                write!(f, "LE page {page} has unsupported type {flags}")
203            }
204            LeError::BadFixup { offset } => {
205                write!(f, "malformed LE fixup record at file offset 0x{offset:x}")
206            }
207            LeError::BadObject(n) => write!(f, "LE refers to missing object {n}"),
208        }
209    }
210}
211
212impl std::error::Error for LeError {}
213
214/// The file offset of the `LE`/`LX` header, if `bytes` is an `MZ` stub whose
215/// `e_lfanew` points at one.
216pub(crate) fn header_offset(bytes: &[u8]) -> Option<(usize, [u8; 2])> {
217    if !bytes.starts_with(b"MZ") {
218        return None;
219    }
220    let at = u32::from_le_bytes(bytes.get(0x3c..0x40)?.try_into().ok()?) as usize;
221    let sig: [u8; 2] = bytes.get(at..at + 2)?.try_into().ok()?;
222    matches!(&sig, b"LE" | b"LX").then_some((at, sig))
223}
224
225/// Little-endian reads that fail with the name of what was being read.
226struct Reader<'a> {
227    bytes: &'a [u8],
228}
229
230impl Reader<'_> {
231    fn u8(&self, at: usize, what: &'static str) -> Result<u8, LeError> {
232        self.bytes.get(at).copied().ok_or(LeError::Truncated(what))
233    }
234
235    fn u16(&self, at: usize, what: &'static str) -> Result<u16, LeError> {
236        let b = self.bytes.get(at..at + 2).ok_or(LeError::Truncated(what))?;
237        Ok(u16::from_le_bytes([b[0], b[1]]))
238    }
239
240    fn u32(&self, at: usize, what: &'static str) -> Result<u32, LeError> {
241        let b = self.bytes.get(at..at + 4).ok_or(LeError::Truncated(what))?;
242        Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
243    }
244
245    /// A length-prefixed string, as the name tables store them.
246    fn pstr(&self, at: usize, what: &'static str) -> Result<String, LeError> {
247        let len = self.u8(at, what)? as usize;
248        let b = self
249            .bytes
250            .get(at + 1..at + 1 + len)
251            .ok_or(LeError::Truncated(what))?;
252        Ok(String::from_utf8_lossy(b).into_owned())
253    }
254}
255
256impl LeBinary {
257    pub fn parse(bytes: &[u8]) -> Result<Self, LeError> {
258        let (le, sig) = header_offset(bytes).ok_or(LeError::NotLe)?;
259        if &sig == b"LX" {
260            return Err(LeError::Lx);
261        }
262        let r = Reader { bytes };
263        let h8 = |off: usize| r.u8(le + off, "header");
264        let h16 = |off: usize| r.u16(le + off, "header");
265        let h32 = |off: usize| r.u32(le + off, "header");
266        if h8(0x02)? != 0 || h8(0x03)? != 0 {
267            return Err(LeError::BigEndian);
268        }
269
270        let module_pages = h32(0x14)?;
271        let page_size = h32(0x28)?;
272        let last_page_size = h32(0x2c)?;
273        let object_table = le + h32(0x40)? as usize;
274        let object_count = h32(0x44)?;
275        let page_map = le + h32(0x48)? as usize;
276        let resident_names = h32(0x58)?;
277        let fixup_pages = le + h32(0x68)? as usize;
278        let fixup_records = le + h32(0x6c)? as usize;
279        let import_module_table = le + h32(0x70)? as usize;
280        let import_module_count = h32(0x74)?;
281        let import_procs = le + h32(0x78)? as usize;
282        // The one offset in the header that counts from the start of the file.
283        let data_pages = h32(0x80)? as usize;
284
285        let module_name = if resident_names != 0 {
286            Some(r.pstr(le + resident_names as usize, "resident name table")?)
287                .filter(|n| !n.is_empty())
288        } else {
289            None
290        };
291
292        let mut import_modules = Vec::new();
293        let mut at = import_module_table;
294        for _ in 0..import_module_count {
295            let name = r.pstr(at, "import module table")?;
296            at += 1 + name.len();
297            import_modules.push(name);
298        }
299
300        // Objects, and for each object page the logical page number that
301        // indexes the fixup page table.
302        let mut objects = Vec::new();
303        let mut pages: Vec<(u32, u64)> = Vec::new(); // (logical page, linear address)
304        for i in 0..object_count {
305            let e = object_table + 24 * i as usize;
306            let virtual_size = r.u32(e, "object table")? as u64;
307            let base = r.u32(e + 4, "object table")? as u64;
308            let flags = r.u32(e + 8, "object table")?;
309            let first_page = r.u32(e + 12, "object table")?;
310            let page_count = r.u32(e + 16, "object table")?;
311
312            let mut data = Vec::new();
313            for j in 0..page_count {
314                let logical = first_page + j;
315                let pm = page_map + 4 * (logical as usize - 1);
316                // LE page-map entry: a 24-bit big-endian page number, then a type.
317                let number = (r.u8(pm, "page map")? as u32) << 16
318                    | (r.u8(pm + 1, "page map")? as u32) << 8
319                    | r.u8(pm + 2, "page map")? as u32;
320                let kind = r.u8(pm + 3, "page map")?;
321                data.resize((j * page_size) as usize, 0);
322                match kind {
323                    0 => {
324                        let size = if number == module_pages {
325                            last_page_size
326                        } else {
327                            page_size
328                        };
329                        let start = data_pages + (number as usize - 1) * page_size as usize;
330                        let page = bytes
331                            .get(start..start + size as usize)
332                            .ok_or(LeError::Truncated("page"))?;
333                        data.extend_from_slice(page);
334                    }
335                    // Zero-filled (3) and invalid (2) pages read as zeros.
336                    2 | 3 => data.resize(((j + 1) * page_size) as usize, 0),
337                    flags => {
338                        return Err(LeError::UnsupportedPage {
339                            page: logical,
340                            flags,
341                        });
342                    }
343                }
344                pages.push((logical, base + (j * page_size) as u64));
345            }
346            data.truncate(virtual_size as usize);
347            objects.push(LeObject {
348                number: i + 1,
349                base,
350                virtual_size,
351                flags,
352                data,
353            });
354        }
355
356        let mut fixups = Vec::new();
357        for &(logical, page_va) in &pages {
358            let slot = fixup_pages + 4 * (logical as usize - 1);
359            let start = fixup_records + r.u32(slot, "fixup page table")? as usize;
360            let end = fixup_records + r.u32(slot + 4, "fixup page table")? as usize;
361            let mut at = start;
362            while at < end {
363                at = parse_fixup(&r, at, page_va, import_procs, &mut fixups)?;
364            }
365        }
366        fixups.sort_by_key(|f| f.address);
367
368        let mut binary = LeBinary {
369            cpu: h16(0x08)?,
370            os_type: h16(0x0a)?,
371            module_flags: h32(0x10)?,
372            page_size,
373            module_name,
374            import_modules,
375            objects,
376            fixups: Vec::new(),
377            entrypoint: None,
378            initial_stack: None,
379        };
380        binary.entrypoint = binary.linear(h32(0x18)?, h32(0x1c)?)?;
381        binary.initial_stack = binary.linear(h32(0x20)?, h32(0x24)?)?;
382        for f in &fixups {
383            binary.apply(f)?;
384        }
385        binary.fixups = fixups;
386        Ok(binary)
387    }
388
389    /// The linear address of `offset` in object `object`, or `None` when the
390    /// object number is 0 (the header's "none").
391    fn linear(&self, object: u32, offset: u32) -> Result<Option<u64>, LeError> {
392        if object == 0 {
393            return Ok(None);
394        }
395        let obj = self.object(object)?;
396        Ok(Some(obj.base + offset as u64))
397    }
398
399    fn object(&self, number: u32) -> Result<&LeObject, LeError> {
400        (number as usize)
401            .checked_sub(1)
402            .and_then(|i| self.objects.get(i))
403            .ok_or(LeError::BadObject(number))
404    }
405
406    /// The linear address a fixup refers to, when the image alone determines
407    /// it: an internal reference. Imports and entry-table references need the
408    /// run-time loader.
409    pub fn fixup_target(&self, fixup: &LeFixup) -> Option<u64> {
410        match fixup.target {
411            LeFixupTarget::Internal { object, offset } => {
412                self.linear(object, offset).ok().flatten()
413            }
414            _ => None,
415        }
416    }
417
418    /// Write the offset part of an internal fixup into its object's bytes.
419    /// Selector parts are left as the file has them.
420    fn apply(&mut self, fixup: &LeFixup) -> Result<(), LeError> {
421        let LeFixupTarget::Internal { object, .. } = fixup.target else {
422            return Ok(());
423        };
424        let target = self.fixup_target(fixup).ok_or(LeError::BadObject(object))?;
425        let at = fixup.address;
426        let value: Vec<u8> = match fixup.kind {
427            LeFixupKind::Selector16 => return Ok(()),
428            LeFixupKind::Byte => vec![target as u8],
429            LeFixupKind::Offset16 | LeFixupKind::Pointer16_16 => {
430                (target as u16).to_le_bytes().to_vec()
431            }
432            LeFixupKind::Offset32 | LeFixupKind::Pointer16_32 => {
433                (target as u32).to_le_bytes().to_vec()
434            }
435            LeFixupKind::Relative32 => (target.wrapping_sub(at + 4) as u32).to_le_bytes().to_vec(),
436        };
437        // A fixup may straddle the end of its object's file-backed bytes: the
438        // zero-filled tail is part of the object, so `data` grows to hold it
439        // (up to the virtual size). RUN.EXE's last fini record's pointer does.
440        if let Some(obj) = self.objects.iter_mut().find(|o| o.contains(at)) {
441            let off = (at - obj.base) as usize;
442            let end = (off + value.len()).min(obj.virtual_size as usize);
443            if obj.data.len() < end {
444                obj.data.resize(end, 0);
445            }
446            for (i, b) in value.into_iter().enumerate() {
447                if let Some(slot) = obj.data.get_mut(off + i) {
448                    *slot = b;
449                }
450            }
451        }
452        Ok(())
453    }
454
455    fn object_at(&self, addr: u64) -> Option<&LeObject> {
456        self.objects.iter().find(|o| o.contains(addr))
457    }
458}
459
460/// Parse the fixup record at file offset `at`, whose source offsets are
461/// relative to the page at `page_va`; push one [`LeFixup`] per source and
462/// return the offset of the next record.
463fn parse_fixup(
464    r: &Reader<'_>,
465    at: usize,
466    page_va: u64,
467    import_procs: usize,
468    out: &mut Vec<LeFixup>,
469) -> Result<usize, LeError> {
470    let bad = LeError::BadFixup { offset: at };
471    let src = r.u8(at, "fixup record")?;
472    let flags = r.u8(at + 1, "fixup record")?;
473    let kind = LeFixupKind::from_nibble(src & 0x0f).ok_or(bad.clone())?;
474    let alias = src & 0x10 != 0;
475    let source_list = src & 0x20 != 0;
476    let mut p = at + 2;
477
478    // The source offset (signed: a fixup may start on the previous page), or
479    // the count of offsets listed after the target.
480    let (first, count) = if source_list {
481        let n = r.u8(p, "fixup record")?;
482        p += 1;
483        (None, n)
484    } else {
485        let off = r.u16(p, "fixup record")? as i16;
486        p += 2;
487        (Some(off), 1)
488    };
489
490    let read_object = |p: &mut usize| -> Result<u16, LeError> {
491        if flags & 0x40 != 0 {
492            let v = r.u16(*p, "fixup record")?;
493            *p += 2;
494            Ok(v)
495        } else {
496            let v = r.u8(*p, "fixup record")? as u16;
497            *p += 1;
498            Ok(v)
499        }
500    };
501    let read_additive = |p: &mut usize| -> Result<u32, LeError> {
502        if flags & 0x04 == 0 {
503            return Ok(0);
504        }
505        if flags & 0x20 != 0 {
506            let v = r.u32(*p, "fixup record")?;
507            *p += 4;
508            Ok(v)
509        } else {
510            let v = r.u16(*p, "fixup record")? as u32;
511            *p += 2;
512            Ok(v)
513        }
514    };
515    let read_offset = |p: &mut usize| -> Result<u32, LeError> {
516        if flags & 0x10 != 0 {
517            let v = r.u32(*p, "fixup record")?;
518            *p += 4;
519            Ok(v)
520        } else {
521            let v = r.u16(*p, "fixup record")? as u32;
522            *p += 2;
523            Ok(v)
524        }
525    };
526
527    let target = match flags & 0x03 {
528        0 => {
529            let object = read_object(&mut p)? as u32;
530            let offset = if kind == LeFixupKind::Selector16 {
531                0
532            } else {
533                read_offset(&mut p)?
534            };
535            LeFixupTarget::Internal { object, offset }
536        }
537        1 => {
538            let module = read_object(&mut p)?;
539            let ordinal = if flags & 0x80 != 0 {
540                let v = r.u8(p, "fixup record")? as u32;
541                p += 1;
542                v
543            } else {
544                read_offset(&mut p)?
545            };
546            let additive = read_additive(&mut p)?;
547            LeFixupTarget::ImportOrdinal {
548                module,
549                ordinal,
550                additive,
551            }
552        }
553        2 => {
554            let module = read_object(&mut p)?;
555            let name_at = read_offset(&mut p)? as usize;
556            let name = r.pstr(import_procs + name_at, "import procedure name table")?;
557            let additive = read_additive(&mut p)?;
558            LeFixupTarget::ImportName {
559                module,
560                name,
561                additive,
562            }
563        }
564        _ => {
565            let ordinal = read_object(&mut p)?;
566            let additive = read_additive(&mut p)?;
567            LeFixupTarget::Entry { ordinal, additive }
568        }
569    };
570
571    let mut push = |off: i16| {
572        out.push(LeFixup {
573            address: page_va.wrapping_add_signed(off as i64),
574            kind,
575            target: target.clone(),
576            alias,
577        })
578    };
579    match first {
580        Some(off) => push(off),
581        None => {
582            for _ in 0..count {
583                push(r.u16(p, "fixup record")? as i16);
584                p += 2;
585            }
586        }
587    }
588    Ok(p)
589}
590
591impl BinaryFormat for LeBinary {
592    /// The lowest object base.
593    fn load_address(&self) -> u64 {
594        self.objects.iter().map(|o| o.base).min().unwrap_or(0)
595    }
596
597    fn architecture(&self) -> Arch {
598        Arch::I386
599    }
600
601    fn endianness(&self) -> Endian {
602        Endian::Little
603    }
604
605    /// 32 when the entry point's object (or, without one, any code object) is
606    /// USE32; 16 otherwise.
607    fn bits(&self) -> u32 {
608        let code = match self.entrypoint.and_then(|e| self.object_at(e)) {
609            Some(o) => o.big(),
610            None => self.objects.iter().any(|o| o.executable() && o.big()),
611        };
612        if code { 32 } else { 16 }
613    }
614
615    /// Objects have no names; each is reported as `object<N>`.
616    fn sections(&self) -> Vec<Section> {
617        self.objects
618            .iter()
619            .map(|o| Section {
620                name: format!("object{}", o.number),
621                address: o.base,
622                size: o.virtual_size,
623                writable: o.writable(),
624                executable: o.executable(),
625            })
626            .collect()
627    }
628
629    fn linked_libraries(&self) -> Vec<String> {
630        self.import_modules.clone()
631    }
632
633    fn byte_at(&self, addr: u64) -> Option<u8> {
634        let o = self.object_at(addr)?;
635        Some(o.data.get((addr - o.base) as usize).copied().unwrap_or(0))
636    }
637
638    fn bytes_at(&self, addr: u64) -> Option<&[u8]> {
639        let o = self.object_at(addr)?;
640        o.data.get((addr - o.base) as usize..)
641    }
642
643    fn mapped_regions(&self) -> Vec<(u64, Vec<u8>, bool, bool)> {
644        self.objects
645            .iter()
646            .map(|o| {
647                let mut bytes = o.data.clone();
648                bytes.resize(o.virtual_size as usize, 0);
649                (o.base, bytes, o.executable(), o.writable())
650            })
651            .collect()
652    }
653
654    fn is_executable(&self, addr: u64) -> bool {
655        self.object_at(addr).is_some_and(|o| o.executable())
656    }
657
658    fn is_known_writable(&self, addr: u64) -> bool {
659        self.object_at(addr).is_some_and(|o| o.writable())
660    }
661
662    /// DOS extenders do not enforce the read-only flag (DOS/4GW maps every
663    /// object read-write), so an object without it is not proven immutable.
664    fn is_known_read_only(&self, _addr: u64) -> bool {
665        false
666    }
667
668    fn segment_bounds(&self, addr: u64) -> Option<(u64, u64)> {
669        self.object_at(addr).map(|o| (o.base, o.end()))
670    }
671
672    fn entry_points(&self) -> Vec<u64> {
673        self.entrypoint.into_iter().collect()
674    }
675
676    fn entrypoint(&self) -> Option<u64> {
677        self.entrypoint
678    }
679
680    fn symbol_name(&self, addr: u64) -> Option<&str> {
681        (Some(addr) == self.entrypoint).then_some("_start")
682    }
683
684    fn symbol_address(&self, name: &str) -> Option<u64> {
685        (name == "_start").then_some(self.entrypoint).flatten()
686    }
687}
688
689#[cfg(test)]
690mod tests {
691    use super::*;
692
693    /// A minimal LE: a 32-bit code object at 0x10000 and a data object at
694    /// 0x20000, one page each, with fixups:
695    /// - code+1: `mov eax, [data+0x10]` → Offset32 to object 2 offset 0x10
696    /// - code+6: `call code+0x20`       → Relative32 to object 1 offset 0x20
697    /// - code+0xb: far pointer          → Pointer16_32 to object 2 offset 4
698    /// - data+0, data+8 and data+0x1e (a source list; the last straddles the
699    ///   end of the file-backed bytes) → Offset32 to object 1 offset 0x20
700    pub(crate) fn sample() -> Vec<u8> {
701        let le = 0x40usize;
702        let page = 0x200u32;
703        let mut f = vec![0u8; 0x600];
704        f[..2].copy_from_slice(b"MZ");
705        f[0x3c..0x40].copy_from_slice(&(le as u32).to_le_bytes());
706        let put32 =
707            |f: &mut Vec<u8>, at: usize, v: u32| f[at..at + 4].copy_from_slice(&v.to_le_bytes());
708        f[le..le + 2].copy_from_slice(b"LE");
709        f[le + 0x08] = 2; // 386
710        f[le + 0x0a] = 1;
711        put32(&mut f, le + 0x14, 2); // module pages
712        put32(&mut f, le + 0x18, 1); // eip object
713        put32(&mut f, le + 0x1c, 0x0); // eip
714        put32(&mut f, le + 0x20, 2); // esp object
715        put32(&mut f, le + 0x24, 0x100); // esp
716        put32(&mut f, le + 0x28, page);
717        put32(&mut f, le + 0x2c, 0x20); // last page size
718        put32(&mut f, le + 0x40, 0xc4); // object table
719        put32(&mut f, le + 0x44, 2);
720        put32(&mut f, le + 0x48, 0xf4); // page map
721        put32(&mut f, le + 0x58, 0xfc); // resident names
722        put32(&mut f, le + 0x68, 0x104); // fixup page table
723        put32(&mut f, le + 0x6c, 0x110); // fixup records
724        put32(&mut f, le + 0x70, 0x160); // import modules
725        put32(&mut f, le + 0x78, 0x160); // import procs
726        put32(&mut f, le + 0x80, 0x200); // data pages (file offset)
727
728        // Objects: code (0x40 bytes, RX, big), data (0x100 bytes of which 0x20 in file, RW).
729        let ot = le + 0xc4;
730        for (i, (vs, base, flags, first)) in [
731            (
732                0x40u32,
733                0x10000u32,
734                OBJ_READABLE | OBJ_EXECUTABLE | OBJ_BIG,
735                1u32,
736            ),
737            (0x100, 0x20000, OBJ_READABLE | OBJ_WRITABLE | OBJ_BIG, 2),
738        ]
739        .into_iter()
740        .enumerate()
741        {
742            let e = ot + 24 * i;
743            put32(&mut f, e, vs);
744            put32(&mut f, e + 4, base);
745            put32(&mut f, e + 8, flags);
746            put32(&mut f, e + 12, first);
747            put32(&mut f, e + 16, 1);
748        }
749        // Page map: logical 1 -> physical 1, logical 2 -> physical 2.
750        f[le + 0xf4..le + 0xf8].copy_from_slice(&[0, 0, 1, 0]);
751        f[le + 0xf8..le + 0xfc].copy_from_slice(&[0, 0, 2, 0]);
752        f[le + 0xfc] = 4;
753        f[le + 0xfd..le + 0x101].copy_from_slice(b"demo");
754
755        // Fixup records: page 1's, then page 2's.
756        let recs: Vec<u8> = [
757            // Offset32, internal, object 2, 16-bit offset 0x10, at +1
758            vec![0x07, 0x00, 0x01, 0x00, 0x02, 0x10, 0x00],
759            // Relative32, internal, object 1, offset 0x20, at +6
760            vec![0x08, 0x00, 0x06, 0x00, 0x01, 0x20, 0x00],
761            // Pointer16_32, internal, object 2, offset 4, at +0xb
762            vec![0x06, 0x00, 0x0b, 0x00, 0x02, 0x04, 0x00],
763        ]
764        .concat();
765        let page2: Vec<u8> = vec![
766            // Offset32, source list of 3, object 1, 32-bit offset 0x20; sources 0, 8, 0x1e
767            0x27, 0x10, 0x03, 0x01, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x1e, 0x00,
768        ];
769        let fr = le + 0x110;
770        f[fr..fr + recs.len()].copy_from_slice(&recs);
771        f[fr + recs.len()..fr + recs.len() + page2.len()].copy_from_slice(&page2);
772        put32(&mut f, le + 0x104, 0);
773        put32(&mut f, le + 0x108, recs.len() as u32);
774        put32(&mut f, le + 0x10c, (recs.len() + page2.len()) as u32);
775
776        // Page 1: code with the object-relative values the linker leaves.
777        let code: [u8; 17] = [
778            0xa1, 0x10, 0, 0, 0, // mov eax, [0x10]
779            0xe8, 0, 0, 0, 0, // call rel32
780            0x90, 0, 0, 0, 0, 0, 0, // far pointer slot
781        ];
782        f[0x200..0x200 + code.len()].copy_from_slice(&code);
783        f[0x200 + page as usize..0x200 + page as usize + 0x20].fill(0xcc);
784        f.truncate(0x200 + page as usize + 0x20);
785        f
786    }
787
788    #[test]
789    fn parses_objects_and_applies_internal_fixups() {
790        let b = LeBinary::parse(&sample()).unwrap();
791        assert_eq!(b.module_name.as_deref(), Some("demo"));
792        assert_eq!(b.objects.len(), 2);
793        assert_eq!(b.entrypoint, Some(0x10000));
794        assert_eq!(b.initial_stack, Some(0x20100));
795        assert_eq!(b.bits(), 32);
796        assert_eq!(b.architecture(), Arch::I386);
797
798        assert_eq!(b.read_uint(0x10001, 4), Some(0x20010));
799        // call at 0x10005: rel32 at 0x10006, target 0x10020.
800        assert_eq!(b.read_uint(0x10006, 4), Some(0x10020 - 0x1000a));
801        assert_eq!(b.read_uint(0x1000b, 4), Some(0x20004));
802        assert_eq!(b.read_uint(0x20000, 4), Some(0x10020));
803        assert_eq!(b.read_uint(0x20008, 4), Some(0x10020));
804        assert_eq!(b.read_uint(0x2001e, 4), Some(0x10020));
805        // Unfixed data bytes and the zero-filled tail.
806        assert_eq!(b.byte_at(0x20004), Some(0xcc));
807        assert_eq!(b.byte_at(0x200ff), Some(0));
808        assert_eq!(b.byte_at(0x20100), None);
809    }
810
811    #[test]
812    fn keeps_every_fixup_with_its_target() {
813        let b = LeBinary::parse(&sample()).unwrap();
814        let rows: Vec<_> = b
815            .fixups
816            .iter()
817            .map(|f| (f.address, f.kind, b.fixup_target(f)))
818            .collect();
819        assert_eq!(
820            rows,
821            vec![
822                (0x10001, LeFixupKind::Offset32, Some(0x20010)),
823                (0x10006, LeFixupKind::Relative32, Some(0x10020)),
824                (0x1000b, LeFixupKind::Pointer16_32, Some(0x20004)),
825                (0x20000, LeFixupKind::Offset32, Some(0x10020)),
826                (0x20008, LeFixupKind::Offset32, Some(0x10020)),
827                (0x2001e, LeFixupKind::Offset32, Some(0x10020)),
828            ]
829        );
830        assert!(LeFixupKind::Pointer16_32.has_selector());
831    }
832
833    #[test]
834    fn reports_object_permissions() {
835        let b = LeBinary::parse(&sample()).unwrap();
836        assert!(b.is_executable(0x10000));
837        assert!(!b.is_executable(0x20000));
838        assert!(b.is_known_writable(0x20000));
839        assert!(!b.is_known_read_only(0x10000));
840        let names: Vec<_> = b.sections().into_iter().map(|s| s.name).collect();
841        assert_eq!(names, ["object1", "object2"]);
842    }
843
844    #[test]
845    fn rejects_lx_and_bare_mz() {
846        let mut f = sample();
847        f[0x40..0x42].copy_from_slice(b"LX");
848        assert_eq!(LeBinary::parse(&f).unwrap_err(), LeError::Lx);
849        f[0x40..0x42].copy_from_slice(b"NE");
850        assert_eq!(LeBinary::parse(&f).unwrap_err(), LeError::NotLe);
851    }
852}