rigless 0.2.1

Virtual hardware-in-the-loop runtime: run unmodified firmware on an emulated MCU with every peripheral, chip model and unit of virtual time in Rust, and a CPU core of its own that translates the firmware's instructions to host code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The smallest reader of an ELF file that the runtime needs: the file's machine, class and byte
//! order, its section headers, which the firmware's symbols and its stored bytes come from, and its program
//! headers, which say where those bytes are stored. It reads 32-bit and 64-bit files of either byte
//! order and nothing else of the file.

use std::fmt;

/// `\x7fELF`, which every ELF file starts with.
const MAGIC: &[u8; 4] = b"\x7fELF";
/// A program header's kind when its segment is loaded.
const LOAD: u64 = 1;
/// A section's flag when the program occupies it in memory.
const ALLOCATED: u64 = 0x2;
/// A section's kind when it takes up no bytes of the file, like zeroed data.
const NO_BITS: u32 = 8;

/// Why an ELF file couldn't be read.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The file isn't an ELF file of a class and a byte order this reads.
    #[error("isn't an ELF file this reads")]
    NotElf,
    /// The file ends before something it says it holds.
    #[error("ends before its {0}")]
    Short(&'static str),
    /// A section is only partly inside the loaded segment that holds it.
    #[error("has a section only partly inside the segment that loads it")]
    Straddles,
    /// A section's load address runs past the end of the address space.
    #[error("loads a section past the end of the address space")]
    Wraps,
}

/// The machine an ELF file is built for, as its header numbers it in `e_machine`, and whether it's
/// a 64-bit file. A core family's [`CoreSpec`](crate::emulator::CoreSpec) names the one it runs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Machine {
    /// `e_machine`, as the processor's supplement to the ELF format numbers it.
    pub number: u16,
    /// A 64-bit file, `ELFCLASS64`, where `false` is a 32-bit one.
    pub wide: bool,
}

impl Machine {
    /// The machine `number`, in a 64-bit file when `wide`.
    #[must_use]
    pub const fn new(number: u16, wide: bool) -> Self {
        Self { number, wide }
    }
}

impl fmt::Display for Machine {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "ELF machine {} in {}-bit files",
            self.number,
            if self.wide { 64 } else { 32 }
        )
    }
}

/// Bytes of the file stored in memory: the address they're stored at, where they start in the file,
/// and how many there are.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Load {
    pub(crate) address: u64,
    pub(crate) offset: u64,
    pub(crate) length: u64,
}

/// One section header, as far as the runtime reads it.
pub(crate) struct Section {
    /// What it holds, as the format numbers it.
    pub(crate) kind: u32,
    /// Its flags, of which the runtime reads whether the program occupies it in memory.
    pub(crate) flags: u64,
    /// Where it starts in the file.
    pub(crate) offset: u64,
    /// How long it is.
    pub(crate) size: u64,
    /// The section it links to.
    pub(crate) link: u64,
    /// How long each entry in it is.
    pub(crate) entry: u64,
}

/// An ELF file as its header lays it out.
pub(crate) struct File<'a> {
    bytes: &'a [u8],
    wide: bool,
    big: bool,
}

impl<'a> File<'a> {
    pub(crate) fn new(bytes: &'a [u8]) -> Result<Self, Error> {
        let (Some(magic), Some(&class), Some(&order)) =
            (bytes.get(..4), bytes.get(4), bytes.get(5))
        else {
            return Err(Error::NotElf);
        };
        if magic != MAGIC || !(1..=2).contains(&class) || !(1..=2).contains(&order) {
            return Err(Error::NotElf);
        }
        Ok(Self {
            bytes,
            wide: class == 2,
            big: order == 2,
        })
    }

    pub(crate) fn bytes(
        &self,
        at: u64,
        length: u64,
        what: &'static str,
    ) -> Result<&'a [u8], Error> {
        let start = usize::try_from(at).map_err(|_too_large| Error::Short(what))?;
        let end = start
            .checked_add(usize::try_from(length).map_err(|_too_large| Error::Short(what))?)
            .ok_or(Error::Short(what))?;
        self.bytes.get(start..end).ok_or(Error::Short(what))
    }

    /// The unsigned integer of `width` bytes at `at`, in the file's byte order.
    fn number(&self, at: u64, width: u64, what: &'static str) -> Result<u64, Error> {
        let bytes = self.bytes(at, width, what)?;
        let fold = |value: u64, &byte: &u8| (value << 8) | u64::from(byte);
        Ok(if self.big {
            bytes.iter().fold(0, fold)
        } else {
            bytes.iter().rev().fold(0, fold)
        })
    }

    /// An address or an offset: 8 bytes in a 64-bit file, 4 in a 32-bit one.
    fn word(&self, at: u64, what: &'static str) -> Result<u64, Error> {
        self.number(at, if self.wide { 8 } else { 4 }, what)
    }

    /// Where entry `index` of a table at `table` with entries `size` bytes long starts, checked
    /// against the file's length first, so an offset into the entry can't overflow.
    fn entry(&self, table: u64, size: u64, index: u64, what: &'static str) -> Result<u64, Error> {
        index
            .checked_mul(size)
            .and_then(|offset| table.checked_add(offset))
            .filter(|&at| at <= self.bytes.len() as u64)
            .ok_or(Error::Short(what))
    }

    /// The machine the file is built for.
    pub(crate) fn machine(&self) -> Result<Machine, Error> {
        let number = self.number(18, 2, "header")?;
        Ok(Machine::new(
            u16::try_from(number).expect("two bytes"),
            self.wide,
        ))
    }

    /// Whether the file keeps its values big-endian.
    pub(crate) fn big_endian(&self) -> bool {
        self.big
    }

    /// How many sections the file has.
    pub(crate) fn sections(&self) -> Result<u64, Error> {
        self.number(if self.wide { 60 } else { 48 }, 2, "header")
    }

    /// Section `index`'s header.
    pub(crate) fn section(&self, index: u64) -> Result<Section, Error> {
        let (table, size) = if self.wide {
            (self.word(40, "header")?, self.number(58, 2, "header")?)
        } else {
            (self.word(32, "header")?, self.number(46, 2, "header")?)
        };
        let what = "section headers";
        let at = self.entry(table, size, index, what)?;
        let kind = u32::try_from(self.number(at + 4, 4, what)?)
            .map_err(|_too_large| Error::Short(what))?;
        Ok(if self.wide {
            Section {
                kind,
                flags: self.word(at + 8, what)?,
                offset: self.word(at + 24, what)?,
                size: self.word(at + 32, what)?,
                link: self.number(at + 40, 4, what)?,
                entry: self.word(at + 56, what)?,
            }
        } else {
            Section {
                kind,
                flags: self.word(at + 8, what)?,
                offset: self.word(at + 16, what)?,
                size: self.word(at + 20, what)?,
                link: self.number(at + 24, 4, what)?,
                entry: self.word(at + 36, what)?,
            }
        })
    }

    /// The symbol at `at`, inside the symbol table: where its name starts among the strings, its
    /// value and its kind.
    pub(crate) fn symbol(&self, at: u64) -> Result<(u64, u64, u8), Error> {
        let what = "symbols";
        let (value, info) = if self.wide {
            (self.word(at + 8, what)?, at + 4)
        } else {
            (self.word(at + 4, what)?, at + 12)
        };
        Ok((
            self.number(at, 4, what)?,
            value,
            self.bytes(info, 1, what)?[0],
        ))
    }

    /// Everything the file stores in memory: each allocated section's bytes, with the address they're
    /// stored at, where they start in the file and how many there are.
    ///
    /// A section is stored where the loaded segment holding it puts it, at the segment's physical
    /// address, so data that runs from RAM is stored where the linker put its copy. That's what
    /// objcopy writes into a binary and what a debugger's `load` writes to a board. Bytes a segment
    /// carries outside every section aren't listed, like the file's own headers a linker maps in
    /// front of the first one, and neither is what a section only zeroes. A file with no section
    /// headers lists each loaded segment's bytes instead.
    pub(crate) fn loads(&self) -> Result<Vec<Load>, Error> {
        let segments = self.segments()?;
        let count = self.sections()?;
        if count == 0 {
            return Ok(segments);
        }
        let mut loads = Vec::new();
        for index in 0..count {
            let section = self.section(index)?;
            if section.flags & ALLOCATED == 0 || section.kind == NO_BITS || section.size == 0 {
                continue;
            }
            self.bytes(section.offset, section.size, "sections")?;
            let end = section.offset + section.size;
            // A section no loaded segment touches isn't stored anywhere.
            let Some(segment) = segments.iter().find(|segment| {
                segment.offset < end && section.offset < segment.offset + segment.length
            }) else {
                continue;
            };
            if section.offset < segment.offset || end > segment.offset + segment.length {
                return Err(Error::Straddles);
            }
            loads.push(Load {
                address: segment
                    .address
                    .checked_add(section.offset - segment.offset)
                    .ok_or(Error::Wraps)?,
                offset: section.offset,
                length: section.size,
            });
        }
        Ok(loads)
    }

    /// Every loaded segment that holds bytes of the file, stored at its physical address.
    fn segments(&self) -> Result<Vec<Load>, Error> {
        let (table, size, count) = if self.wide {
            (
                self.word(32, "header")?,
                self.number(54, 2, "header")?,
                self.number(56, 2, "header")?,
            )
        } else {
            (
                self.word(28, "header")?,
                self.number(42, 2, "header")?,
                self.number(44, 2, "header")?,
            )
        };
        let what = "program headers";
        let mut segments = Vec::new();
        for index in 0..count {
            let at = self.entry(table, size, index, what)?;
            let (offset, address, length) = if self.wide {
                (
                    self.word(at + 8, what)?,
                    self.word(at + 24, what)?,
                    self.word(at + 32, what)?,
                )
            } else {
                (
                    self.word(at + 4, what)?,
                    self.word(at + 12, what)?,
                    self.word(at + 16, what)?,
                )
            };
            if self.number(at, 4, what)? == LOAD && length > 0 {
                self.bytes(offset, length, "segments")?;
                segments.push(Load {
                    address,
                    offset,
                    length,
                });
            }
        }
        Ok(segments)
    }
}

/// An ELF file of `class`, 1 for 32-bit and 2 for 64-bit, and byte `order`, 1 for little-endian and
/// 2 for big. It has one program header per segment, which is its kind, its physical address, its
/// virtual address, its bytes in the file and its length in memory. It has one section header per
/// section after the null one, which is its kind, its flags, the segment its bytes are in, where in
/// that segment's bytes it starts, and its size.
#[cfg(test)]
pub(crate) fn built(
    class: u8,
    order: u8,
    segments: &[(u64, u64, u64, &[u8], u64)],
    sections: &[(u32, u64, usize, usize, usize)],
) -> Vec<u8> {
    let (wide, big) = (class == 2, order == 2);
    let put = |out: &mut Vec<u8>, value: u64, width: usize| {
        let bytes = value.to_le_bytes();
        let mut field = bytes[..width].to_vec();
        if big {
            field.reverse();
        }
        out.extend(field);
    };
    let word = if wide { 8 } else { 4 };
    let header: usize = if wide { 64 } else { 52 };
    let entry: usize = if wide { 56 } else { 32 };
    let section_entry: usize = if wide { 64 } else { 40 };
    let mut at = header + entry * segments.len();
    let mut offsets = Vec::new();
    for &(.., bytes, _) in segments {
        offsets.push(at);
        at += bytes.len();
    }
    let section_table = at;
    let mut out = vec![0x7f, b'E', b'L', b'F', class, order];
    out.resize(if wide { 32 } else { 28 }, 0);
    put(&mut out, header as u64, word);
    put(
        &mut out,
        if sections.is_empty() {
            0
        } else {
            section_table as u64
        },
        word,
    );
    out.resize(if wide { 54 } else { 42 }, 0);
    put(&mut out, entry as u64, 2);
    put(&mut out, segments.len() as u64, 2);
    put(&mut out, section_entry as u64, 2);
    put(
        &mut out,
        if sections.is_empty() {
            0
        } else {
            sections.len() as u64 + 1
        },
        2,
    );
    out.resize(header, 0);
    for (&(kind, physical, virtual_, bytes, length), &offset) in segments.iter().zip(&offsets) {
        put(&mut out, kind, 4);
        if wide {
            put(&mut out, 0, 4);
        }
        for value in [
            offset as u64,
            virtual_,
            physical,
            bytes.len() as u64,
            length,
        ] {
            put(&mut out, value, word);
        }
        if !wide {
            put(&mut out, 0, 4);
        }
        put(&mut out, 0, word);
    }
    for &(.., bytes, _) in segments {
        out.extend(bytes);
    }
    if !sections.is_empty() {
        out.resize(out.len() + section_entry, 0);
    }
    for &(kind, flags, segment, start, size) in sections {
        put(&mut out, 0, 4);
        put(&mut out, kind.into(), 4);
        put(&mut out, flags, word);
        put(&mut out, 0, word);
        put(&mut out, (offsets[segment] + start) as u64, word);
        put(&mut out, size as u64, word);
        put(&mut out, 0, 4);
        put(&mut out, 0, 4);
        put(&mut out, 0, word);
        put(&mut out, 0, word);
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A section's kind when it holds the program's bytes.
    const PROGRAM: u32 = 1;

    /// What `file` stores, as addresses and bytes.
    fn stored(file: &[u8]) -> Vec<(u64, Vec<u8>)> {
        let elf = File::new(file).unwrap();
        elf.loads()
            .unwrap()
            .iter()
            .map(|load| {
                let bytes = elf.bytes(load.offset, load.length, "segments").unwrap();
                (load.address, bytes.to_vec())
            })
            .collect()
    }

    #[test]
    fn a_section_is_stored_where_its_segment_puts_it_and_nothing_outside_a_section_is() {
        for class in [1, 2] {
            for order in [1, 2] {
                let file = built(
                    class,
                    order,
                    &[
                        (LOAD, 0x1000, 0x1000, &[0xE1, 0xE1, 1, 2, 3, 4], 6),
                        (LOAD, 0x1006, 0x8000, &[5, 6], 2),
                    ],
                    &[
                        (PROGRAM, 0, 0, 0, 2),
                        (PROGRAM, ALLOCATED, 0, 2, 4),
                        (PROGRAM, ALLOCATED, 1, 0, 2),
                        (NO_BITS, ALLOCATED, 1, 2, 0x100),
                    ],
                );
                assert_eq!(
                    stored(&file),
                    [(0x1002, vec![1, 2, 3, 4]), (0x1006, vec![5, 6])],
                    "class {class}, order {order}: the two bytes of the file's own in front of the code \
                     aren't stored, data that runs from 0x8000 is stored after the code, and neither \
                     zeroed memory nor a section the program doesn't occupy is"
                );
            }
        }
    }

    #[test]
    fn a_file_with_no_section_headers_stores_each_loaded_segments_bytes() {
        const NOTE: u64 = 4;
        for class in [1, 2] {
            for order in [1, 2] {
                let file = built(
                    class,
                    order,
                    &[
                        (LOAD, 0x1000, 0x1000, &[1, 2, 3, 4], 4),
                        (LOAD, 0x1004, 0x8000, &[5, 6], 2),
                        (LOAD, 0x8002, 0x8002, &[], 0x100),
                        (NOTE, 0x1006, 0x1006, &[7], 1),
                    ],
                    &[],
                );
                assert_eq!(
                    stored(&file),
                    [(0x1000, vec![1, 2, 3, 4]), (0x1004, vec![5, 6])],
                    "class {class}, order {order}"
                );
            }
        }
    }

    #[test]
    fn a_section_partly_outside_its_segment_or_loaded_past_the_address_space_is_refused() {
        let straddles = built(
            1,
            1,
            &[(LOAD, 0x1000, 0x1000, &[1, 2, 3, 4], 4)],
            &[(PROGRAM, ALLOCATED, 0, 2, 4)],
        );
        assert_eq!(
            File::new(&straddles).unwrap().loads(),
            Err(Error::Straddles),
            "a section two bytes past the end of its segment's bytes"
        );
        let wraps = built(
            2,
            1,
            &[(LOAD, u64::MAX - 1, 0x1000, &[1, 2, 3, 4], 4)],
            &[(PROGRAM, ALLOCATED, 0, 2, 2)],
        );
        assert_eq!(File::new(&wraps).unwrap().loads(), Err(Error::Wraps));
    }

    #[test]
    fn a_segment_or_a_section_that_runs_past_the_end_of_the_file_is_refused() {
        let segment = built(1, 1, &[(LOAD, 0x1000, 0x1000, &[1, 2, 3, 4], 4)], &[]);
        assert_eq!(
            File::new(&segment[..segment.len() - 1]).unwrap().loads(),
            Err(Error::Short("segments"))
        );
        let section = built(
            1,
            1,
            &[(LOAD, 0x1000, 0x1000, &[1, 2, 3, 4], 4)],
            &[(PROGRAM, ALLOCATED, 0, 0, 10_000)],
        );
        assert_eq!(
            File::new(&section).unwrap().loads(),
            Err(Error::Short("sections"))
        );
    }
}