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
542
543
544
545
546
547
548
549
550
551
552
553
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: Apache-2.0
//! The seven messages and how each one is laid into a slot.

use crate::soc::Width;

use crate::sidecar::layout::{Slot, Version};
use crate::sidecar::sync::Ordering;

#[repr(u32)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Kind {
    Hello = 1,
    Read = 2,
    Write = 3,
    Stopped = 4,
    RunUntil = 5,
    Reply = 6,
    Shutdown = 7,
}

impl Kind {
    const ALL: [Self; 7] = [
        Self::Hello,
        Self::Read,
        Self::Write,
        Self::Stopped,
        Self::RunUntil,
        Self::Reply,
        Self::Shutdown,
    ];

    fn decode(kind: u32) -> Result<Self, DecodeError> {
        Self::ALL
            .into_iter()
            .find(|candidate| *candidate as u32 == kind)
            .ok_or(DecodeError::UnknownKind(kind))
    }
}

const WIDTHS: [Width; 4] = [Width::W8, Width::W16, Width::W32, Width::W64];

fn decode_width(bits: u8) -> Result<Width, DecodeError> {
    WIDTHS
        .into_iter()
        .find(|width| width.bits() == bits)
        .ok_or(DecodeError::InvalidWidth(bits))
}

/// Why a run ended, as the wire byte in the slot.
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum StopReason {
    /// The instruction count reached the deadline.
    Deadline = 1,
    /// The CPU halted with nothing pending, and the clock warped to the deadline.
    Idle = 2,
}

impl StopReason {
    const ALL: [Self; 2] = [Self::Deadline, Self::Idle];

    fn decode(reason: u8) -> Result<Self, DecodeError> {
        Self::ALL
            .into_iter()
            .find(|candidate| *candidate as u8 == reason)
            .ok_or(DecodeError::UnknownReason(reason))
    }
}

/// A slot that failed validation on decode.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum DecodeError {
    /// The kind is not one this side of the exchange receives; zero is an empty slot.
    #[error("unknown message kind {0}")]
    UnknownKind(u32),
    /// The reason byte names no stop reason.
    #[error("unknown stop reason {0}")]
    UnknownReason(u8),
    /// The width is not 8, 16, 32, or 64 bits.
    #[error("width {0} is not a bus width")]
    InvalidWidth(u8),
    /// The packed version has bits above the thirty-two the format uses.
    #[error("version {0:#x} does not fit the packed form")]
    InvalidVersion(u64),
}

/// What the sidecar writes into its slot.
///
/// A new kind is a minor version and is meant to break an exhaustive match in the receiver, so this is deliberately not `non_exhaustive`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SidecarMessage {
    /// The first message, before any instruction executes.
    Hello {
        /// The version the sidecar speaks.
        version: Version,
    },
    /// The firmware read a peripheral address and waits for the value.
    Read {
        /// The guest address.
        address: u64,
        /// The access width; on the wire as its [`bits`](Width::bits).
        width: Width,
        /// The instructions retired including the accessing one; the access is that instruction's last act.
        instruction_count: u64,
        /// The program counter of the access.
        program_counter: u64,
        /// The virtual clock at the access; the clock deadlines are in.
        virtual_time_ns: u64,
    },
    /// The firmware wrote a peripheral address and waits for the write to take effect.
    Write {
        /// The guest address.
        address: u64,
        /// The access width; on the wire as its [`bits`](Width::bits).
        width: Width,
        /// The value written.
        value: u64,
        /// The instructions retired including the accessing one; the access is that instruction's last act.
        instruction_count: u64,
        /// The program counter of the access.
        program_counter: u64,
        /// The virtual clock at the access; the clock deadlines are in.
        virtual_time_ns: u64,
    },
    /// The run ended.
    Stopped {
        /// The instructions retired before the stop.
        instruction_count: u64,
        /// The virtual clock at the stop; the deadline, on either reason.
        virtual_time_ns: u64,
        /// Why it stopped.
        reason: StopReason,
    },
}

/// What the core writes into its slot.
///
/// A new kind is a minor version and is meant to break an exhaustive match in the receiver, so this is deliberately not `non_exhaustive`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CoreMessage {
    /// Execute until the virtual clock reaches the deadline.
    RunUntil {
        /// The virtual time to stop at.
        deadline_ns: u64,
    },
    /// The answer to an access, with the deadline the sidecar re-arms to.
    Reply {
        /// The value read; zero for a write.
        value: u64,
        /// The core's next event.
        deadline_ns: u64,
    },
    /// Exit cleanly.
    Shutdown,
}

#[derive(Default)]
struct SlotFields {
    kind: u32,
    width: u8,
    reason: u8,
    address: u64,
    value: u64,
    instruction_count: u64,
    program_counter: u64,
    virtual_time_ns: u64,
    deadline_ns: u64,
}

impl SlotFields {
    fn store(&self, slot: &Slot) {
        slot.kind.store(self.kind, Ordering::Relaxed);
        slot.width.store(self.width, Ordering::Relaxed);
        slot.reason.store(self.reason, Ordering::Relaxed);
        slot.address.store(self.address, Ordering::Relaxed);
        slot.value.store(self.value, Ordering::Relaxed);
        slot.instruction_count
            .store(self.instruction_count, Ordering::Relaxed);
        slot.program_counter
            .store(self.program_counter, Ordering::Relaxed);
        slot.virtual_time_ns
            .store(self.virtual_time_ns, Ordering::Relaxed);
        slot.deadline_ns.store(self.deadline_ns, Ordering::Relaxed);
    }

    fn load(slot: &Slot) -> Self {
        Self {
            kind: slot.kind.load(Ordering::Relaxed),
            width: slot.width.load(Ordering::Relaxed),
            reason: slot.reason.load(Ordering::Relaxed),
            address: slot.address.load(Ordering::Relaxed),
            value: slot.value.load(Ordering::Relaxed),
            instruction_count: slot.instruction_count.load(Ordering::Relaxed),
            program_counter: slot.program_counter.load(Ordering::Relaxed),
            virtual_time_ns: slot.virtual_time_ns.load(Ordering::Relaxed),
            deadline_ns: slot.deadline_ns.load(Ordering::Relaxed),
        }
    }
}

fn unpack_version(value: u64) -> Result<Version, DecodeError> {
    u32::try_from(value)
        .map(Version::unpack)
        .map_err(|_too_wide| DecodeError::InvalidVersion(value))
}

impl SidecarMessage {
    /// Stores every field into `slot`, zero where the message has none; valid only between `wait_for` returning and `hand_over`.
    pub fn encode(&self, slot: &Slot) {
        let fields = match *self {
            Self::Hello { version } => SlotFields {
                kind: Kind::Hello as u32,
                value: u64::from(version.pack()),
                ..SlotFields::default()
            },
            Self::Read {
                address,
                width,
                instruction_count,
                program_counter,
                virtual_time_ns,
            } => SlotFields {
                kind: Kind::Read as u32,
                width: width.bits(),
                address,
                instruction_count,
                program_counter,
                virtual_time_ns,
                ..SlotFields::default()
            },
            Self::Write {
                address,
                width,
                value,
                instruction_count,
                program_counter,
                virtual_time_ns,
            } => SlotFields {
                kind: Kind::Write as u32,
                width: width.bits(),
                address,
                value,
                instruction_count,
                program_counter,
                virtual_time_ns,
                ..SlotFields::default()
            },
            Self::Stopped {
                instruction_count,
                virtual_time_ns,
                reason,
            } => SlotFields {
                kind: Kind::Stopped as u32,
                reason: reason as u8,
                instruction_count,
                virtual_time_ns,
                ..SlotFields::default()
            },
        };
        fields.store(slot);
    }

    /// Reads `slot` back as a message, rejecting anything the sidecar would not write.
    pub fn decode(slot: &Slot) -> Result<Self, DecodeError> {
        let fields = SlotFields::load(slot);
        match Kind::decode(fields.kind)? {
            Kind::Hello => Ok(Self::Hello {
                version: unpack_version(fields.value)?,
            }),
            Kind::Read => Ok(Self::Read {
                address: fields.address,
                width: decode_width(fields.width)?,
                instruction_count: fields.instruction_count,
                program_counter: fields.program_counter,
                virtual_time_ns: fields.virtual_time_ns,
            }),
            Kind::Write => Ok(Self::Write {
                address: fields.address,
                width: decode_width(fields.width)?,
                value: fields.value,
                instruction_count: fields.instruction_count,
                program_counter: fields.program_counter,
                virtual_time_ns: fields.virtual_time_ns,
            }),
            Kind::Stopped => Ok(Self::Stopped {
                instruction_count: fields.instruction_count,
                virtual_time_ns: fields.virtual_time_ns,
                reason: StopReason::decode(fields.reason)?,
            }),
            other => Err(DecodeError::UnknownKind(other as u32)),
        }
    }
}

impl CoreMessage {
    /// Stores every field into `slot`, zero where the message has none; valid only between `wait_for` returning and `hand_over`.
    pub fn encode(&self, slot: &Slot) {
        let fields = match *self {
            Self::RunUntil { deadline_ns } => SlotFields {
                kind: Kind::RunUntil as u32,
                deadline_ns,
                ..SlotFields::default()
            },
            Self::Reply { value, deadline_ns } => SlotFields {
                kind: Kind::Reply as u32,
                value,
                deadline_ns,
                ..SlotFields::default()
            },
            Self::Shutdown => SlotFields {
                kind: Kind::Shutdown as u32,
                ..SlotFields::default()
            },
        };
        fields.store(slot);
    }

    /// Reads `slot` back as a message, rejecting anything the core would not write.
    pub fn decode(slot: &Slot) -> Result<Self, DecodeError> {
        let fields = SlotFields::load(slot);
        match Kind::decode(fields.kind)? {
            Kind::RunUntil => Ok(Self::RunUntil {
                deadline_ns: fields.deadline_ns,
            }),
            Kind::Reply => Ok(Self::Reply {
                value: fields.value,
                deadline_ns: fields.deadline_ns,
            }),
            Kind::Shutdown => Ok(Self::Shutdown),
            other => Err(DecodeError::UnknownKind(other as u32)),
        }
    }
}

#[cfg(not(loom))]
#[cfg(test)]
mod tests {
    use proptest::prelude::*;

    use super::*;

    fn width_strategy() -> impl Strategy<Value = Width> {
        proptest::sample::select(WIDTHS.to_vec())
    }

    fn version_strategy() -> impl Strategy<Value = Version> {
        (any::<u16>(), any::<u16>()).prop_map(|(major, minor)| Version { major, minor })
    }

    fn sidecar_message_strategy() -> impl Strategy<Value = SidecarMessage> {
        prop_oneof![
            version_strategy().prop_map(|version| SidecarMessage::Hello { version }),
            (
                any::<u64>(),
                width_strategy(),
                any::<u64>(),
                any::<u64>(),
                any::<u64>()
            )
                .prop_map(
                    |(address, width, instruction_count, program_counter, virtual_time_ns)| {
                        SidecarMessage::Read {
                            address,
                            width,
                            instruction_count,
                            program_counter,
                            virtual_time_ns,
                        }
                    }
                ),
            (
                any::<u64>(),
                width_strategy(),
                any::<u64>(),
                any::<u64>(),
                any::<u64>(),
                any::<u64>()
            )
                .prop_map(
                    |(
                        address,
                        width,
                        value,
                        instruction_count,
                        program_counter,
                        virtual_time_ns,
                    )| {
                        SidecarMessage::Write {
                            address,
                            width,
                            value,
                            instruction_count,
                            program_counter,
                            virtual_time_ns,
                        }
                    }
                ),
            (
                any::<u64>(),
                any::<u64>(),
                proptest::sample::select(StopReason::ALL.to_vec())
            )
                .prop_map(|(instruction_count, virtual_time_ns, reason)| {
                    SidecarMessage::Stopped {
                        instruction_count,
                        virtual_time_ns,
                        reason,
                    }
                }),
        ]
    }

    fn core_message_strategy() -> impl Strategy<Value = CoreMessage> {
        prop_oneof![
            any::<u64>().prop_map(|deadline_ns| CoreMessage::RunUntil { deadline_ns }),
            (any::<u64>(), any::<u64>())
                .prop_map(|(value, deadline_ns)| CoreMessage::Reply { value, deadline_ns }),
            Just(CoreMessage::Shutdown),
        ]
    }

    proptest! {
        #[test]
        fn round_trip_every_message_kind(
            sidecar in sidecar_message_strategy(),
            core in core_message_strategy(),
        ) {
            let slot = Slot::default();
            sidecar.encode(&slot);
            prop_assert_eq!(SidecarMessage::decode(&slot), Ok(sidecar));
            core.encode(&slot);
            prop_assert_eq!(CoreMessage::decode(&slot), Ok(core));
        }
    }

    #[test]
    fn decode_rejects_empty_slot() {
        let slot = Slot::default();
        assert_eq!(
            SidecarMessage::decode(&slot),
            Err(DecodeError::UnknownKind(0))
        );
        assert_eq!(CoreMessage::decode(&slot), Err(DecodeError::UnknownKind(0)));
    }

    #[test]
    fn decode_rejects_the_other_sides_kind() {
        let slot = Slot::default();
        CoreMessage::Shutdown.encode(&slot);
        assert_eq!(
            SidecarMessage::decode(&slot),
            Err(DecodeError::UnknownKind(Kind::Shutdown as u32))
        );
        SidecarMessage::Hello {
            version: Version { major: 1, minor: 0 },
        }
        .encode(&slot);
        assert_eq!(
            CoreMessage::decode(&slot),
            Err(DecodeError::UnknownKind(Kind::Hello as u32))
        );
    }

    #[test]
    fn decode_rejects_unknown_reason() {
        let slot = Slot::default();
        SidecarMessage::Stopped {
            instruction_count: 0,
            virtual_time_ns: 0,
            reason: StopReason::Idle,
        }
        .encode(&slot);
        slot.reason.store(0, Ordering::Relaxed);
        assert_eq!(
            SidecarMessage::decode(&slot),
            Err(DecodeError::UnknownReason(0))
        );
    }

    #[test]
    fn decode_rejects_width_that_is_not_a_bus_width() {
        let slot = Slot::default();
        SidecarMessage::Read {
            address: 0,
            width: Width::W32,
            instruction_count: 0,
            program_counter: 0,
            virtual_time_ns: 0,
        }
        .encode(&slot);
        slot.width.store(24, Ordering::Relaxed);
        assert_eq!(
            SidecarMessage::decode(&slot),
            Err(DecodeError::InvalidWidth(24))
        );
    }

    #[test]
    fn decode_rejects_version_above_thirty_two_bits() {
        let slot = Slot::default();
        SidecarMessage::Hello {
            version: Version { major: 1, minor: 0 },
        }
        .encode(&slot);
        slot.value.store(1 << 32, Ordering::Relaxed);
        assert_eq!(
            SidecarMessage::decode(&slot),
            Err(DecodeError::InvalidVersion(1 << 32))
        );
    }

    #[test]
    fn hello_packs_the_version_into_value() {
        let slot = Slot::default();
        SidecarMessage::Hello {
            version: Version { major: 1, minor: 2 },
        }
        .encode(&slot);
        assert_eq!(slot.value.load(Ordering::Relaxed), 0x0001_0002);
    }

    #[test]
    fn encode_zeroes_the_fields_a_message_lacks() {
        let slot = Slot::default();
        SidecarMessage::Write {
            address: 1,
            width: Width::W8,
            value: 2,
            instruction_count: 3,
            program_counter: 4,
            virtual_time_ns: 5,
        }
        .encode(&slot);
        CoreMessage::Shutdown.encode(&slot);
        let fields = SlotFields::load(&slot);
        assert_eq!(fields.kind, Kind::Shutdown as u32);
        assert_eq!(
            [
                u64::from(fields.width),
                u64::from(fields.reason),
                fields.address,
                fields.value,
                fields.instruction_count,
                fields.program_counter,
                fields.virtual_time_ns,
                fields.deadline_ns
            ],
            [0; 8]
        );
    }
}