rigless 0.2.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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The faults the engine armed, as the target counts toward each: a link at a time, right after
//! every access, at every stop and at every hit on what the emulator watches, once the models have
//! settled. An `After` link's instant is a pause of the session's, which the models never hear of, so a
//! run with one is the run without it up to where the fault fires. An instruction or a write is
//! watched only while a link counts it.

use super::{Armed, Code, Fault, Fired, Held, Link, LinkError, bytes_of, fits, serve::apply};
use crate::chip::Placed;
use crate::emulator::{
    Access, AccessKind, Hit, HitKind, Host, InterruptLine, Settled, Stop, Watch,
};
use crate::machine::Board;
use crate::mcu::Operate;
use crate::session::Session;
use crate::soc::{Endian, lane_shift};
use crate::symbols::{self, Symbols};
use crate::time::VirtualNanos;

/// Every fault the engine armed that hasn't fired yet, with how far its trigger has counted, and
/// every one that fired since the last answer.
///
/// A snapshot keeps what's armed and how far each has counted, so a run restored from one fires
/// where the run that took it would have. What fired is always told before a snapshot is taken.
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct Triggers {
    armed: Vec<Counting>,
    #[serde(skip)]
    fired: Vec<Fired>,
}

/// One armed fault and the link of its trigger counting now.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct Counting {
    id: u32,
    links: Vec<Link>,
    fault: Fault,
    /// The link counting now.
    next: usize,
    progress: Progress,
}

/// How far the link counting now has got.
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
enum Progress {
    /// An `After`: the instant it fires at.
    Until(VirtualNanos),
    /// An `Access`: the addresses its register spans, what it counts there, and how many more it
    /// waits for.
    Accesses {
        from: u64,
        to: u64,
        kind: AccessKind,
        mask: u64,
        value: u64,
        left: u32,
    },
    /// A `Transaction`: the chip, and the count of its ended transactions it fires at.
    Transactions { chip: u16, ended: u64 },
    /// An `Execute` or a `Write`: what the emulator watches for it, and how many more hits it waits
    /// for.
    Hits { watch: Watch, left: u32 },
}

/// Where the run stands when a link starts or a fault fires.
#[derive(Debug, Clone, Copy)]
struct Point {
    at: VirtualNanos,
    instruction_count: u64,
    program_counter: Option<u64>,
}

impl Point {
    fn of(settled: Settled) -> Self {
        match settled {
            Settled::Access { access, .. } => Self {
                at: access.virtual_time,
                instruction_count: access.instruction_count,
                program_counter: access.program_counter,
            },
            Settled::Stop(stop) => Self {
                at: stop.at,
                instruction_count: stop.instruction_count,
                program_counter: None,
            },
            Settled::Hit(hit) => Self {
                at: hit.at,
                instruction_count: hit.instruction_count,
                program_counter: (hit.kind == HitKind::Instruction).then_some(hit.address),
            },
        }
    }
}

impl Triggers {
    /// Arms `faults` at `stop`, where the run stands, after naming each instruction by the address
    /// the firmware's `symbols` give it and checking each against the board and the part. None fires
    /// here: [`Triggers::settled`] at that same stop fires those whose first links count to one.
    ///
    /// # Errors
    ///
    /// A fault the engine already armed under the same id, a register, a chip, a line or a condition
    /// the target doesn't have, a symbol the firmware doesn't name one address by or whose symbols
    /// couldn't be read, a condition's value that doesn't fit it, a write range outside RAM or partly
    /// over another, or a count or a match that could never fire. Nothing of that `Advance`'s faults
    /// is armed then.
    pub fn arm<D: Board + ?Sized>(
        &mut self,
        mut faults: Vec<Armed>,
        session: &mut Session<D>,
        stop: Stop,
        symbols: Result<&Symbols, &symbols::Error>,
    ) -> Result<(), LinkError> {
        for link in faults.iter_mut().flat_map(|armed| &mut armed.links) {
            if let Link::Execute { code, .. } = link
                && let Code::Symbol(name) = code
            {
                let address = symbols
                    .map_err(Clone::clone)
                    .and_then(|symbols| symbols.get(name))
                    .map_err(|error| {
                        LinkError::Misfit(format!(
                            "names an instruction by its symbol, and {error}"
                        ))
                    })?;
                *code = Code::Address(address);
            }
        }
        for (index, armed) in faults.iter().enumerate() {
            let mut seen = self
                .armed
                .iter()
                .map(|counting| counting.id)
                .chain(faults[..index].iter().map(|earlier| earlier.id));
            if seen.any(|id| id == armed.id) {
                return Err(LinkError::Misfit(format!(
                    "armed a fault {} that's already armed",
                    armed.id
                )));
            }
            check(armed, session)?;
        }
        // ceiling: one write range across faults; upgrade when a case needs two at once, with the
        // emulator reporting every range a store covers, since it reports a store to the first alone
        let watched: Vec<(u32, (u64, u64))> = self
            .armed
            .iter()
            .flat_map(|counting| {
                counting.links[counting.next..]
                    .iter()
                    .map(move |link| (counting.id, link))
            })
            .chain(
                faults
                    .iter()
                    .flat_map(|armed| armed.links.iter().map(move |link| (armed.id, link))),
            )
            .filter_map(|(id, link)| match *link {
                Link::Write {
                    address, length, ..
                } => Some((id, (address, address + length.get()))),
                _ => None,
            })
            .collect();
        if let Some(&(id, (from, to))) = watched.iter().find(|&&(id, range)| {
            watched
                .iter()
                .any(|&(other, watching)| other != id && watching != range)
        }) {
            return Err(LinkError::Misfit(format!(
                "armed fault {id} to watch writes from {from:#x} to {to:#x} beside another fault \
                 watching another range, and the emulator reports a store to one range only"
            )));
        }
        let point = Point::of(Settled::Stop(stop));
        let counting = faults
            .into_iter()
            .map(|armed| {
                Ok(Counting {
                    progress: start(&armed.links[0], session, point)?,
                    id: armed.id,
                    links: armed.links,
                    fault: armed.fault,
                    next: 0,
                })
            })
            .collect::<Result<Vec<_>, LinkError>>()?;
        self.armed.extend(counting);
        Ok(())
    }

    /// Counts what just happened toward every armed fault, fires each whose last link it completes,
    /// and pauses the run at the earliest `After` instant still waiting. A debugger's access isn't the
    /// core's, so nothing counts or fires on one.
    ///
    /// # Errors
    ///
    /// A chip the board no longer hands out, or conditions its edge refuses.
    pub fn settled<D: Board + ?Sized>(
        &mut self,
        session: &mut Session<D>,
        host: &mut dyn Host,
        held: &mut Held,
        settled: Settled,
    ) -> Result<(), LinkError> {
        if self.armed.is_empty() {
            return Ok(());
        }
        match settled {
            Settled::Access { access, .. } if access.program_counter.is_none() => return Ok(()),
            Settled::Access { access, value } => {
                let endian = session.mcu().cpu().endian;
                for counting in &mut self.armed {
                    counting.progress.saw(&access, value, endian);
                }
            }
            Settled::Hit(hit) => {
                for counting in &mut self.armed {
                    counting.progress.hit(&hit);
                }
            }
            Settled::Stop(_) => {}
        }
        self.fire_due(session, host, held, Point::of(settled))?;
        session.pause_at(self.pause());
        Ok(())
    }

    /// The earliest `After` instant still waiting, if one is.
    fn pause(&self) -> Option<VirtualNanos> {
        self.armed
            .iter()
            .filter_map(|counting| match counting.progress {
                Progress::Until(at) => Some(at),
                _ => None,
            })
            .min()
    }

    /// Every fault that fired since the last call, in the order it fired.
    pub fn take_fired(&mut self) -> Vec<Fired> {
        std::mem::take(&mut self.fired)
    }

    /// Moves every armed fault on past each of its links that's due at `point`, and fires those
    /// whose last link was.
    fn fire_due<D: Board + ?Sized>(
        &mut self,
        session: &mut Session<D>,
        host: &mut dyn Host,
        held: &mut Held,
        point: Point,
    ) -> Result<(), LinkError> {
        let mut index = 0;
        while index < self.armed.len() {
            let counting = &mut self.armed[index];
            let mut done = false;
            while counting.progress.due(session, point)? {
                if let Progress::Hits { watch, .. } = counting.progress {
                    session.unwatch(watch);
                }
                counting.next += 1;
                let Some(link) = counting.links.get(counting.next) else {
                    done = true;
                    break;
                };
                counting.progress = start(link, session, point)?;
            }
            if done {
                let counting = self.armed.remove(index);
                let conditions = fire(&counting.fault, session, host, held, point)?;
                self.fired.push(Fired {
                    id: counting.id,
                    at: point.at,
                    instruction_count: point.instruction_count,
                    program_counter: point.program_counter,
                    conditions,
                });
            } else {
                index += 1;
            }
        }
        Ok(())
    }
}

impl Progress {
    /// Counts `access` toward an `Access` link it matches, on a part that keeps its bytes
    /// `endian`. A debugger's access, with no instruction behind it, isn't the core's.
    fn saw(&mut self, access: &Access, read_or_written: u64, endian: Endian) {
        if let Self::Accesses {
            from,
            to,
            kind,
            mask,
            value,
            left,
        } = self
            && access.program_counter.is_some()
            && access.kind == *kind
            && (*from..*to).contains(&access.address)
            && carries(
                access,
                (*from, *to),
                endian,
                read_or_written,
                (*mask, *value),
            )
        {
            *left = left.saturating_sub(1);
        }
    }

    /// Counts `hit` toward an `Execute` or a `Write` link whose watch it is.
    fn hit(&mut self, hit: &Hit) {
        if let Self::Hits { watch, left } = self {
            let counts = match (*watch, hit.kind) {
                (Watch::Instruction(address), HitKind::Instruction) => address == hit.address,
                (Watch::Writes { address, length }, HitKind::Write) => {
                    (address..address.saturating_add(length)).contains(&hit.address)
                }
                _ => false,
            };
            if counts {
                *left = left.saturating_sub(1);
            }
        }
    }

    /// Whether the link has counted to where it fires, standing at `point`.
    fn due<D: Board + ?Sized>(
        self,
        session: &mut Session<D>,
        point: Point,
    ) -> Result<bool, LinkError> {
        Ok(match self {
            Self::Until(at) => point.at >= at,
            Self::Accesses { left, .. } | Self::Hits { left, .. } => left == 0,
            Self::Transactions { chip, ended } => place(session, chip)?.ended() >= ended,
        })
    }
}

/// Whether `access` to the register spanning `register`, reading or writing `read_or_written`,
/// carries every bit of `mask` and has them at `value`, with its bytes where the bus puts a narrow
/// access on a part that keeps its bytes `endian`: in the register's lanes that byte order gives
/// the bytes it reaches. One that runs past the register's end carries none of its bits.
fn carries(
    access: &Access,
    (from, to): (u64, u64),
    endian: Endian,
    read_or_written: u64,
    (mask, value): (u64, u64),
) -> bool {
    let bytes = u64::from(access.width.bytes());
    let shift = access
        .address
        .checked_add(bytes)
        .filter(|&end| end <= to)
        .and_then(|_| {
            let width = u32::try_from(to - from).ok()?;
            let byte = u32::try_from(access.address - from).ok()?;
            Some(lane_shift(endian, width, byte, access.width))
        });
    let (lanes, placed) = shift.map_or((0, 0), |shift| {
        (
            access.width.mask() << shift,
            (read_or_written & access.width.mask()) << shift,
        )
    });
    mask & !lanes == 0 && placed & mask == value
}

/// Starts `link` counting at `point`, and has the emulator watch what it counts.
fn start<D: Board + ?Sized>(
    link: &Link,
    session: &mut Session<D>,
    point: Point,
) -> Result<Progress, LinkError> {
    Ok(match *link {
        Link::After(length) => Progress::Until(VirtualNanos(point.at.0.saturating_add(length.0))),
        Link::Access {
            instance,
            register,
            kind,
            mask,
            value,
            count,
        } => {
            let (from, to) = span(session, instance, register)?;
            Progress::Accesses {
                from,
                to,
                kind,
                mask,
                value,
                left: count - 1,
            }
        }
        Link::Transaction { chip, count } => Progress::Transactions {
            chip,
            ended: place(session, chip)?.ended() + u64::from(count - 1),
        },
        Link::Execute {
            code: Code::Address(address),
            count,
        } => watching(session, Watch::Instruction(address), count),
        Link::Execute { .. } => {
            return Err(LinkError::Misfit(
                "names an instruction by what the target can't find".to_owned(),
            ));
        }
        Link::Write {
            address,
            length,
            count,
        } => watching(
            session,
            Watch::Writes {
                address,
                length: length.get(),
            },
            count,
        ),
    })
}

/// Has the emulator watch `watch`, and counts `count` hits on it.
fn watching<D: Board + ?Sized>(session: &mut Session<D>, watch: Watch, count: u32) -> Progress {
    session.watch(watch);
    Progress::Hits { watch, left: count }
}

/// Checks everything `armed` names against the board and the part, and every count and match it asks
/// for, before any of it counts.
fn check<D: Board + ?Sized>(armed: &Armed, session: &mut Session<D>) -> Result<(), LinkError> {
    let misfit = |why: &str| Err(LinkError::Misfit(format!("armed fault {} {why}", armed.id)));
    if armed.links.is_empty() {
        return misfit("with nothing to fire it");
    }
    for link in &armed.links {
        match *link {
            Link::Access {
                instance,
                register,
                mask,
                value,
                count,
                ..
            } => {
                span(session, instance, register)?;
                if value & !mask != 0 {
                    return misfit("to match bits its mask leaves out, which nothing ever does");
                }
                if count == 0 {
                    return misfit("to count to zero");
                }
            }
            Link::Transaction { chip, count } => {
                place(session, chip)?;
                if count == 0 {
                    return misfit("to count to zero");
                }
            }
            Link::Execute { count, .. } | Link::Write { count, .. } if count == 0 => {
                return misfit("to count to zero");
            }
            Link::Write {
                address, length, ..
            } => {
                // ceiling: a core whose addresses are its bus's, as the emulator watches the core's own;
                // upgrade when a family with an MMU runs
                let in_memory = address.checked_add(length.get()).is_some_and(|end| {
                    session.mcu().bus().memory().iter().any(|region| {
                        region.kind.is_writable()
                            && address >= region.base
                            && end <= region.base + region.size
                    })
                });
                if !in_memory {
                    return misfit("to watch writes outside the part's RAM");
                }
            }
            Link::Execute {
                code: Code::Address(address),
                ..
            } if !session
                .mcu()
                .bus()
                .memory()
                .iter()
                .any(|region| region.contains(address)) =>
            {
                return misfit("to watch an instruction outside the part's memory");
            }
            Link::After(_) | Link::Execute { .. } => {}
        }
    }
    match &armed.fault {
        Fault::Conditions(sets) => {
            let conditions = edge(session)?.conditions();
            for set in sets {
                let field = conditions.get(usize::from(set.index)).ok_or_else(|| {
                    LinkError::Misfit(format!(
                        "armed a fault setting condition {} and the board has {}",
                        set.index,
                        conditions.len()
                    ))
                })?;
                if !fits(field, set.value)? {
                    return Err(LinkError::Misfit(format!(
                        "armed a fault setting {} to {}, which doesn't fit it",
                        field.name, set.value
                    )));
                }
            }
        }
        Fault::Flip { chip, .. } | Fault::Drop { chip } => {
            place(session, *chip)?;
        }
        Fault::Interrupt { line } => {
            let lines = session.mcu().cpu().interrupt_lines;
            if *line >= lines {
                return Err(LinkError::Misfit(format!(
                    "armed a fault raising line {line} and the part has {lines}"
                )));
            }
        }
        Fault::Reset => {}
        Fault::BusError { instance, register } => {
            span(session, *instance, *register)?;
        }
    }
    Ok(())
}

/// Does what `fault` does at `point`, and answers the conditions it set.
fn fire<D: Board + ?Sized>(
    fault: &Fault,
    session: &mut Session<D>,
    host: &mut dyn Host,
    held: &mut Held,
    point: Point,
) -> Result<Vec<super::Set>, LinkError> {
    match fault {
        Fault::Conditions(sets) => {
            apply(&mut held.conditions, sets, "condition")?;
            let edge = edge(session)?;
            edge.condition_wire(&bytes_of(edge.conditions(), &held.conditions)?)?;
            // What the step drew, drawn again under the conditions as they now stand, so noise set
            // here takes effect here too. The step's own index keys it, which the run just delivered.
            edge.draw(held.seed, held.advances.saturating_sub(1));
            return Ok(sets.clone());
        }
        Fault::Flip { chip, mask } => place(session, *chip)?.flip(*mask),
        Fault::Drop { chip } => place(session, *chip)?.drop_next(),
        Fault::Interrupt { line } => {
            let line = InterruptLine::new(*line).ok_or_else(|| {
                LinkError::Misfit(format!(
                    "armed a fault raising line {line}, past any core's"
                ))
            })?;
            session.pulse(line, host);
        }
        Fault::Reset => session.reset_by_pin(point.at, point.instruction_count, host),
        // ceiling: a CPU that ignores a failed bus transaction takes nothing from this; upgrade when
        // such a family runs, with its core family saying so and `check` refusing the fault there
        Fault::BusError { instance, register } => {
            let (from, to) = span(session, *instance, *register)?;
            session.fail_next(from, to);
        }
    }
    Ok(Vec::new())
}

/// The addresses register `register` of instance `instance` spans on the target's bus.
fn span<D: Board + ?Sized>(
    session: &mut Session<D>,
    instance: u16,
    register: u16,
) -> Result<(u64, u64), LinkError> {
    let bus = session.mcu().bus();
    let slots = bus.slots();
    let peripheral = slots
        .get(usize::from(instance))
        .ok_or_else(|| {
            LinkError::Misfit(format!(
                "names instance {instance} and the part has {}",
                slots.len()
            ))
        })?
        .peripheral();
    let spec = peripheral
        .registers
        .get(usize::from(register))
        .ok_or_else(|| {
            LinkError::Misfit(format!(
                "names register {register} of {} and it has {}",
                peripheral.name,
                peripheral.registers.len()
            ))
        })?;
    Ok((
        peripheral.base + u64::from(spec.offset),
        peripheral.base + u64::from(spec.end()),
    ))
}

fn edge<D: Board + ?Sized>(
    session: &mut Session<D>,
) -> Result<&mut dyn crate::edge::Coupled, LinkError> {
    session
        .board_mut()
        .edge()
        .ok_or_else(|| LinkError::Board("has no edge to name a chip or a condition on".to_owned()))
}

fn place<D: Board + ?Sized>(
    session: &mut Session<D>,
    chip: u16,
) -> Result<&mut dyn Placed, LinkError> {
    let edge = edge(session)?;
    let count = edge.chips().len();
    edge.place(usize::from(chip))
        .ok_or_else(|| LinkError::Misfit(format!("names chip {chip} and the board has {count}")))
}

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

    /// A narrow write matches in the lanes the bus puts it in: the low half of a word at its first
    /// byte on a little-endian part, and the high half there on a big-endian one. One that runs past
    /// the register carries none of its bits.
    #[test]
    fn a_narrow_access_carries_its_bits_in_the_parts_lanes() {
        const REGISTER: (u64, u64) = (0x4000_0010, 0x4000_0014);
        let half = Access::new(AccessKind::Write, REGISTER.0, Width::W16, 0x8000);
        let high_bit = (0x8000_0000, 0x8000_0000);
        let low_half_bit = (0x8000, 0x8000);
        assert!(carries(
            &half,
            REGISTER,
            Endian::Little,
            0x8000,
            low_half_bit
        ));
        assert!(!carries(&half, REGISTER, Endian::Little, 0x8000, high_bit));
        assert!(carries(&half, REGISTER, Endian::Big, 0x8000, high_bit));
        assert!(!carries(&half, REGISTER, Endian::Big, 0x8000, low_half_bit));
        let last = Access::new(AccessKind::Write, REGISTER.0 + 3, Width::W8, 0x80);
        assert!(carries(&last, REGISTER, Endian::Little, 0x80, high_bit));
        assert!(carries(&last, REGISTER, Endian::Big, 0x80, (0x80, 0x80)));
        let past = Access::new(AccessKind::Write, REGISTER.0 + 2, Width::W32, 0x8000);
        assert!(!carries(&past, REGISTER, Endian::Little, 0x8000, high_bit));
        assert!(carries(&past, REGISTER, Endian::Little, 0x8000, (0, 0)));
    }
}