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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The registers a timer has by what they do, the kinds of timer, and what a part says of its own.
//!
//! Every timer of both manuals keeps a register at the same offset, so the model names one by its
//! [`Slot`] and finds the row a layout holds it in once, when the timer is built. A slot's offset is
//! the one the part's own tables give the register by name, which is how `0x50` is `TIMx_OR` on
//! the STM32F427 and nothing on the STM32H743, whose `TIMx_CCMR3` is at `0x54`. A layout that has no
//! row for a slot answers zero and stores nothing.

use std::fmt;

use crate::device::{Level, RequestChange};
use crate::soc::{Layout, RegisterSpec, find_row};

pub(crate) const ROWS: usize = 28;

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) enum Slot {
    Cr1,
    Cr2,
    Smcr,
    Dier,
    Sr,
    Egr,
    Ccmr1,
    Ccmr2,
    Ccer,
    Cnt,
    Psc,
    Arr,
    Rcr,
    Ccr1,
    Ccr2,
    Ccr3,
    Ccr4,
    Bdtr,
    Dcr,
    Dmar,
    Or,
    Ccmr3,
    Ccr5,
    Ccr6,
    Af1,
    Af2,
    Tisel,
}

pub(crate) const SLOTS: usize = 27;

impl Slot {
    pub(crate) const ALL: [Self; SLOTS] = [
        Self::Cr1,
        Self::Cr2,
        Self::Smcr,
        Self::Dier,
        Self::Sr,
        Self::Egr,
        Self::Ccmr1,
        Self::Ccmr2,
        Self::Ccer,
        Self::Cnt,
        Self::Psc,
        Self::Arr,
        Self::Rcr,
        Self::Ccr1,
        Self::Ccr2,
        Self::Ccr3,
        Self::Ccr4,
        Self::Bdtr,
        Self::Dcr,
        Self::Dmar,
        Self::Or,
        Self::Ccmr3,
        Self::Ccr5,
        Self::Ccr6,
        Self::Af1,
        Self::Af2,
        Self::Tisel,
    ];

    // A mode register's two views share a row, and the input view's name finds it.
    const fn name(self) -> &'static str {
        match self {
            Self::Cr1 => "CR1",
            Self::Cr2 => "CR2",
            Self::Smcr => "SMCR",
            Self::Dier => "DIER",
            Self::Sr => "SR",
            Self::Egr => "EGR",
            Self::Ccmr1 => "CCMR1_Input",
            Self::Ccmr2 => "CCMR2_Input",
            Self::Ccer => "CCER",
            Self::Cnt => "CNT",
            Self::Psc => "PSC",
            Self::Arr => "ARR",
            Self::Rcr => "RCR",
            Self::Ccr1 => "CCR1",
            Self::Ccr2 => "CCR2",
            Self::Ccr3 => "CCR3",
            Self::Ccr4 => "CCR4",
            Self::Bdtr => "BDTR",
            Self::Dcr => "DCR",
            Self::Dmar => "DMAR",
            Self::Or => "OR",
            Self::Ccmr3 => "CCMR3_Output",
            Self::Ccr5 => "CCR5",
            Self::Ccr6 => "CCR6",
            Self::Af1 => "AF1",
            Self::Af2 => "AF2",
            Self::Tisel => "TISEL",
        }
    }

    pub(crate) const fn index(self) -> usize {
        self as usize
    }
}

pub(crate) const fn offsets(part: &Part) -> [Option<u32>; SLOTS] {
    let mut offsets = [None; SLOTS];
    let mut slot = 0;
    while slot < SLOTS {
        let name = Slot::ALL[slot].name();
        let mut table = 0;
        while table < part.tables.len() && offsets[slot].is_none() {
            if let Some(row) = find_row(part.tables[table], name) {
                offsets[slot] = Some(part.tables[table][row].offset);
            }
            table += 1;
        }
        slot += 1;
    }
    offsets
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) struct Map {
    rows: [Option<u8>; SLOTS],
    slots: [Option<Slot>; ROWS],
}

impl Map {
    pub(crate) fn of(table: &[RegisterSpec], offsets: &[Option<u32>; SLOTS]) -> Self {
        let mut map = Self {
            rows: [None; SLOTS],
            slots: [None; ROWS],
        };
        for (row, spec) in table.iter().enumerate() {
            let slot = Slot::ALL
                .into_iter()
                .find(|slot| offsets[slot.index()] == Some(spec.offset));
            map.slots[row] = slot;
            if let Some(slot) = slot
                && map.rows[slot.index()].is_none()
            {
                map.rows[slot.index()] = u8::try_from(row).ok();
            }
        }
        map
    }

    pub(crate) fn row(&self, slot: Slot) -> Option<usize> {
        self.rows[slot.index()].map(usize::from)
    }

    pub(crate) fn slot(&self, row: usize) -> Option<Slot> {
        self.slots.get(row).copied().flatten()
    }
}

/// How wide an instance's counter is: sixteen bits, or thirty-two on the general-purpose TIM2 and
/// TIM5 of both parts, RM0090 rev 22 section 18.2 and RM0433 rev 9 section 39.2. `CNT`, `ARR` and
/// every `CCRx` count, reload and compare in it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Counter {
    /// Sixteen bits.
    Narrow,
    /// Thirty-two bits: TIM2 and TIM5.
    Wide,
}

impl Counter {
    /// What a count, an auto-reload and a capture/compare value wrap in, and `ARR`'s reset value.
    #[must_use]
    pub const fn mask(self) -> u64 {
        match self {
            Self::Narrow => super::HALF_WORD,
            Self::Wide => super::WORD,
        }
    }
}

/// Which timer a model stands for. A kind decides how many channels the timer has, which of the modes
/// and inputs of its layout exist on it, and which break and dead-time it has. It's what separates
/// timers that share a layout, as RM0433 rev 9's TIM2 to TIM5 and TIM12 to TIM14 do.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Kind {
    /// RM0433 rev 9's TIM1 and TIM8, chapter 38: six channels, four with pins, a sixteen-bit
    /// repetition counter, two break inputs, three complementary outputs and every mode.
    Advanced,
    /// RM0090 rev 22's TIM1 and TIM8, chapter 17: four channels, an eight-bit repetition counter, one
    /// break input on its pin, three complementary outputs and the modes of a three-bit `OCxM`.
    FourChannelBreak,
    /// TIM2 to TIM5 of RM0090 rev 22 chapter 18 and RM0433 rev 9 chapter 39: four channels, up, down
    /// and center-aligned counting, the encoder interface, the external trigger input and every
    /// output mode but the break's.
    General,
    /// RM0433 rev 9's TIM12, section 40.4: two channels and a slave mode controller, up counting only.
    TwoChannelSlave,
    /// RM0433 rev 9's TIM13 and TIM14, section 40.5: one channel, up counting only, no slave mode
    /// controller.
    OneChannel,
    /// RM0433 rev 9's TIM15, section 41.5: two channels, one with a complementary output, a repetition
    /// counter, a break input and a slave mode controller, up counting only.
    TwoChannelBreak,
    /// RM0433 rev 9's TIM16 and TIM17, section 41.6: one channel with a complementary output, a
    /// repetition counter and a break input, no slave mode controller.
    OneChannelBreak,
    /// RM0433 rev 9's TIM6 and TIM7, chapter 42: no channels, a time base that drives the converters.
    Basic,
}

impl Kind {
    /// How many capture/compare channels the timer has, counting the advanced timer's two without pins.
    #[must_use]
    pub const fn channels(self) -> u8 {
        match self {
            Self::Advanced => 6,
            Self::FourChannelBreak | Self::General => 4,
            Self::TwoChannelSlave | Self::TwoChannelBreak => 2,
            Self::OneChannel | Self::OneChannelBreak => 1,
            Self::Basic => 0,
        }
    }

    pub(super) const fn up_down(self) -> bool {
        matches!(
            self,
            Self::Advanced | Self::FourChannelBreak | Self::General
        )
    }

    pub(super) const fn external_trigger(self) -> bool {
        self.up_down()
    }

    pub(super) const fn slave(self) -> bool {
        matches!(
            self,
            Self::Advanced
                | Self::FourChannelBreak
                | Self::General
                | Self::TwoChannelSlave
                | Self::TwoChannelBreak
        )
    }

    pub(super) const fn master(self) -> bool {
        self.slave() || matches!(self, Self::Basic)
    }

    pub(super) const fn dma(self) -> bool {
        !matches!(self, Self::TwoChannelSlave | Self::OneChannel)
    }

    // `REP`: RM0090 rev 22 17.4.13, and RM0433 rev 9 38.4.15, 41.5.13 and 41.6.12.
    pub(super) const fn repetition_mask(self) -> u64 {
        match self {
            Self::Advanced => super::HALF_WORD,
            Self::FourChannelBreak | Self::TwoChannelBreak | Self::OneChannelBreak => {
                super::fields::BYTE
            }
            _ => 0,
        }
    }

    pub(super) const fn breaks(self) -> usize {
        match self {
            Self::Advanced => 2,
            Self::FourChannelBreak | Self::TwoChannelBreak | Self::OneChannelBreak => 1,
            _ => 0,
        }
    }

    // RM0433 rev 9 38.4.26 to 38.4.29. RM0090 rev 22's break is its `BKIN` pin alone, 17.3.12.
    pub(super) const fn gathers_break_sources(self) -> bool {
        matches!(
            self,
            Self::Advanced | Self::TwoChannelBreak | Self::OneChannelBreak
        )
    }

    pub(super) const fn complementary(self) -> usize {
        match self {
            Self::Advanced | Self::FourChannelBreak => 3,
            Self::TwoChannelBreak | Self::OneChannelBreak => 1,
            _ => 0,
        }
    }

    pub(super) const fn xor_inputs(self) -> usize {
        match self {
            Self::Advanced | Self::FourChannelBreak | Self::General => 3,
            Self::TwoChannelSlave | Self::TwoChannelBreak => 2,
            _ => 0,
        }
    }

    // `SBIF`, RM0433 rev 9 38.4.5. Every other timer flags a system break in `BIF`, RM0090 rev 22 17.3.12.
    pub(super) const fn system_break_flag(self) -> bool {
        matches!(self, Self::Advanced)
    }

    // `TRGO2` and `MMS2`, RM0433 rev 9 38.4.2.
    pub(super) const fn second_trigger(self) -> bool {
        matches!(self, Self::Advanced)
    }

    pub(super) const fn has_mode(self, mode: u64) -> bool {
        match mode {
            0..=7 => true,
            8 | 9 | 12 | 13 => matches!(
                self,
                Self::Advanced | Self::General | Self::TwoChannelSlave | Self::TwoChannelBreak
            ),
            14 | 15 => matches!(self, Self::Advanced | Self::General),
            _ => false,
        }
    }
}

/// One timer as the part wires it: the instance, how wide it counts and which timer it is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Timer {
    /// The instance, as the vendor names it.
    pub instance: &'static str,
    /// What it counts in.
    pub counter: Counter,
    /// What it is.
    pub kind: Kind,
}

impl Timer {
    /// The row for `instance`.
    #[must_use]
    pub const fn new(instance: &'static str, counter: Counter, kind: Kind) -> Self {
        Self {
            instance,
            counter,
            kind,
        }
    }
}

/// What a part builds one of its timers from.
pub trait Instance: Copy {
    /// How wide it counts.
    fn counter(self) -> Counter;
    /// Which timer it is, where it says, or `None` for the family's one kind.
    fn kind(self) -> Option<Kind>;
    /// The instance's name, where the part acknowledges a request to it by name.
    fn name(self) -> Option<&'static str>;
}

impl Instance for Timer {
    fn counter(self) -> Counter {
        self.counter
    }

    fn kind(self) -> Option<Kind> {
        Some(self.kind)
    }

    fn name(self) -> Option<&'static str> {
        Some(self.instance)
    }
}

impl Instance for Counter {
    fn counter(self) -> Counter {
        self
    }

    fn kind(self) -> Option<Kind> {
        None
    }

    fn name(self) -> Option<&'static str> {
        None
    }
}

/// The interrupt a timer raises, by position in its instance's table.
///
/// The advanced timers have four, break, update, trigger with commutation, and capture and compare,
/// RM0090 rev 22 table 63 and RM0433 rev 9 Table 147. Every other timer has one line for all of its
/// events.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Flags {
    /// `BIF`, and `B2IF` and `SBIF` where the part has them.
    Break,
    /// `UIF`.
    Update,
    /// `TIF` and `COMIF`.
    TriggerAndCommutation,
    /// `CCxIF`.
    CaptureCompare,
}

/// Which layout a timer is addressed through, which kinds of timer use it, and the part it's in.
pub trait Family: fmt::Debug + Copy + Send + Sync + 'static {
    /// The register layout an instance of this family is addressed through.
    type Register: Layout + Send;
    /// What the part builds one of these timers from.
    type Instance: Instance;
    /// What the part says of every timer it carries.
    const PART: &'static Part;
    /// The kinds of timer that use the layout.
    const KINDS: &'static [Kind];
    /// How many interrupt lines the instance has, which is the length of its table.
    const LINES: usize = 1;
    /// The position in the instance's table of the line a kind of flag raises, the one line by default.
    fn line(_: Flags) -> usize {
        GLOBAL
    }
    /// The table an instance counting in `counter` answers from, which is the layout's own unless the
    /// part gives narrower instances a shorter table.
    fn layout(_counter: Counter) -> &'static [RegisterSpec] {
        <Self::Register as Layout>::REGISTERS
    }
}

/// What a part's manual and errata sheet give its timers that the other part's don't.
#[derive(Debug)]
pub struct Part {
    /// The tables ST's file gives the part's timers, searched in order for a register or a field by
    /// name.
    pub tables: &'static [&'static [RegisterSpec]],
    /// The fields the file names otherwise than the manual.
    pub spellings: &'static [Spelling],
    /// When a timer asks to be woken for its counter's events.
    pub wakeups: Wakeups,
    /// What the `BKIN` pin carries before anything drives it.
    pub break_pin: Option<Level>,
    /// Which of a timer's requests, in its own numbering, a request change from another instance
    /// acknowledges, given the timer's name. `None` on a part that acknowledges none.
    pub acknowledged: Option<fn(&str, &RequestChange) -> Option<usize>>,
    /// The timer errata the part's sheet gives it.
    pub errata: Errata,
}

/// A field ST's file names otherwise than the manual.
#[derive(Debug)]
pub struct Spelling {
    /// The register, as the file names it.
    pub register: &'static str,
    /// The field, as the manual names it.
    pub manual: &'static str,
    /// The field, as the file names it.
    pub file: &'static str,
}

/// When a timer asks the event queue to wake it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Wakeups {
    /// At every counter event.
    Every,
    /// Only while something outside the timer could see its counter's events: an interrupt or a
    /// request enabled, a pin driven, a trigger output or a slave that follows them, one pulse mode
    /// ending the count, or a break. The next access settles the rest.
    WhenSeen,
}

/// The timer errata a part's sheet gives it, each of which the model reproduces.
#[derive(Debug)]
pub struct Errata {
    /// A compare match one counter cycle after the previous one, brought by a `CCR` change, is missed
    /// in three patterns. ES0206 rev 24 2.7.3 and ES0392 rev 15 2.16.2.
    pub consecutive_compare_missed: bool,
    /// An `OCxREF` cleared by `ETRF` stays inactive one extra period when the slave reset comes before
    /// the compare. ES0206 rev 24 2.7.4 and ES0392 rev 15 2.16.3.
    pub clear_outlasts_reset: bool,
    /// In combined reset and trigger mode with `MSM` and one pulse mode, a trigger arriving at `ARR`
    /// starts no pulse. ES0392 rev 15 2.16.1.
    pub trigger_lost_at_reload: bool,
}

const GLOBAL: usize = 0;

/// The DMA request an update event makes, in the instance's own numbering: `tim_up_dma`.
pub const UPDATE_REQUEST: usize = 0;

/// The DMA requests of capture/compare events 1 to 4, `tim_ch1_dma` to `tim_ch4_dma`.
pub const CHANNEL_REQUESTS: [usize; 4] = [1, 2, 3, 4];

/// The DMA request of a trigger event, `tim_trig_dma`.
pub const TRIGGER_REQUEST: usize = 5;

/// The DMA request of a commutation event, `tim_com_dma`.
pub const COMMUTATION_REQUEST: usize = 6;