453 lines
14 KiB
Rust
453 lines
14 KiB
Rust
//! Fixed shared-card codec. All offsets and CRC coverage are defined in the save spec.
|
|
use prometeu_hal::memcard::{MemcardIoError, MemcardStorage};
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
pub const SLOT_COUNT: usize = 64;
|
|
pub const BLOCK_COUNT: usize = 68;
|
|
pub const SLOT_BYTES: usize = 65_536;
|
|
pub const PAGE_BYTES: usize = 4096;
|
|
pub const CATALOG_BYTES: usize = 131_072;
|
|
pub const ICON_BYTES: usize = 262_144;
|
|
pub const CATALOG_OFFSETS: [u64; 2] = [16_384, 409_600];
|
|
pub const ICON_OFFSETS: [u64; 2] = [147_456, 540_672];
|
|
pub const MAP_OFFSETS: [u64; 2] = [8192, 12_288];
|
|
pub const DATA_OFFSET: u64 = 802_816;
|
|
pub const IMAGE_BYTES: u64 = DATA_OFFSET + (BLOCK_COUNT * SLOT_BYTES) as u64;
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum Error {
|
|
Io(MemcardIoError),
|
|
Corrupt,
|
|
Unsupported,
|
|
NoSpace,
|
|
InvalidRange,
|
|
CounterExhausted,
|
|
ReadOnly,
|
|
Indeterminate,
|
|
Busy,
|
|
Canceled,
|
|
OutOfMemory,
|
|
AccessDenied,
|
|
InvalidState,
|
|
}
|
|
impl From<MemcardIoError> for Error {
|
|
fn from(e: MemcardIoError) -> Self {
|
|
Self::Io(e)
|
|
}
|
|
}
|
|
pub type Result<T> = std::result::Result<T, Error>;
|
|
|
|
pub fn crc32c(bytes: &[u8]) -> u32 {
|
|
crc_extend(!0, bytes) ^ !0
|
|
}
|
|
pub fn crc_extend(mut crc: u32, bytes: &[u8]) -> u32 {
|
|
for &byte in bytes {
|
|
crc ^= byte as u32;
|
|
for _ in 0..8 {
|
|
crc = (crc >> 1) ^ (0x82f6_3b78 & 0u32.wrapping_sub(crc & 1));
|
|
}
|
|
}
|
|
crc
|
|
}
|
|
fn u32_at(b: &[u8], p: usize) -> u32 {
|
|
u32::from_le_bytes(b[p..p + 4].try_into().unwrap())
|
|
}
|
|
fn u64_at(b: &[u8], p: usize) -> u64 {
|
|
u64::from_le_bytes(b[p..p + 8].try_into().unwrap())
|
|
}
|
|
fn put32(b: &mut [u8], p: usize, n: u32) {
|
|
b[p..p + 4].copy_from_slice(&n.to_le_bytes());
|
|
}
|
|
fn put64(b: &mut [u8], p: usize, n: u64) {
|
|
b[p..p + 8].copy_from_slice(&n.to_le_bytes());
|
|
}
|
|
fn zero(b: &[u8]) -> Result<()> {
|
|
if b.iter().any(|&v| v != 0) { Err(Error::Corrupt) } else { Ok(()) }
|
|
}
|
|
fn page_crc(b: &[u8; PAGE_BYTES]) -> Result<()> {
|
|
if crc32c(&b[..4092]) != u32_at(b, 4092) {
|
|
return Err(Error::Corrupt);
|
|
}
|
|
Ok(())
|
|
}
|
|
fn seal(b: &mut [u8; PAGE_BYTES]) {
|
|
let crc = crc32c(&b[..4092]);
|
|
put32(b, 4092, crc);
|
|
}
|
|
|
|
pub fn identity_page(id: [u8; 16]) -> [u8; PAGE_BYTES] {
|
|
let mut b = [0; PAGE_BYTES];
|
|
b[..8].copy_from_slice(b"PMCARD1\0");
|
|
put32(&mut b, 8, 1);
|
|
put32(&mut b, 12, IMAGE_BYTES as u32);
|
|
b[16..32].copy_from_slice(&id);
|
|
seal(&mut b);
|
|
b
|
|
}
|
|
pub fn decode_identity(b: &[u8; PAGE_BYTES]) -> Result<[u8; 16]> {
|
|
if &b[..8] != b"PMCARD1\0" || u32_at(b, 8) != 1 {
|
|
return Err(Error::Unsupported);
|
|
}
|
|
page_crc(b)?;
|
|
if u32_at(b, 12) != IMAGE_BYTES as u32 {
|
|
return Err(Error::Corrupt);
|
|
}
|
|
zero(&b[32..4092])?;
|
|
Ok(b[16..32].try_into().unwrap())
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Icon {
|
|
pub offset: u32,
|
|
pub frames: u8,
|
|
pub duration: u16,
|
|
pub crc32c: u32,
|
|
}
|
|
impl Icon {
|
|
pub fn length(&self) -> Result<usize> {
|
|
if !(1..=4).contains(&self.frames)
|
|
|| self.duration == 0
|
|
|| (self.frames == 1 && self.duration != 1)
|
|
{
|
|
return Err(Error::Corrupt);
|
|
}
|
|
Ok(48 + 512 * self.frames as usize)
|
|
}
|
|
}
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Game {
|
|
pub app_id: u32,
|
|
pub title: String,
|
|
#[serde(rename = "dataFormatVersion")]
|
|
pub data_format_version: u32,
|
|
pub created_at: u64,
|
|
pub slots: Vec<u8>,
|
|
pub icon: Icon,
|
|
}
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Catalog {
|
|
#[serde(rename = "metadataVersion")]
|
|
pub metadata_version: u32,
|
|
pub games: Vec<Game>,
|
|
}
|
|
impl Default for Catalog {
|
|
fn default() -> Self {
|
|
Self { metadata_version: 1, games: Vec::new() }
|
|
}
|
|
}
|
|
impl Catalog {
|
|
pub fn validate(&self, icons_used: usize) -> Result<[bool; SLOT_COUNT]> {
|
|
if self.metadata_version != 1 || self.games.len() > 64 || icons_used > ICON_BYTES {
|
|
return Err(Error::Corrupt);
|
|
}
|
|
let mut assigned = [false; SLOT_COUNT];
|
|
let mut spans = Vec::with_capacity(64);
|
|
for (index, g) in self.games.iter().enumerate() {
|
|
if g.title.trim().is_empty()
|
|
|| g.title.len() > 128
|
|
|| g.slots.is_empty()
|
|
|| g.slots.len() > 64
|
|
|| self.games[..index].iter().any(|prior| prior.app_id == g.app_id)
|
|
{
|
|
return Err(Error::Corrupt);
|
|
}
|
|
for &slot in &g.slots {
|
|
let used = assigned.get_mut(slot as usize).ok_or(Error::Corrupt)?;
|
|
if *used {
|
|
return Err(Error::Corrupt);
|
|
}
|
|
*used = true;
|
|
}
|
|
let start = g.icon.offset as usize;
|
|
let end = start.checked_add(g.icon.length()?).ok_or(Error::Corrupt)?;
|
|
if end > icons_used || spans.iter().any(|&(a, b)| start < b && a < end) {
|
|
return Err(Error::Corrupt);
|
|
}
|
|
spans.push((start, end));
|
|
}
|
|
Ok(assigned)
|
|
}
|
|
pub fn encode(&self, icons_used: usize) -> Result<Vec<u8>> {
|
|
self.validate(icons_used)?;
|
|
let b = serde_json::to_vec(self).map_err(|_| Error::Corrupt)?;
|
|
if b.len() > CATALOG_BYTES {
|
|
return Err(Error::NoSpace);
|
|
}
|
|
Ok(b)
|
|
}
|
|
pub fn decode(b: &[u8], icons_used: usize) -> Result<Self> {
|
|
if b.len() > CATALOG_BYTES {
|
|
return Err(Error::Corrupt);
|
|
}
|
|
// Bound nesting before serde; strings (including escaped quotes) do not count.
|
|
let (mut depth, mut quoted, mut escaped) = (0u8, false, false);
|
|
for &v in b {
|
|
if quoted {
|
|
if escaped {
|
|
escaped = false;
|
|
} else if v == b'\\' {
|
|
escaped = true;
|
|
} else if v == b'"' {
|
|
quoted = false;
|
|
}
|
|
} else {
|
|
match v {
|
|
b'"' => quoted = true,
|
|
b'[' | b'{' => {
|
|
depth = depth.checked_add(1).ok_or(Error::Corrupt)?;
|
|
if depth > 8 {
|
|
return Err(Error::Corrupt);
|
|
}
|
|
}
|
|
b']' | b'}' => depth = depth.checked_sub(1).ok_or(Error::Corrupt)?,
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
let catalog: Self = serde_json::from_slice(b).map_err(|_| Error::Corrupt)?;
|
|
catalog.validate(icons_used)?;
|
|
Ok(catalog)
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
|
pub struct Slot {
|
|
pub assigned: bool,
|
|
pub block: Option<u8>,
|
|
pub used: u32,
|
|
pub generation: u64,
|
|
pub update_at: u64,
|
|
pub crc: u32,
|
|
}
|
|
impl Slot {
|
|
fn validate(&self) -> Result<()> {
|
|
if !self.assigned && *self != Self::default() {
|
|
return Err(Error::Corrupt);
|
|
}
|
|
if self.generation == 0 && (self.update_at != 0 || self.block.is_some()) {
|
|
return Err(Error::Corrupt);
|
|
}
|
|
match self.block {
|
|
Some(id)
|
|
if id as usize >= BLOCK_COUNT
|
|
|| self.used == 0
|
|
|| self.used as usize > SLOT_BYTES =>
|
|
{
|
|
Err(Error::Corrupt)
|
|
}
|
|
None if self.used != 0 || self.crc != 0 => Err(Error::Corrupt),
|
|
_ => Ok(()),
|
|
}
|
|
}
|
|
}
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct Map {
|
|
pub card_id: [u8; 16],
|
|
pub sequence: u64,
|
|
pub public_copy: usize,
|
|
pub catalog_len: u32,
|
|
pub catalog_crc: u32,
|
|
pub icons_len: u32,
|
|
pub icons_crc: u32,
|
|
pub order: [u8; BLOCK_COUNT],
|
|
pub quarantine: [bool; BLOCK_COUNT],
|
|
pub slots: [Slot; SLOT_COUNT],
|
|
}
|
|
impl Map {
|
|
pub fn new(card_id: [u8; 16]) -> Self {
|
|
Self {
|
|
card_id,
|
|
sequence: 1,
|
|
public_copy: 0,
|
|
catalog_len: 0,
|
|
catalog_crc: 0,
|
|
icons_len: 0,
|
|
icons_crc: 0,
|
|
order: std::array::from_fn(|i| i as u8),
|
|
quarantine: [false; BLOCK_COUNT],
|
|
slots: [Slot::default(); SLOT_COUNT],
|
|
}
|
|
}
|
|
pub fn encode(&self) -> Result<[u8; PAGE_BYTES]> {
|
|
if self.sequence == 0
|
|
|| self.public_copy > 1
|
|
|| self.catalog_len as usize > CATALOG_BYTES
|
|
|| self.icons_len as usize > ICON_BYTES
|
|
{
|
|
return Err(Error::Corrupt);
|
|
}
|
|
let mut seen = [false; BLOCK_COUNT];
|
|
for &id in &self.order {
|
|
let v = seen.get_mut(id as usize).ok_or(Error::Corrupt)?;
|
|
if *v {
|
|
return Err(Error::Corrupt);
|
|
}
|
|
*v = true;
|
|
}
|
|
let mut owned = [false; BLOCK_COUNT];
|
|
let mut b = [0; PAGE_BYTES];
|
|
b[..8].copy_from_slice(b"PMMAP1\0\0");
|
|
put64(&mut b, 8, self.sequence);
|
|
put32(&mut b, 16, self.public_copy as u32);
|
|
put32(&mut b, 20, self.catalog_len);
|
|
put32(&mut b, 24, self.catalog_crc);
|
|
put32(&mut b, 28, self.icons_len);
|
|
put32(&mut b, 32, self.icons_crc);
|
|
b[36..52].copy_from_slice(&self.card_id);
|
|
b[64..132].copy_from_slice(&self.order);
|
|
for i in 0..BLOCK_COUNT {
|
|
b[132 + i] = self.quarantine[i] as u8;
|
|
}
|
|
for (i, s) in self.slots.iter().enumerate() {
|
|
s.validate()?;
|
|
if let Some(id) = s.block {
|
|
if owned[id as usize] || self.quarantine[id as usize] {
|
|
return Err(Error::Corrupt);
|
|
}
|
|
owned[id as usize] = true;
|
|
}
|
|
let p = 256 + i * 40;
|
|
b[p] = if !s.assigned {
|
|
0
|
|
} else if s.block.is_none() {
|
|
1
|
|
} else {
|
|
2
|
|
};
|
|
b[p + 1] = s.block.unwrap_or(255);
|
|
put32(&mut b, p + 4, s.used);
|
|
put64(&mut b, p + 8, s.generation);
|
|
put64(&mut b, p + 16, s.update_at);
|
|
put32(&mut b, p + 24, s.crc);
|
|
}
|
|
seal(&mut b);
|
|
Ok(b)
|
|
}
|
|
pub fn decode(b: &[u8; PAGE_BYTES], card_id: [u8; 16]) -> Result<Self> {
|
|
page_crc(b)?;
|
|
if &b[..8] != b"PMMAP1\0\0" || b[36..52] != card_id {
|
|
return Err(Error::Corrupt);
|
|
}
|
|
zero(&b[52..64])?;
|
|
zero(&b[200..256])?;
|
|
zero(&b[2816..4092])?;
|
|
let mut m = Self::new(card_id);
|
|
m.sequence = u64_at(b, 8);
|
|
m.public_copy = u32_at(b, 16) as usize;
|
|
m.catalog_len = u32_at(b, 20);
|
|
m.catalog_crc = u32_at(b, 24);
|
|
m.icons_len = u32_at(b, 28);
|
|
m.icons_crc = u32_at(b, 32);
|
|
m.order.copy_from_slice(&b[64..132]);
|
|
for i in 0..BLOCK_COUNT {
|
|
if b[132 + i] > 1 {
|
|
return Err(Error::Corrupt);
|
|
}
|
|
m.quarantine[i] = b[132 + i] != 0;
|
|
}
|
|
for i in 0..SLOT_COUNT {
|
|
let p = 256 + i * 40;
|
|
zero(&b[p + 2..p + 4])?;
|
|
zero(&b[p + 28..p + 40])?;
|
|
if b[p] > 2 || (b[p] != 2 && b[p + 1] != 255) || (b[p] == 2 && b[p + 1] == 255) {
|
|
return Err(Error::Corrupt);
|
|
}
|
|
m.slots[i] = Slot {
|
|
assigned: b[p] != 0,
|
|
block: if b[p] == 2 { Some(b[p + 1]) } else { None },
|
|
used: u32_at(b, p + 4),
|
|
generation: u64_at(b, p + 8),
|
|
update_at: u64_at(b, p + 16),
|
|
crc: u32_at(b, p + 24),
|
|
};
|
|
}
|
|
if m.encode()? != *b {
|
|
return Err(Error::Corrupt);
|
|
}
|
|
Ok(m)
|
|
}
|
|
pub fn game_update_at(&self, game: &Game) -> Option<u64> {
|
|
game.slots
|
|
.iter()
|
|
.filter_map(|&i| self.slots.get(i as usize))
|
|
.filter(|s| s.generation > 0)
|
|
.map(|s| s.update_at)
|
|
.max()
|
|
}
|
|
}
|
|
|
|
pub fn read_region(io: &mut dyn MemcardStorage, offset: u64, out: &mut [u8]) -> Result<()> {
|
|
for (i, b) in out.chunks_mut(SLOT_BYTES).enumerate() {
|
|
io.read_at(offset + (i * SLOT_BYTES) as u64, b)?;
|
|
}
|
|
Ok(())
|
|
}
|
|
pub fn write_region(io: &mut dyn MemcardStorage, offset: u64, bytes: &[u8]) -> Result<()> {
|
|
for (i, b) in bytes.chunks(SLOT_BYTES).enumerate() {
|
|
io.write_at(offset + (i * SLOT_BYTES) as u64, b)?;
|
|
}
|
|
Ok(())
|
|
}
|
|
pub fn block_offset(id: u8) -> Result<u64> {
|
|
if id as usize >= BLOCK_COUNT {
|
|
return Err(Error::InvalidRange);
|
|
}
|
|
Ok(DATA_OFFSET + id as u64 * SLOT_BYTES as u64)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
#[test]
|
|
fn crc_vectors_and_identity_golden() {
|
|
assert_eq!(crc32c(b""), 0);
|
|
assert_eq!(crc32c(b"123456789"), 0xe3069283);
|
|
let p = identity_page([7; 16]);
|
|
assert_eq!(&p[..16], b"PMCARD1\0\x01\0\0\0\0\x40\x50\0");
|
|
assert_eq!(decode_identity(&p), Ok([7; 16]));
|
|
}
|
|
#[test]
|
|
fn descriptor_roundtrip_rejects_reserved_and_alias() {
|
|
let mut m = Map::new([1; 16]);
|
|
m.slots[2] =
|
|
Slot { assigned: true, block: Some(3), used: 7, generation: 1, update_at: 0, crc: 12 };
|
|
assert_eq!(Map::decode(&m.encode().unwrap(), [1; 16]), Ok(m.clone()));
|
|
m.slots[4] = m.slots[2];
|
|
assert_eq!(m.encode(), Err(Error::Corrupt));
|
|
let mut b = Map::new([1; 16]).encode().unwrap();
|
|
b[3000] = 1;
|
|
seal(&mut b);
|
|
assert_eq!(Map::decode(&b, [1; 16]), Err(Error::Corrupt));
|
|
}
|
|
#[test]
|
|
fn closed_catalog_rejects_duplicates_and_deep_input() {
|
|
for s in [
|
|
r#"{"metadataVersion":1,"metadataVersion":1,"games":[]}"#,
|
|
r#"{"metadataVersion":1,"games":[],"extra":0}"#,
|
|
r#"[[[[[[[[[]]]]]]]]]"#,
|
|
] {
|
|
assert_eq!(Catalog::decode(s.as_bytes(), 0), Err(Error::Corrupt));
|
|
}
|
|
}
|
|
#[test]
|
|
fn maximum_catalog_and_icons_fit_and_preserve_uint64() {
|
|
let mut c = Catalog::default();
|
|
for i in 0..64 {
|
|
c.games.push(Game {
|
|
app_id: u32::MAX - i,
|
|
title: "\u{1}".repeat(127) + "a",
|
|
data_format_version: u32::MAX,
|
|
created_at: u64::MAX,
|
|
slots: vec![i as u8],
|
|
icon: Icon { offset: i * 2096, frames: 4, duration: u16::MAX, crc32c: u32::MAX },
|
|
});
|
|
}
|
|
let b = c.encode(64 * 2096).unwrap();
|
|
assert!(b.len() < CATALOG_BYTES);
|
|
assert_eq!(Catalog::decode(&b, 64 * 2096), Ok(c));
|
|
}
|
|
}
|