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;
const R1_IDLE: u8 = 0x01;
const DATA_ACCEPTED: u8 = 0x05;
const DATA_WRITE_ERROR: u8 = 0x0b;
#[derive(Clone, Copy, PartialEq, Eq)]
enum WritePhase {
Idle,
AwaitToken,
Data,
Crc,
}
pub struct MicroSd {
image: Vec<u8>,
command: Vec<u8>,
response: VecDeque<u8>,
idle: bool,
app_cmd: bool,
selected: bool,
commands: u32,
write_phase: WritePhase,
write_block: u32,
write_data: Vec<u8>,
write_crc: u8,
written_blocks: u64,
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,
}
}
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}")),
}
}
pub fn image(&self) -> &[u8] {
&self.image
}
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;
}
pub fn dirty(&self) -> bool {
self.dirty
}
pub fn written_blocks(&self) -> u64 {
self.written_blocks
}
pub fn take_written_blocks(&mut self) -> u64 {
std::mem::take(&mut self.written_blocks)
}
pub fn save_to(&self, path: &Path) -> io::Result<()> {
std::fs::write(path, &self.image)
}
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)
}
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 {
self.response.push_back(0x40);
}
}
24 => {
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),
}
}
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 {
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 => {
self.write_crc += 1;
if self.write_crc == 2 {
self.store_block();
}
}
WritePhase::Idle => {}
}
}
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;
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();
}
}
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() {
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)
}
}
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> {
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
}
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); 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]);
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);
}
}