rigless 0.0.2

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; needs the rigless-sidecar package from rigless-labs/qemu
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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: Apache-2.0
//! What a peripheral model implements, and the register file the runtime keeps for it.
//!
//! A model is written against one generated register layout and does only what the hardware
//! does beyond storing bits. Everything a table can express, reset values, read-only bits,
//! write-one-to-clear, read-to-clear, write-once, is applied by the [`RegisterFile`] before
//! the model is called.
//!
//! ```
//! use rigless::device::{Device, RegisterFile};
//! # use rigless::soc::{Access, Layout, ReadAction, RegisterSpec, Width, WriteModify};
//! # static REGISTERS: [RegisterSpec; 1] = [RegisterSpec { name: "DR", offset: 0, width: Width::W32, reset: 0, access: Access::ReadWrite, read: ReadAction::None, write: WriteModify::None, fields: &[] }];
//! # #[derive(Debug, Clone, Copy)] enum Register { Dr }
//! # impl Layout for Register { const REGISTERS: &'static [RegisterSpec] = &REGISTERS; fn from_index(index: usize) -> Option<Self> { (index == 0).then_some(Self::Dr) } fn index(self) -> usize { 0 } }
//!
//! # use rigless::device::DeviceContext;
//! /// A UART that collects every byte the firmware sends.
//! #[derive(Default)]
//! struct Uart { sent: Vec<u8> }
//!
//! impl Device for Uart {
//!     type Register = Register;
//!     fn write(&mut self, register: Register, value: u64, _registers: &mut RegisterFile, _context: &mut DeviceContext<'_>) {
//!         if let Register::Dr = register { self.sent.push(value as u8); }
//!     }
//! }
//! ```
//!
//! A model that keeps time schedules an event through its [`DeviceContext`] and is woken by
//! [`Device::on_event`] at that instant, whether or not the firmware touches it meanwhile.

use std::any::Any;

use crate::soc::{Access, Layout, Peripheral, RegisterSpec, WriteModify};
use crate::time::{EventId, EventQueue, VirtualNanos};

/// A peripheral model: the side effects of reads, writes, and its own events on one register layout.
///
/// Every method defaults to doing nothing, so a model overrides only what it needs. Between calls a model does not
/// exist: it may not keep a thread, read a wall clock, or reach another instance.
pub trait Device {
    /// The register layout the model is written for.
    type Register: Layout;

    /// Answers a read, or returns `None` to serve the register file's value.
    ///
    /// The file's own read side effects, such as read-to-clear, apply only when the model
    /// returns `None`.
    fn read(
        &mut self,
        _register: Self::Register,
        _registers: &mut RegisterFile,
        _context: &mut DeviceContext<'_>,
    ) -> Option<u64> {
        None
    }

    /// Reacts to a write.
    ///
    /// `value` is what arrived at the full register width; the file already holds what landed
    /// after the access and write-modify rules.
    fn write(
        &mut self,
        _register: Self::Register,
        _value: u64,
        _registers: &mut RegisterFile,
        _context: &mut DeviceContext<'_>,
    ) {
    }

    /// Reacts to an event the model scheduled, at its instant.
    ///
    /// `event` is the id [`DeviceContext::schedule`] returned. A model that scheduled again since ignores an id
    /// it no longer expects; there is no cancel.
    fn on_event(
        &mut self,
        _event: EventId,
        _registers: &mut RegisterFile,
        _context: &mut DeviceContext<'_>,
    ) {
    }
}

/// What a model may do beyond its registers during one call: read the clock, schedule an event, and raise or
/// lower one of its instance's interrupts.
///
/// The SoC builds one for the instance it is calling, so a model sees its own time and interrupts and nothing else.
#[derive(Debug)]
pub struct DeviceContext<'a> {
    now: VirtualNanos,
    owner: usize,
    instance: &'static str,
    interrupts: &'static [u16],
    events: &'a mut EventQueue,
    changes: &'a mut Vec<InterruptChange>,
}

impl<'a> DeviceContext<'a> {
    pub(crate) fn new(
        now: VirtualNanos,
        owner: usize,
        peripheral: Peripheral,
        events: &'a mut EventQueue,
        changes: &'a mut Vec<InterruptChange>,
    ) -> Self {
        Self {
            now,
            owner,
            instance: peripheral.name,
            interrupts: peripheral.interrupts,
            events,
            changes,
        }
    }

    /// The instant of this call on the virtual clock.
    #[must_use]
    pub fn now(&self) -> VirtualNanos {
        self.now
    }

    /// Schedules an event for this instance at `at`, an absolute instant; one already passed fires at the next
    /// stop, as a past expiry does on QEMU's timer list.
    pub fn schedule(&mut self, at: VirtualNanos) -> EventId {
        self.events.schedule(at.max(self.now), self.owner)
    }

    /// Raises the instance's `interrupt`-th interrupt, as its table lists them.
    ///
    /// A model names the position once, `const UPDATE: usize = 0`, since a layout shared by several instances
    /// cannot know an instance's number. A position the table does not list is a bug in the model and panics.
    pub fn raise(&mut self, interrupt: usize) {
        self.change(interrupt, Level::High);
    }

    /// Lowers the instance's `interrupt`-th interrupt; see [`DeviceContext::raise`].
    pub fn lower(&mut self, interrupt: usize) {
        self.change(interrupt, Level::Low);
    }

    fn change(&mut self, position: usize, level: Level) {
        let Some(&interrupt) = self.interrupts.get(position) else {
            panic!(
                "{} lists {} interrupts; the model asked for position {position}",
                self.instance,
                self.interrupts.len()
            );
        };
        self.changes.push(InterruptChange {
            instance: self.instance,
            interrupt,
            level,
        });
    }
}

/// A level a model set on one of its instance's interrupts, in the instance's own numbering.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InterruptChange {
    /// The instance, as the vendor names it.
    pub instance: &'static str,
    /// The interrupt number from the instance's table.
    pub interrupt: u16,
    /// The level set.
    pub level: Level,
}

/// A logic level, of an interrupt line or a pin; levels are levels, held until changed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Level {
    /// Asserted.
    High,
    /// Released, the level of every line and pin before anything drives it.
    #[default]
    Low,
}

impl From<bool> for Level {
    fn from(high: bool) -> Self {
        if high { Self::High } else { Self::Low }
    }
}

impl std::ops::Not for Level {
    type Output = Self;

    fn not(self) -> Self {
        match self {
            Self::High => Self::Low,
            Self::Low => Self::High,
        }
    }
}

/// A [`Device`] with its layout erased, so the SoC can hold any model behind one type.
pub(crate) trait ErasedDevice {
    fn as_any_mut(&mut self) -> &mut dyn Any;
    fn read(
        &mut self,
        row: usize,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) -> Option<u64>;
    fn write(
        &mut self,
        row: usize,
        value: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    );
    fn on_event(
        &mut self,
        event: EventId,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    );
}

impl<D: Device + 'static> ErasedDevice for D {
    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn read(
        &mut self,
        row: usize,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) -> Option<u64> {
        D::Register::from_index(row)
            .and_then(|register| Device::read(self, register, registers, context))
    }

    fn write(
        &mut self,
        row: usize,
        value: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        if let Some(register) = D::Register::from_index(row) {
            Device::write(self, register, value, registers, context);
        }
    }

    fn on_event(
        &mut self,
        event: EventId,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        Device::on_event(self, event, registers, context);
    }
}

/// The values of one instance's registers, with reset, access rules, and write-modify arithmetic applied for the model.
///
/// Rows follow the instance's table. Registers the vendor declares as alternates of one
/// another share one offset and one value; each row is a view of it with its own access rules.
/// A model reads and writes through [`RegisterFile::get`] and [`RegisterFile::set`] as the
/// hardware would, with no rules applied; the bus goes through the rules.
#[derive(Debug, Clone)]
pub struct RegisterFile {
    table: &'static [RegisterSpec],
    /// The storage slot each row reads and writes; alternates share one.
    slot_of_row: Vec<usize>,
    reset_values: Vec<u64>,
    values: Vec<u64>,
    written_once: Vec<bool>,
    /// An SoC's correction of a row's write rule, for its register and every field in it.
    corrected_rules: Vec<Option<WriteModify>>,
}

impl RegisterFile {
    pub(crate) fn new(table: &'static [RegisterSpec]) -> Self {
        let slot_of_row: Vec<usize> = table
            .iter()
            .map(|register| {
                table
                    .iter()
                    .position(|earlier| earlier.offset == register.offset)
                    .unwrap_or_default()
            })
            .collect();
        let reset_values: Vec<u64> = table.iter().map(|register| register.reset).collect();
        Self {
            table,
            slot_of_row,
            values: reset_values.clone(),
            reset_values,
            written_once: vec![false; table.len()],
            corrected_rules: vec![None; table.len()],
        }
    }

    /// Makes `rule` the write rule of a row's register and of every field in it.
    pub(crate) fn correct_write(&mut self, row: usize, rule: WriteModify) {
        self.corrected_rules[row] = Some(rule);
    }

    /// The write rule of a row's register, after any correction.
    pub(crate) fn write_rule(&self, row: usize) -> WriteModify {
        self.corrected_rules[row].unwrap_or(self.table[row].write)
    }

    pub(crate) fn correct_reset(&mut self, row: usize, value: u64) {
        let slot = self.slot_of_row[row];
        self.reset_values[slot] = value;
        self.values[slot] = value;
    }

    /// Returns every register to its reset value and forgets which were written once.
    pub fn reset(&mut self) {
        self.values.clone_from(&self.reset_values);
        self.written_once.fill(false);
    }

    /// The value a register holds.
    pub fn get<L: Layout>(&self, register: L) -> u64 {
        self.get_row(register.index())
    }

    /// Sets a register as the hardware would, bypassing the bus rules.
    pub fn set<L: Layout>(&mut self, register: L, value: u64) {
        self.values[self.slot_of_row[register.index()]] = value & register.spec().width.mask();
    }

    /// Writes a register as the bus would, honoring its access and write rules: for a model that forwards a
    /// write to another register, as one with a burst window over its own registers does.
    pub fn write_over_bus<L: Layout>(&mut self, register: L, written: u64) {
        self.bus_write(register.index(), written);
    }

    pub(crate) fn get_row(&self, row: usize) -> u64 {
        self.values[self.slot_of_row[row]]
    }

    /// The row of the register covering an offset whose access `allows` the direction, or the first covering row.
    pub(crate) fn row_covering(&self, offset: u32, allows: fn(Access) -> bool) -> Option<usize> {
        let first_past = self
            .table
            .partition_point(|register| register.offset <= offset);
        let covering = (0..first_past)
            .rev()
            .take_while(|&row| self.table[row].end() > offset);
        let mut candidates = covering.collect::<Vec<usize>>();
        candidates.reverse();
        candidates
            .iter()
            .copied()
            .find(|&row| allows(self.table[row].access))
            .or_else(|| candidates.first().copied())
    }

    /// A read over the bus: honors access, then applies the read actions.
    pub(crate) fn bus_read(&mut self, row: usize) -> u64 {
        let register = &self.table[row];
        if !register.access.is_readable() {
            return 0;
        }
        let slot = self.slot_of_row[row];
        let value = self.values[slot];
        let mut after = register.read.apply(value, register.width.mask());
        for field in register
            .fields
            .iter()
            .filter(|field| field.read != register.read)
        {
            after =
                (after & !field.mask()) | (field.read.apply(value, field.mask()) & field.mask());
        }
        self.values[slot] = after;
        value
    }

    /// A write over the bus: honors access, then applies the write-modify arithmetic per register and per field.
    pub(crate) fn bus_write(&mut self, row: usize, written: u64) {
        let register = &self.table[row];
        if !register.access.is_writable()
            || (register.access.is_write_once() && self.written_once[row])
        {
            return;
        }
        self.written_once[row] = true;
        let slot = self.slot_of_row[row];
        let old = self.values[slot];
        let corrected = self.corrected_rules[row];
        let mut landed = corrected.unwrap_or(register.write).apply(old, written);
        for field in register.fields {
            let field_bits = if field.access.is_writable() {
                corrected.unwrap_or(field.write).apply(old, written)
            } else {
                old
            };
            landed = (landed & !field.mask()) | (field_bits & field.mask());
        }
        self.values[slot] = landed & register.width.mask();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::soc::{FieldSpec, ReadAction, Width, WriteModify};

    const fn register(
        name: &'static str,
        offset: u32,
        access: Access,
        read: ReadAction,
    ) -> RegisterSpec {
        RegisterSpec {
            name,
            offset,
            width: Width::W16,
            reset: 0xBEEF,
            access,
            read,
            write: WriteModify::None,
            fields: &[],
        }
    }

    const FLAG: FieldSpec = FieldSpec {
        name: "FLAG",
        bit: 0,
        width: 1,
        access: Access::ReadOnly,
        read: ReadAction::Clear,
        write: WriteModify::None,
    };

    static REGISTERS: [RegisterSpec; 4] = [
        register("PLAIN", 0x0, Access::ReadWrite, ReadAction::None),
        register("ONCE", 0x2, Access::ReadWriteOnce, ReadAction::None),
        register("POP", 0x4, Access::ReadOnly, ReadAction::Clear),
        RegisterSpec {
            fields: &[FLAG],
            ..register("STATUS", 0x6, Access::ReadWrite, ReadAction::None)
        },
    ];

    #[derive(Debug, Clone, Copy)]
    enum Register {
        Plain,
        Once,
        Pop,
        Status,
    }

    impl Layout for Register {
        const REGISTERS: &'static [RegisterSpec] = &REGISTERS;
        fn from_index(index: usize) -> Option<Self> {
            [Self::Plain, Self::Once, Self::Pop, Self::Status]
                .get(index)
                .copied()
        }
        fn index(self) -> usize {
            self as usize
        }
    }

    #[test]
    fn write_modify_arithmetic_and_its_neutral_value() {
        assert_eq!(WriteModify::OneToClear.apply(0b1111, 0b0101), 0b1010);
        assert_eq!(WriteModify::OneToSet.apply(0b1000, 0b0001), 0b1001);
        assert_eq!(WriteModify::OneToToggle.apply(0b1100, 0b0110), 0b1010);
        assert_eq!(WriteModify::ZeroToClear.apply(0b1111, 0b0101), 0b0101);
        assert_eq!(WriteModify::ZeroToSet.apply(0, 0b1110) & 0xF, 0b0001);
        assert_eq!(
            WriteModify::ZeroToToggle.apply(0b1111, 0b1110) & 0xF,
            0b1110
        );
        assert_eq!(WriteModify::Clear.apply(0b1111, 0b0101), 0);
        assert_eq!(WriteModify::Modify.apply(0b1111, 0b0101), 0b1111);
        for modify in [
            WriteModify::None,
            WriteModify::OneToClear,
            WriteModify::OneToSet,
            WriteModify::ZeroToClear,
            WriteModify::ZeroToSet,
        ] {
            assert_eq!(
                modify.apply(0xA5, modify.neutral(0xA5)) & 0xFF,
                0xA5,
                "{modify:?}"
            );
        }
    }

    #[test]
    fn set_masks_to_the_register_width() {
        let mut registers = RegisterFile::new(&REGISTERS);
        registers.set(Register::Plain, 0x1_2345);
        assert_eq!(registers.get(Register::Plain), 0x2345);
    }

    #[test]
    fn reset_restores_values_and_forgets_first_writes() {
        let mut registers = RegisterFile::new(&REGISTERS);
        registers.bus_write(Register::Once.index(), 1);
        registers.bus_write(Register::Once.index(), 2);
        assert_eq!(registers.get(Register::Once), 1);
        registers.reset();
        assert_eq!(registers.get(Register::Once), 0xBEEF);
        registers.bus_write(Register::Once.index(), 3);
        assert_eq!(
            registers.get(Register::Once),
            3,
            "the first write after reset lands again"
        );
    }

    #[test]
    fn a_read_only_register_ignores_writes_and_clears_on_read() {
        let mut registers = RegisterFile::new(&REGISTERS);
        registers.bus_write(Register::Pop.index(), 0);
        assert_eq!(registers.bus_read(Register::Pop.index()), 0xBEEF);
        assert_eq!(registers.bus_read(Register::Pop.index()), 0);
    }

    #[test]
    fn a_field_may_clear_on_read_while_its_register_does_not() {
        let mut registers = RegisterFile::new(&REGISTERS);
        assert_eq!(registers.bus_read(Register::Status.index()), 0xBEEF);
        assert_eq!(registers.get(Register::Status), 0xBEEE, "only FLAG cleared");
    }

    #[test]
    fn rows_are_found_by_the_offset_they_cover() {
        let registers = RegisterFile::new(&REGISTERS);
        assert_eq!(registers.row_covering(0x2, Access::is_readable), Some(1));
        assert_eq!(
            registers.row_covering(0x3, Access::is_readable),
            Some(1),
            "the second byte of ONCE"
        );
        assert_eq!(registers.row_covering(0x8, Access::is_readable), None);
    }
}