litz-board 0.5.1

Board runtime for Litz: flatten a diagram, resolve nets, and drive parts from pin levels.
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
//! A microSD card on SPI.
//!
//! Only the card's own command layer is modelled: CMD0, CMD8, the APP_CMD /
//! ACMD41 handshake, CMD16, CMD17 single-block reads and CMD24 single-block
//! writes. There is no FAT filesystem above it; a firmware that speaks the SPI
//! protocol sees a card that initialises, returns the bytes of its image, and
//! stores a block it writes back into that same image.
//!
//! The image never comes from an arbitrary path written in a diagram. An
//! `image` attribute is accepted only as a relative path with no `..`, and the
//! resolved file is canonicalised and checked to stay inside the project
//! directory. A host that already has bytes can use [`MicroSd::with_image`] and
//! bypass the filesystem entirely, which is the path the browser uses.
//!
//! Writes mutate the in-memory image only. A native runner can persist the
//! result with [`MicroSd::save_to`], or call [`MicroSd::save_changed`] at the
//! end of a run and have it do nothing when the card was never written.

use crate::bus::SpiDevice;
use crate::flatten::FlatPart;
use std::any::Any;
use std::collections::VecDeque;
use std::io;
use std::path::{Component, Path, PathBuf};

const BLOCK: usize = 512;
const TOKEN_START: u8 = 0xfe;
/// The idle response bit CMD0 and CMD8 report.
const R1_IDLE: u8 = 0x01;
/// A data-response token saying the card accepted the block.
const DATA_ACCEPTED: u8 = 0x05;
/// A data-response token saying the card could not store the block.
const DATA_WRITE_ERROR: u8 = 0x0b;

/// Where a CMD24 transfer is in its data phase.
#[derive(Clone, Copy, PartialEq, Eq)]
enum WritePhase {
    /// No write is pending; bytes are commands.
    Idle,
    /// The R1 response is out; waiting for the start token.
    AwaitToken,
    /// Collecting the block's 512 data bytes.
    Data,
    /// Consuming the block's two CRC bytes.
    Crc,
}

/// A microSD card backed by a byte image.
pub struct MicroSd {
    image: Vec<u8>,
    /// The six bytes of the command currently being shifted in.
    command: Vec<u8>,
    response: VecDeque<u8>,
    idle: bool,
    app_cmd: bool,
    selected: bool,
    commands: u32,
    /// The CMD24 data-phase state.
    write_phase: WritePhase,
    /// Block address accepted by CMD24, in 512-byte units.
    write_block: u32,
    /// The block being collected; exactly 512 bytes once complete.
    write_data: Vec<u8>,
    /// CRC bytes consumed so far in [`WritePhase::Crc`].
    write_crc: u8,
    /// Blocks stored since construction or the last image replacement.
    written_blocks: u64,
    /// Whether blocks were written since construction, last save or reset.
    dirty: bool,
}

impl MicroSd {
    pub fn new() -> Self {
        Self::with_image(Vec::new())
    }

    pub fn with_image(image: Vec<u8>) -> Self {
        Self {
            image,
            command: Vec::new(),
            response: VecDeque::new(),
            idle: true,
            app_cmd: false,
            selected: false,
            commands: 0,
            write_phase: WritePhase::Idle,
            write_block: 0,
            write_data: Vec::with_capacity(BLOCK),
            write_crc: 0,
            written_blocks: 0,
            dirty: false,
        }
    }

    /// Build a card from a manifest. `image` is optional; without it the card
    /// is blank but still initialises.
    pub fn from_attrs(part: &FlatPart) -> Result<Self, String> {
        let Some(text) = part.attrs.get("image").map(String::as_str).map(str::trim) else {
            return Ok(Self::new());
        };
        if text.is_empty() {
            return Ok(Self::new());
        }
        let path = relative_image_path(text)?;
        match read_image(&path) {
            Ok(image) => Ok(Self::with_image(image)),
            Err(error) => Err(format!("image {text:?}: {error}")),
        }
    }

    /// The bytes on the card.
    pub fn image(&self) -> &[u8] {
        &self.image
    }

    /// Replace the card contents. The write counters and the dirty flag reset:
    /// the new image is the card's baseline.
    pub fn set_image(&mut self, image: Vec<u8>) {
        self.image = image;
        self.write_phase = WritePhase::Idle;
        self.write_data.clear();
        self.write_crc = 0;
        self.written_blocks = 0;
        self.dirty = false;
    }

    /// Whether blocks were written since construction or the last save.
    pub fn dirty(&self) -> bool {
        self.dirty
    }

    /// Blocks stored since construction or the last image replacement.
    pub fn written_blocks(&self) -> u64 {
        self.written_blocks
    }

    /// Take the number of blocks written since the previous call and reset the
    /// counter. The dirty flag is unaffected; [`MicroSd::save_changed`] still
    /// sees a pending change.
    pub fn take_written_blocks(&mut self) -> u64 {
        std::mem::take(&mut self.written_blocks)
    }

    /// Write the full card image to `path`: the same bytes a reader of a real
    /// card would see, including whatever boot sector or partition table the
    /// image carries.
    pub fn save_to(&self, path: &Path) -> io::Result<()> {
        std::fs::write(path, &self.image)
    }

    /// Save the image only when a block was written. Returns `true` when a
    /// file was written and `false` when the card is clean, so a runner can
    /// call this unconditionally at the end of a run.
    pub fn save_changed(&mut self, path: &Path) -> io::Result<bool> {
        if !self.dirty {
            return Ok(false);
        }
        self.save_to(path)?;
        self.dirty = false;
        Ok(true)
    }

    /// How many commands the card has answered, for a diagnostic.
    pub fn commands(&self) -> u32 {
        self.commands
    }

    pub fn idle(&self) -> bool {
        self.idle
    }

    fn execute(&mut self) {
        let command = self.command[0] & 0x3f;
        let argument = u32::from_be_bytes([
            self.command[1],
            self.command[2],
            self.command[3],
            self.command[4],
        ]);
        self.commands += 1;
        let was_app = self.app_cmd;
        self.app_cmd = false;
        match command {
            0 => {
                self.idle = true;
                self.response.push_back(R1_IDLE);
            }
            8 => {
                self.idle = true;
                self.response.extend([R1_IDLE, 0x00, 0x00, 0x01, 0xaa]);
                self.app_cmd = false;
            }
            55 => {
                self.app_cmd = true;
                self.response
                    .push_back(if self.idle { R1_IDLE } else { 0x00 });
            }
            41 if was_app => {
                self.idle = false;
                self.response.push_back(0x00);
            }
            58 => {
                self.idle = false;
                self.response.extend([0x00, 0x00, 0xff, 0x80, 0x00]);
            }
            16 => self.response.push_back(0x00),
            17 => {
                let offset = argument as usize * BLOCK;
                if offset + BLOCK <= self.image.len() {
                    self.response.push_back(0x00);
                    self.response.push_back(TOKEN_START);
                    self.response
                        .extend(self.image[offset..offset + BLOCK].iter().copied());
                    self.response.extend([0xff, 0xff]);
                } else {
                    // Parameter error: the block is outside the image.
                    self.response.push_back(0x40);
                }
            }
            24 => {
                // The write is accepted only for a block the image already
                // has room for; the data itself arrives after this command.
                let end = (argument as usize)
                    .checked_mul(BLOCK)
                    .and_then(|offset| offset.checked_add(BLOCK));
                if end.is_some_and(|end| end <= self.image.len()) {
                    self.write_block = argument;
                    self.write_data.clear();
                    self.write_crc = 0;
                    self.write_phase = WritePhase::AwaitToken;
                    self.response.push_back(0x00);
                } else {
                    self.response.push_back(0x40);
                }
            }
            _ => self.response.push_back(0x04),
        }
    }

    /// One byte on the wire while a CMD24 data phase is pending.
    fn write_byte(&mut self, byte: u8) {
        match self.write_phase {
            WritePhase::AwaitToken => {
                if byte == TOKEN_START {
                    self.write_data.clear();
                    self.write_phase = WritePhase::Data;
                } else if byte & 0xc0 == 0x40 {
                    // A fresh command abandons the pending write rather than
                    // wedging the card on a token that never comes.
                    self.write_phase = WritePhase::Idle;
                    self.command.clear();
                    self.command.push(byte);
                }
            }
            WritePhase::Data => {
                self.write_data.push(byte);
                if self.write_data.len() == BLOCK {
                    self.write_phase = WritePhase::Crc;
                    self.write_crc = 0;
                }
            }
            WritePhase::Crc => {
                // The CRC is consumed but not checked: SPI mode leaves data
                // CRC checking off, and a firmware may send dummy bytes.
                self.write_crc += 1;
                if self.write_crc == 2 {
                    self.store_block();
                }
            }
            WritePhase::Idle => {}
        }
    }

    /// Commit the collected block and answer with a data-response token.
    fn store_block(&mut self) {
        let offset = (self.write_block as usize).checked_mul(BLOCK);
        let stored = offset.filter(|offset| {
            offset
                .checked_add(BLOCK)
                .is_some_and(|end| end <= self.image.len())
        });
        if let Some(offset) = stored {
            self.image[offset..offset + BLOCK].copy_from_slice(&self.write_data[..BLOCK]);
            self.written_blocks += 1;
            self.dirty = true;
            // The transfer loop pops a response for the byte it just handled,
            // so the leading 0xff sits on the second CRC byte and the token is
            // shifted out on the next byte, as a real card does.
            self.response.extend([0xff, DATA_ACCEPTED, 0x00, 0xff]);
        } else {
            self.response.extend([0xff, DATA_WRITE_ERROR, 0x00, 0xff]);
        }
        self.write_phase = WritePhase::Idle;
        self.write_data.clear();
        self.write_crc = 0;
    }
}

impl Default for MicroSd {
    fn default() -> Self {
        Self::new()
    }
}

impl SpiDevice for MicroSd {
    fn select(&mut self, selected: bool) {
        self.selected = selected;
        if !selected {
            self.command.clear();
            self.response.clear();
            // `app_cmd` is card state, not transaction state: CMD55 and the
            // ACMD that follows it are normally separate chip-select windows.
        }
    }

    fn transfer(&mut self, tx: &[u8], rx_len: usize) -> Vec<u8> {
        if !self.selected {
            return vec![0xff; rx_len];
        }
        let mut out = Vec::with_capacity(rx_len.max(tx.len()));
        for &byte in tx {
            if self.write_phase == WritePhase::Idle {
                if self.command.is_empty() {
                    // A command starts with 01xxxxxx; 0xff dummy clocks and
                    // data bytes with other high bits are ignored.
                    if byte & 0xc0 == 0x40 {
                        self.command.push(byte);
                    }
                } else {
                    self.command.push(byte);
                    if self.command.len() == 6 {
                        self.execute();
                        self.command.clear();
                    }
                }
            } else {
                self.write_byte(byte);
            }
            out.push(self.response.pop_front().unwrap_or(0xff));
        }
        out.resize(rx_len, 0xff);
        out.truncate(rx_len);
        out
    }

    fn as_any(&self) -> Option<&dyn Any> {
        Some(self)
    }

    fn as_any_mut(&mut self) -> Option<&mut dyn Any> {
        Some(self)
    }
}

/// Validate that a manifest's image path is relative and cannot climb out of
/// its directory. Symlinks are handled later, after canonicalisation.
fn relative_image_path(text: &str) -> Result<PathBuf, String> {
    if text.trim().is_empty() {
        return Err("the image path is empty".into());
    }
    let path = Path::new(text);
    if path.is_absolute() {
        return Err("the image path must be relative, not absolute".into());
    }
    for component in path.components() {
        match component {
            Component::Normal(part) if !part.is_empty() => {}
            Component::CurDir => {}
            _ => {
                return Err(
                    "the image path must stay inside the project directory (no `..`, root or prefix)"
                        .into(),
                );
            }
        }
    }
    Ok(path.to_path_buf())
}

#[cfg(not(target_arch = "wasm32"))]
fn read_image(relative: &Path) -> Result<Vec<u8>, String> {
    let base = std::env::current_dir().map_err(|error| format!("no current directory: {error}"))?;
    let base = base
        .canonicalize()
        .map_err(|error| format!("the project directory is not readable: {error}"))?;
    let candidate = base.join(relative);
    let candidate = candidate
        .canonicalize()
        .map_err(|error| format!("cannot resolve {}: {error}", candidate.display()))?;
    if !candidate.starts_with(&base) {
        return Err("the image resolves outside the project directory".into());
    }
    if !candidate.is_file() {
        return Err(format!("{} is not a file", candidate.display()));
    }
    std::fs::read(&candidate)
        .map_err(|error| format!("cannot read {}: {error}", candidate.display()))
}

#[cfg(target_arch = "wasm32")]
fn read_image(_relative: &Path) -> Result<Vec<u8>, String> {
    // A browser build has no project directory to read from; the host sets the
    // card's bytes through the model instead.
    Ok(Vec::new())
}

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

    fn card(image: Vec<u8>) -> MicroSd {
        MicroSd::with_image(image)
    }

    fn exchange(card: &mut MicroSd, tx: &[u8]) -> Vec<u8> {
        card.select(true);
        let out = card.transfer(tx, tx.len());
        card.select(false);
        out
    }

    /// Send one command and return the bytes the card shifted out after the
    /// command (its first response byte arrives on the command's last byte).
    fn command(card: &mut MicroSd, index: u8, argument: u32, padding: usize) -> Vec<u8> {
        let mut tx = Vec::new();
        tx.extend_from_slice(&[0xff, 0x40 | index]);
        tx.extend_from_slice(&argument.to_be_bytes());
        tx.push(0x95); // a CRC the model does not check
        tx.extend(std::iter::repeat_n(0xff, padding));
        let reply = exchange(card, &tx);
        reply[6..].to_vec()
    }

    #[test]
    fn a_card_initialises_from_cmd0_and_cmd8() {
        let mut card = card(Vec::new());
        assert_eq!(command(&mut card, 0, 0, 1)[0], R1_IDLE);
        let reply = command(&mut card, 8, 0x1aa, 4);
        assert_eq!(&reply[..5], &[0x01, 0x00, 0x00, 0x01, 0xaa]);
        // The APP_CMD / ACMD41 handshake leaves the card ready.
        command(&mut card, 55, 0, 1);
        assert_eq!(command(&mut card, 41, 0, 1)[0], 0x00);
        assert!(!card.idle());
    }

    #[test]
    fn cmd17_reads_one_block_from_the_image() {
        let mut image = vec![0u8; 1024];
        image[0] = b'L';
        image[1] = b'i';
        image[2] = b't';
        image[3] = b'z';
        let mut card = card(image);
        let reply = command(&mut card, 17, 0, BLOCK + 4);
        assert_eq!(reply[0], 0x00, "R1 accepted");
        assert_eq!(reply[1], TOKEN_START);
        assert_eq!(&reply[2..6], b"Litz");

        let reply = command(&mut card, 17, 1, BLOCK + 4);
        assert_eq!(reply[0], 0x00);
        assert_eq!(reply[1], TOKEN_START);
        assert_eq!(reply[2], 0x00, "the second block is blank");
    }

    #[test]
    fn a_block_outside_the_image_is_refused() {
        let mut card = card(vec![0u8; 512]);
        let reply = command(&mut card, 17, 7, 2);
        assert_eq!(reply[0], 0x40, "parameter error");
    }

    #[test]
    fn an_image_path_may_not_escape_the_project_directory() {
        for bad in ["../card.img", "/etc/passwd", "a/../../card.img", "..", ""] {
            assert!(relative_image_path(bad).is_err(), "{bad:?}");
        }
        assert!(relative_image_path("card.img").is_ok());
        assert!(relative_image_path("data/card.img").is_ok());
    }

    #[test]
    fn a_blank_card_still_answers_commands() {
        let card = MicroSd::new();
        assert!(card.image().is_empty());
        assert_eq!(card.commands(), 0);
    }
}