use std::{
borrow::Cow,
ffi::CStr,
fmt::{Debug, Display, Formatter},
io,
io::{BufRead, Seek},
mem::size_of,
str::from_utf8,
};
use dyn_clone::DynClone;
use zerocopy::{big_endian::*, FromBytes, Immutable, IntoBytes, KnownLayout};
use crate::{io::MagicBytes, static_assert, Result};
pub(crate) mod fst;
pub(crate) mod gcn;
pub(crate) mod hashes;
pub(crate) mod reader;
pub(crate) mod streams;
pub(crate) mod wii;
pub use fst::{Fst, Node, NodeKind};
pub use streams::{FileStream, OwnedFileStream, WindowedStream};
pub use wii::{SignedHeader, Ticket, TicketLimit, TmdHeader, REGION_SIZE};
pub const SECTOR_SIZE: usize = 0x8000;
pub const WII_MAGIC: MagicBytes = [0x5D, 0x1C, 0x9E, 0xA3];
pub const GCN_MAGIC: MagicBytes = [0xC2, 0x33, 0x9F, 0x3D];
#[derive(Clone, Debug, PartialEq, FromBytes, IntoBytes, Immutable, KnownLayout)]
#[repr(C, align(4))]
pub struct DiscHeader {
pub game_id: [u8; 6],
pub disc_num: u8,
pub disc_version: u8,
pub audio_streaming: u8,
pub audio_stream_buf_size: u8,
_pad1: [u8; 14],
pub wii_magic: MagicBytes,
pub gcn_magic: MagicBytes,
pub game_title: [u8; 64],
pub no_partition_hashes: u8,
pub no_partition_encryption: u8,
_pad2: [u8; 926],
}
static_assert!(size_of::<DiscHeader>() == 0x400);
impl DiscHeader {
#[inline]
pub fn game_id_str(&self) -> &str { from_utf8(&self.game_id).unwrap_or("[invalid]") }
#[inline]
pub fn game_title_str(&self) -> &str {
CStr::from_bytes_until_nul(&self.game_title)
.ok()
.and_then(|c| c.to_str().ok())
.unwrap_or("[invalid]")
}
#[inline]
pub fn is_gamecube(&self) -> bool { self.gcn_magic == GCN_MAGIC }
#[inline]
pub fn is_wii(&self) -> bool { self.wii_magic == WII_MAGIC }
}
#[derive(Clone, Debug, PartialEq, FromBytes, IntoBytes, Immutable, KnownLayout)]
#[repr(C, align(4))]
pub struct PartitionHeader {
pub debug_mon_offset: U32,
pub debug_load_address: U32,
_pad1: [u8; 0x18],
pub dol_offset: U32,
pub fst_offset: U32,
pub fst_size: U32,
pub fst_max_size: U32,
pub fst_memory_address: U32,
pub user_offset: U32,
pub user_size: U32,
_pad2: [u8; 4],
}
static_assert!(size_of::<PartitionHeader>() == 0x40);
impl PartitionHeader {
#[inline]
pub fn dol_offset(&self, is_wii: bool) -> u64 {
if is_wii {
self.dol_offset.get() as u64 * 4
} else {
self.dol_offset.get() as u64
}
}
#[inline]
pub fn fst_offset(&self, is_wii: bool) -> u64 {
if is_wii {
self.fst_offset.get() as u64 * 4
} else {
self.fst_offset.get() as u64
}
}
#[inline]
pub fn fst_size(&self, is_wii: bool) -> u64 {
if is_wii {
self.fst_size.get() as u64 * 4
} else {
self.fst_size.get() as u64
}
}
#[inline]
pub fn fst_max_size(&self, is_wii: bool) -> u64 {
if is_wii {
self.fst_max_size.get() as u64 * 4
} else {
self.fst_max_size.get() as u64
}
}
}
#[derive(Debug, PartialEq, Clone, FromBytes, IntoBytes, Immutable, KnownLayout)]
#[repr(C, align(4))]
pub struct ApploaderHeader {
pub date: [u8; 16],
pub entry_point: U32,
pub size: U32,
pub trailer_size: U32,
_pad: [u8; 4],
}
impl ApploaderHeader {
#[inline]
pub fn date_str(&self) -> Option<&str> {
CStr::from_bytes_until_nul(&self.date).ok().and_then(|c| c.to_str().ok())
}
}
pub const DOL_MAX_TEXT_SECTIONS: usize = 7;
pub const DOL_MAX_DATA_SECTIONS: usize = 11;
#[derive(Debug, Clone, FromBytes, Immutable, KnownLayout)]
pub struct DolHeader {
pub text_offs: [U32; DOL_MAX_TEXT_SECTIONS],
pub data_offs: [U32; DOL_MAX_DATA_SECTIONS],
pub text_addrs: [U32; DOL_MAX_TEXT_SECTIONS],
pub data_addrs: [U32; DOL_MAX_DATA_SECTIONS],
pub text_sizes: [U32; DOL_MAX_TEXT_SECTIONS],
pub data_sizes: [U32; DOL_MAX_DATA_SECTIONS],
pub bss_addr: U32,
pub bss_size: U32,
pub entry_point: U32,
_pad: [u8; 0x1C],
}
static_assert!(size_of::<DolHeader>() == 0x100);
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum PartitionKind {
Data,
Update,
Channel,
Other(u32),
}
impl Display for PartitionKind {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::Data => write!(f, "Data"),
Self::Update => write!(f, "Update"),
Self::Channel => write!(f, "Channel"),
Self::Other(v) => {
let bytes = v.to_be_bytes();
write!(f, "Other ({:08X}, {})", v, String::from_utf8_lossy(&bytes))
}
}
}
}
impl PartitionKind {
#[inline]
pub fn dir_name(&self) -> Cow<str> {
match self {
Self::Data => Cow::Borrowed("DATA"),
Self::Update => Cow::Borrowed("UPDATE"),
Self::Channel => Cow::Borrowed("CHANNEL"),
Self::Other(v) => {
let bytes = v.to_be_bytes();
Cow::Owned(format!("P-{}", String::from_utf8_lossy(&bytes)))
}
}
}
}
impl From<u32> for PartitionKind {
#[inline]
fn from(v: u32) -> Self {
match v {
0 => Self::Data,
1 => Self::Update,
2 => Self::Channel,
v => Self::Other(v),
}
}
}
pub trait PartitionBase: DynClone + BufRead + Seek + Send + Sync {
fn meta(&mut self) -> Result<Box<PartitionMeta>>;
fn open_file(&mut self, node: Node) -> io::Result<FileStream>;
fn into_open_file(self: Box<Self>, node: Node) -> io::Result<OwnedFileStream>;
}
dyn_clone::clone_trait_object!(PartitionBase);
pub const BOOT_SIZE: usize = size_of::<DiscHeader>() + size_of::<PartitionHeader>();
pub const BI2_SIZE: usize = 0x2000;
#[derive(Clone, Debug)]
pub struct PartitionMeta {
pub raw_boot: Box<[u8; BOOT_SIZE]>,
pub raw_bi2: Box<[u8; BI2_SIZE]>,
pub raw_apploader: Box<[u8]>,
pub raw_dol: Box<[u8]>,
pub raw_fst: Box<[u8]>,
pub raw_ticket: Option<Box<[u8]>>,
pub raw_tmd: Option<Box<[u8]>>,
pub raw_cert_chain: Option<Box<[u8]>>,
pub raw_h3_table: Option<Box<[u8]>>,
}
impl PartitionMeta {
#[inline]
pub fn header(&self) -> &DiscHeader {
DiscHeader::ref_from_bytes(&self.raw_boot[..size_of::<DiscHeader>()]).unwrap()
}
#[inline]
pub fn partition_header(&self) -> &PartitionHeader {
PartitionHeader::ref_from_bytes(&self.raw_boot[size_of::<DiscHeader>()..]).unwrap()
}
#[inline]
pub fn apploader_header(&self) -> &ApploaderHeader {
ApploaderHeader::ref_from_prefix(&self.raw_apploader).unwrap().0
}
#[inline]
pub fn fst(&self) -> Result<Fst, &'static str> { Fst::new(&self.raw_fst) }
#[inline]
pub fn dol_header(&self) -> &DolHeader { DolHeader::ref_from_prefix(&self.raw_dol).unwrap().0 }
#[inline]
pub fn ticket(&self) -> Option<&Ticket> {
self.raw_ticket.as_ref().and_then(|v| Ticket::ref_from_bytes(v).ok())
}
#[inline]
pub fn tmd_header(&self) -> Option<&TmdHeader> {
self.raw_tmd.as_ref().and_then(|v| TmdHeader::ref_from_prefix(v).ok().map(|(v, _)| v))
}
}
pub const MINI_DVD_SIZE: u64 = 1_459_978_240;
pub const SL_DVD_SIZE: u64 = 4_699_979_776;
pub const DL_DVD_SIZE: u64 = 8_511_160_320;