rigless 0.3.0

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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The images a run places in memory, and where the core boots from.
//!
//! A run places one or more images before the core's first instruction, the way a probe writes them
//! to a board: an ELF file's sections at the load addresses it stores them at, and any other file
//! whole at the address the run names. Nothing else is written, not what a section only zeroes and
//! not the bytes outside every section, so a bootloader and the application behind it both place,
//! though each zeroes the same RAM when it starts and a linker can map the application's own headers
//! over the bootloader's flash. The core boots where it does on its own unless the run names another
//! address.
//!
//! [`place`] holds every segment to the target's memory map and to every other, and the address the
//! core boots from to what's placed there, before anything runs. A mistake is refused with what it
//! hit, instead of showing up as a core running from empty memory.

use std::fmt;
use std::io;
use std::path::{Path, PathBuf};

use sha2::{Digest, Sha256};

use crate::elf::{self, File, Machine};
use crate::emulator::{Alias, CoreSpec};
use crate::soc::{Endian, Extent, Region, first_overlap};

/// Why an image couldn't be read or placed.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The file couldn't be read.
    #[error("reading {}: {source}", path.display())]
    Read {
        /// The file.
        path: PathBuf,
        /// Why.
        source: io::Error,
    },
    /// The file is an ELF file that ends before what it says it holds.
    #[error("{} {source}", path.display())]
    Elf {
        /// The file.
        path: PathBuf,
        /// Where it ends early.
        source: elf::Error,
    },
    /// An ELF file was given an address, and it says where its bytes go itself.
    #[error("{} is an ELF file, which says where its bytes go, so give it no address", path.display())]
    Addressed {
        /// The file.
        path: PathBuf,
    },
    /// A file that isn't ELF was given no address to go at.
    #[error("{} isn't an ELF file, so it needs an address to go at", path.display())]
    Unaddressed {
        /// The file.
        path: PathBuf,
    },
    /// A segment isn't inside one region of the target's memory.
    #[error("{} places {start:#x} to {end:#x}, and no one memory region holds all of it", path.display())]
    Outside {
        /// The image.
        path: PathBuf,
        /// The segment's first byte.
        start: u64,
        /// The byte past its last.
        end: u64,
    },
    /// Two segments place bytes at the same address.
    #[error("{first} and {second} overlap from {at:#x}")]
    Overlap {
        /// The segment that starts first, in memory.
        first: Span,
        /// The one that starts inside it.
        second: Span,
        /// The first address both place a byte at.
        at: u64,
    },
    /// Nothing is placed where the core boots from.
    #[error("the core boots from {}, and no image places anything there", at_in_memory(*at, *held))]
    Unbooted {
        /// Where the core boots from.
        at: u64,
        /// Where `at` is in the memory map, through an alias when it's one, or `None` when no region
        /// holds it.
        held: Option<u64>,
    },
    /// An ELF file is built for another machine than the core runs, or keeps its values in the
    /// other byte order from the part's.
    #[error("{} is built for {file}, {}, and the core runs {core}, {}", path.display(), order(*file_endian), order(*part_endian))]
    OtherMachine {
        /// The image.
        path: PathBuf,
        /// The machine it's built for.
        file: Machine,
        /// The byte order it keeps.
        file_endian: Endian,
        /// The machine the core runs, or the file's own when the core names none.
        core: Machine,
        /// The part's byte order.
        part_endian: Endian,
    },
    /// The core can't boot from the address the run named.
    #[error("the core can't boot from {at:#x}, which isn't a multiple of {alignment:#x}")]
    Misaligned {
        /// The address.
        at: u64,
        /// What it has to be a multiple of.
        alignment: u64,
    },
}

/// Where a segment lands, as a refusal names it: its image, and where it starts and ends.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Span {
    /// The image.
    pub path: PathBuf,
    /// The segment's first byte.
    pub start: u64,
    /// The byte past its last.
    pub end: u64,
}

impl fmt::Display for Span {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} at {:#x} to {:#x}",
            self.path.display(),
            self.start,
            self.end
        )
    }
}

fn order(endian: Endian) -> &'static str {
    match endian {
        Endian::Little => "little-endian",
        Endian::Big => "big-endian",
    }
}

fn at_in_memory(at: u64, held: Option<u64>) -> String {
    match held {
        Some(held) if held != at => format!("{at:#x}, which is {held:#x}"),
        _ => format!("{at:#x}"),
    }
}

/// A firmware file as a run places it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Image {
    path: PathBuf,
    bytes: Vec<u8>,
    /// Where each segment goes, and where its bytes are in the file.
    segments: Vec<(u64, std::ops::Range<usize>)>,
    at: Option<u64>,
    /// The machine an ELF file is built for and its byte order, or `None` for any other file.
    built: Option<(Machine, Endian)>,
}

impl Image {
    /// Reads the file at `path`, whose sections go where it stores them when it's an ELF file, or
    /// whole at `at` when it isn't ELF.
    ///
    /// # Errors
    ///
    /// A file that can't be read, an ELF file that ends before what it says it holds, an ELF file
    /// given an address, since it says where it goes itself, and any other file given none.
    pub fn read(path: &Path, at: Option<u64>) -> Result<Self, Error> {
        let bytes = std::fs::read(path).map_err(|source| Error::Read {
            path: path.to_owned(),
            source,
        })?;
        Self::new(path, bytes, at)
    }

    /// The image `bytes`, named `path` wherever a refusal names it.
    ///
    /// # Errors
    ///
    /// As for [`Image::read`], less reading the file.
    pub fn new(path: &Path, bytes: Vec<u8>, at: Option<u64>) -> Result<Self, Error> {
        let elf = |source| Error::Elf {
            path: path.to_owned(),
            source,
        };
        let (segments, built) = match (File::new(&bytes), at) {
            (Ok(file), None) => {
                let endian = if file.big_endian() {
                    Endian::Big
                } else {
                    Endian::Little
                };
                let segments = file
                    .loads()
                    .map_err(elf)?
                    .into_iter()
                    .map(|load| {
                        // `loads` checked each one's bytes are inside the file.
                        let start = usize::try_from(load.offset).expect("inside the file");
                        let end = start + usize::try_from(load.length).expect("inside the file");
                        (load.address, start..end)
                    })
                    .collect();
                (segments, Some((file.machine().map_err(elf)?, endian)))
            }
            (Ok(_), Some(_)) => {
                return Err(Error::Addressed {
                    path: path.to_owned(),
                });
            }
            (Err(_), Some(at)) => (vec![(at, 0..bytes.len())], None),
            (Err(_), None) => {
                return Err(Error::Unaddressed {
                    path: path.to_owned(),
                });
            }
        };
        Ok(Self {
            path: path.to_owned(),
            bytes,
            segments,
            at,
            built,
        })
    }

    /// The file's bytes.
    #[must_use]
    pub fn bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Every segment that holds a byte, with the address it goes to.
    pub fn segments(&self) -> impl Iterator<Item = (u64, &[u8])> {
        self.segments
            .iter()
            .filter(|(_, bytes)| !bytes.is_empty())
            .map(|(address, bytes)| (*address, &self.bytes[bytes.clone()]))
    }
}

/// One stretch of bytes a run places, and where.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Segment {
    /// Where the first byte goes.
    pub address: u64,
    /// The bytes.
    pub bytes: Vec<u8>,
}

/// Every segment of `images`, once each ELF file is built for the machine the target `spec` runs
/// in the byte order of a part that keeps its data `endian`, each segment is inside one region of
/// `memory` as the target starts, no two overlap, and something is placed where the core boots from:
/// `boot`, or where it boots on its own when that's `None`.
///
/// # Errors
///
/// An ELF file for another machine or byte order, a `boot` the core can't boot from, a segment
/// outside every region, two segments that overlap, and nothing placed where the core boots from.
pub fn place(
    images: &[Image],
    memory: &[Region],
    spec: &CoreSpec,
    endian: Endian,
    boot: Option<u64>,
) -> Result<Vec<Segment>, Error> {
    for image in images {
        let Some((file, file_endian)) = image.built else {
            continue;
        };
        let core = spec.elf.unwrap_or(file);
        if file != core || file_endian != endian {
            return Err(Error::OtherMachine {
                path: image.path.clone(),
                file,
                file_endian,
                core,
                part_endian: endian,
            });
        }
    }
    let alignment = spec.boot.alignment.get();
    if let Some(at) = boot.filter(|at| at % alignment != 0) {
        return Err(Error::Misaligned { at, alignment });
    }
    let mut placed = Vec::new();
    for image in images {
        for (address, bytes) in image.segments() {
            let length = bytes.len() as u64;
            let outside = || Error::Outside {
                path: image.path.clone(),
                start: address,
                end: address.saturating_add(length),
            };
            let start = held(memory, &spec.aliases, address, length).ok_or_else(outside)?;
            placed.push(Span {
                path: image.path.clone(),
                start,
                end: start + length,
            });
        }
    }
    let spans = placed.iter().enumerate().map(|(index, segment)| Extent {
        name: index,
        base: segment.start,
        size: segment.end - segment.start,
    });
    if let Some((first, second)) = first_overlap(spans) {
        let (first, second) = (placed[first].clone(), placed[second].clone());
        let at = second.start;
        return Err(Error::Overlap { first, second, at });
    }
    let at = boot.unwrap_or(spec.boot.reset);
    let held = held(memory, &spec.aliases, at, 1);
    if !held.is_some_and(|held| {
        placed
            .iter()
            .any(|segment| (segment.start..segment.end).contains(&held))
    }) {
        return Err(Error::Unbooted { at, held });
    }
    Ok(images
        .iter()
        .flat_map(Image::segments)
        .map(|(address, bytes)| Segment {
            address,
            bytes: bytes.to_vec(),
        })
        .collect())
}

/// Where the `length` bytes from `address` are in the region that holds all of them, reached at its
/// own address or at the second one an alias gives it, or `None` when no one region does.
fn held(memory: &[Region], aliases: &[Alias], address: u64, length: u64) -> Option<u64> {
    let end = address.checked_add(length)?;
    let inside = |base: u64, size: u64| base <= address && base.checked_add(size) >= Some(end);
    memory
        .iter()
        .find(|region| inside(region.base, region.size))
        .map(|_| address)
        .or_else(|| {
            aliases.iter().find_map(|alias| {
                let region = memory.iter().find(|region| region.name == alias.region)?;
                inside(alias.at, region.size).then(|| region.base + (address - alias.at))
            })
        })
}

/// The SHA-256 a snapshot names a run's firmware by: every image's bytes and where a file that isn't
/// ELF goes, in the run's order, and where the core boots from.
#[must_use]
pub fn digest(images: &[Image], boot: Option<u64>) -> [u8; 32] {
    fn address(hash: &mut Sha256, at: Option<u64>) {
        match at {
            Some(at) => {
                hash.update([1]);
                hash.update(at.to_le_bytes());
            }
            None => hash.update([0]),
        }
    }
    let mut hash = Sha256::new();
    for image in images {
        hash.update((image.bytes.len() as u64).to_le_bytes());
        hash.update(&image.bytes);
        address(&mut hash, image.at);
    }
    address(&mut hash, boot);
    hash.finalize().into()
}

#[cfg(test)]
mod tests {
    use std::num::NonZeroU64;
    use std::sync::Arc;

    use super::*;
    use crate::elf::built;
    use crate::emulator::Boot;

    /// A program header's kind when its segment is loaded.
    const LOAD: u64 = 1;
    const FLASH: u64 = 0x0800_0000;
    const RAM: u64 = 0x2000_0000;
    const MEMORY: [Region; 2] = [
        Region::flash("flash", FLASH, 0x10_0000),
        Region::ram("ram", RAM, 0x1_0000),
    ];

    /// A target whose flash also answers at 0, where the core boots from on its own, and which boots
    /// from a multiple of 512. Placing images makes no core, so it has none.
    fn spec() -> CoreSpec {
        let mut spec = CoreSpec::new(
            Arc::new(|_| Err(crate::emulator::Error::Machine("no core".to_owned()))),
            NonZeroU64::new(250_000_000).unwrap(),
            Boot::new(0, NonZeroU64::new(512).unwrap()),
        );
        spec.aliases = vec![Alias {
            region: "flash",
            at: 0,
        }];
        spec
    }

    /// An ELF file with `length` bytes of code at `at`, data stored after them that runs from RAM,
    /// and zeroed RAM, which every image has at the same address.
    fn elf(name: &str, at: u64, length: usize) -> Image {
        let code = vec![0xC0; length];
        let file = built(
            1,
            1,
            &[
                (LOAD, at, at, &code, length as u64),
                (LOAD, at + length as u64, RAM, &[0xDA; 8], 8),
                (LOAD, RAM + 8, RAM + 8, &[], 0x100),
            ],
            &[],
        );
        Image::new(Path::new(name), file, None).unwrap()
    }

    fn raw(name: &str, at: u64, length: usize) -> Image {
        Image::new(Path::new(name), vec![0xB1; length], Some(at)).unwrap()
    }

    #[test]
    fn an_elf_file_places_its_bytes_where_they_are_stored_and_nothing_it_zeroes() {
        let placed = place(
            &[elf("app.elf", FLASH, 16)],
            &MEMORY,
            &spec(),
            Endian::Little,
            None,
        )
        .unwrap();
        assert_eq!(
            placed,
            [
                Segment {
                    address: FLASH,
                    bytes: vec![0xC0; 16]
                },
                Segment {
                    address: FLASH + 16,
                    bytes: vec![0xDA; 8]
                },
            ]
        );
    }

    #[test]
    fn a_bootloader_and_the_application_behind_it_both_place_though_both_zero_the_same_ram() {
        let images = [
            elf("bootloader.elf", FLASH, 0x3000),
            elf("app.elf", FLASH + 0x4000, 0x100),
        ];
        let placed = place(&images, &MEMORY, &spec(), Endian::Little, None).unwrap();
        assert_eq!(
            placed
                .iter()
                .map(|segment| segment.address)
                .collect::<Vec<_>>(),
            [FLASH, FLASH + 0x3000, FLASH + 0x4000, FLASH + 0x4100]
        );
    }

    #[test]
    fn a_file_that_isnt_elf_goes_whole_at_its_address_and_needs_one() {
        let placed = place(
            &[raw("app.bin", FLASH, 4)],
            &MEMORY,
            &spec(),
            Endian::Little,
            None,
        )
        .unwrap();
        assert_eq!(
            placed,
            [Segment {
                address: FLASH,
                bytes: vec![0xB1; 4]
            }]
        );
        let unaddressed = Image::new(Path::new("app.bin"), vec![0xB1; 4], None).unwrap_err();
        assert_eq!(
            unaddressed.to_string(),
            "app.bin isn't an ELF file, so it needs an address to go at"
        );
        let file = elf("app.elf", FLASH, 4).bytes().to_vec();
        let addressed = Image::new(Path::new("app.elf"), file, Some(FLASH)).unwrap_err();
        assert_eq!(
            addressed.to_string(),
            "app.elf is an ELF file, which says where its bytes go, so give it no address"
        );
    }

    #[test]
    fn two_images_that_overlap_are_refused_with_both_named_even_through_an_alias() {
        let overlap = |images: &[Image]| {
            place(images, &MEMORY, &spec(), Endian::Little, None)
                .unwrap_err()
                .to_string()
        };
        assert_eq!(
            overlap(&[
                elf("bootloader.elf", FLASH, 0x4010),
                raw("app.bin", FLASH + 0x4000, 0x100),
            ]),
            "bootloader.elf at 0x8000000 to 0x8004010 and app.bin at 0x8004000 to 0x8004100 \
             overlap from 0x8004000"
        );
        assert_eq!(
            overlap(&[raw("low.bin", 0, 0x10), raw("high.bin", FLASH + 8, 0x10)]),
            "low.bin at 0x8000000 to 0x8000010 and high.bin at 0x8000008 to 0x8000018 overlap \
             from 0x8000008",
            "an image placed at the second address flash answers at is in flash"
        );
    }

    #[test]
    fn a_segment_no_one_region_holds_is_refused() {
        let outside = |image: Image| {
            place(
                &[raw("boot.bin", FLASH, 8), image],
                &MEMORY,
                &spec(),
                Endian::Little,
                None,
            )
            .unwrap_err()
            .to_string()
        };
        assert_eq!(
            outside(raw("far.bin", 0x0900_0000, 4)),
            "far.bin places 0x9000000 to 0x9000004, and no one memory region holds all of it"
        );
        assert_eq!(
            outside(raw("long.bin", FLASH + 0xF_FFFC, 8)),
            "long.bin places 0x80ffffc to 0x8100004, and no one memory region holds all of it"
        );
    }

    #[test]
    fn the_core_boots_where_it_does_on_its_own_unless_the_run_names_where() {
        let app = [elf("app.elf", FLASH + 0x4000, 0x100)];
        assert_eq!(
            place(&app, &MEMORY, &spec(), Endian::Little, None)
                .unwrap_err()
                .to_string(),
            "the core boots from 0x0, which is 0x8000000, and no image places anything there"
        );
        assert!(place(&app, &MEMORY, &spec(), Endian::Little, Some(FLASH + 0x4000)).is_ok());
        assert_eq!(
            place(&app, &MEMORY, &spec(), Endian::Little, Some(FLASH + 0x8000))
                .unwrap_err()
                .to_string(),
            "the core boots from 0x8008000, and no image places anything there"
        );
        assert_eq!(
            place(&app, &MEMORY, &spec(), Endian::Little, Some(FLASH + 0x4100))
                .unwrap_err()
                .to_string(),
            "the core can't boot from 0x8004100, which isn't a multiple of 0x200"
        );
    }

    /// An ELF file is placed only when it's built for the machine the core runs, in the part's
    /// byte order, and the refusal names both. A core that names no machine takes any, and a file
    /// that isn't ELF is never asked.
    #[test]
    fn an_elf_file_for_another_machine_or_byte_order_is_refused() {
        let mut named = spec();
        named.elf = Some(Machine::new(0xBEEF, false));
        let mut app = elf("app.elf", 0, 16).bytes().to_vec();
        app[18..20].copy_from_slice(&0xBEEF_u16.to_le_bytes());
        let app = Image::new(Path::new("app.elf"), app, None).unwrap();
        assert!(
            place(
                std::slice::from_ref(&app),
                &MEMORY,
                &named,
                Endian::Little,
                None
            )
            .is_ok()
        );
        let other = elf("other.elf", 0, 16);
        assert_eq!(
            place(
                std::slice::from_ref(&other),
                &MEMORY,
                &named,
                Endian::Little,
                None
            )
            .unwrap_err()
            .to_string(),
            "other.elf is built for ELF machine 0 in 32-bit files, little-endian, and the core runs \
             ELF machine 48879 in 32-bit files, little-endian"
        );
        assert!(place(&[other], &MEMORY, &spec(), Endian::Little, None).is_ok());
        assert!(matches!(
            place(&[app], &MEMORY, &named, Endian::Big, None),
            Err(Error::OtherMachine {
                file_endian: Endian::Little,
                part_endian: Endian::Big,
                ..
            })
        ));
        let wide = Image::new(
            Path::new("wide.elf"),
            built(2, 1, &[(LOAD, 0, 0, &[0xC0; 16], 16)], &[]),
            None,
        )
        .unwrap();
        assert!(matches!(
            place(&[wide], &MEMORY, &named, Endian::Little, None),
            Err(Error::OtherMachine { file, .. }) if file.wide
        ));
        assert!(place(&[raw("app.bin", 0, 4)], &MEMORY, &named, Endian::Big, None).is_ok());
    }

    #[test]
    fn the_digest_moves_with_any_image_where_one_goes_or_where_the_core_boots() {
        let (boot, app) = (raw("boot.bin", FLASH, 4), raw("app.bin", FLASH + 0x200, 4));
        let first = digest(&[boot.clone(), app.clone()], None);
        assert_eq!(first, digest(&[boot.clone(), app.clone()], None));
        for other in [
            digest(&[app.clone(), boot.clone()], None),
            digest(&[boot.clone(), raw("app.bin", FLASH + 0x400, 4)], None),
            digest(&[boot.clone(), app.clone()], Some(FLASH)),
            digest(std::slice::from_ref(&boot), None),
        ] {
            assert_ne!(first, other);
        }
    }
}