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
//! A library for working with GCM/ISO files (raw bit-for-bit disk images) for the Nintendo
//! GameCube.
//!
//! Features:
//!
//! * GCM parser
//!     * Disk metadata (game_id, internal name, etc.)
//!     * Offsets to various sections of the GCM
//! * GameCube filesystem parser
//!     * Raw access to filesystem structures
//!     * Iterate over directories in a high-level manner
//!     * Information about the storage of files, allowing extraction
//! * DOL executable parser
//!     * The main executable for the game
//!     * Allows for extraction or loading into memory
//!     * Supports parsing extracted DOL files as well
//! * Apploader parser
//!     * The second stage loader for the game
//!     * Primarily only useful for hardware accuracy purposes
//!
//! ```
//! use gc_gcm::GcmFile;
//!
//! let iso = GcmFile::open("melee.iso").unwrap();
//!
//! println!("Name of game: {:?}", iso.internal_name);
//! println!("Size of executable: {:x?}", iso.dol.raw_data.len());
//! println!(
//!     "Number of files: {}",
//!     iso.filesystem.files
//!         .iter()
//!         .filter(|entry| matches!(entry, gc_gcm::FsNode::File { .. }))
//!         .count()
//! );
//! ```
//!
//! Output:
//!
//! ```text
//! Name of game: "Super Smash Bros Melee"
//! Size of executable: 4385e0
//! Number of files: 1209
//! ```

#![cfg_attr(feature = "no_std", no_std)]
use binread::{derive_binread, BinRead, BinReaderExt, NullString, io::{self, SeekFrom}};
use binread::file_ptr::{FilePtr, FilePtr32, IntoSeekFrom};
use binread::helpers::read_bytes;
use core::fmt;

#[cfg(feature = "no_std")]
mod std;

#[cfg(feature = "no_std")]
use crate::std::{string::String, vec::Vec};

/// Top-level view of a GCM file
#[derive(BinRead, Debug)]
#[br(big)]
struct GcmTop (
    // magic value at 0x1c
    #[br(seek_before = SeekFrom::Start(0x1c))]
    pub GcmFile,
);

/// A 6-character ID for a game
#[derive(BinRead)]
pub struct GameId(pub [u8; 6]);

/// A parsed GCM/ISO file
#[derive_binread]
#[derive(Debug)]
#[br(magic = 0xc2339f3d_u32)]
pub struct GcmFile {
    #[br(seek_before = SeekFrom::Start(0))]
    pub game_id: GameId,
    pub disc_number: u8,
    pub revision: u8,
    
    #[br(seek_before = SeekFrom::Start(0x20))]
    #[br(map = NullString::into_string)]
    pub internal_name: String,
    
    // just gonna skip debug stuff

    #[br(seek_before = SeekFrom::Start(0x420))]
    pub dol_offset: u32,

    #[br(seek_before = SeekFrom::Start(0x420))]
    #[br(parse_with = FilePtr32::parse)]
    pub dol: DolFile,
    
    fs_offset: u32,
    fs_size: u32,
    max_fs_size: u32,
    
    #[br(seek_before = SeekFrom::Start(fs_offset as u64))]
    #[br(args(fs_offset, fs_size))]
    pub filesystem: FileSystem,

    // raw data

    #[br(seek_before = SeekFrom::Start(0))]
    #[br(parse_with = read_bytes)]
    #[br(count = 0x440)]
    pub boot_bin: Vec<u8>,

    #[br(seek_before = SeekFrom::Start(0x440))]
    #[br(parse_with = read_bytes)]
    #[br(count = 0x2000)]
    pub bi2_bin: Vec<u8>,

    #[br(seek_before = SeekFrom::Start(0x2440))]
    pub apploader_header: ApploaderHeader,

    #[br(seek_before = SeekFrom::Start(0x2440))]
    #[br(parse_with = read_bytes)]
    #[br(count = apploader_header.size + apploader_header.trailer_size + ApploaderHeader::SIZE)]
    pub apploader: Vec<u8>,

    #[br(seek_before = SeekFrom::Start(fs_offset as u64))]
    #[br(parse_with = read_bytes)]
    #[br(count = fs_size)]
    pub fst_bytes: Vec<u8>,
}

#[derive(BinRead, Debug)]
pub struct ApploaderHeader {
    date: [u8; 0x10],
    entrypoint_ptr: u32,
    size: u32,
    trailer_size: u32,
    padding: [u8; 4],
}

impl ApploaderHeader {
    const SIZE: u32 = 0x20;
}

/// The parsed GCM filesystem
#[derive(BinRead, Debug)]
#[br(import(offset: u32, size: u32))]
pub struct FileSystem {
    pub root: RootNode,

    #[br(args(
        offset as u64, // root offset
        (offset + (root.total_node_count * FsNode::SIZE)) as u64 // name offset (after all entries)
    ))]
    #[br(count = root.total_node_count - 1)]
    pub files: Vec<FsNode>,
}

/// The root node of the filesystem, under which all the other nodes fall
#[derive(BinRead, Debug)]
#[br(magic = 1u8)]
pub struct RootNode {
    #[br(map = U24::into)]
    pub name_offset: u32,
    pub node_start_index: u32,
    pub total_node_count: u32,
}

type FilePtr24<T> = FilePtr<U24, T>;

/// A given parsed node in the filesystem
#[br(import(root_offset: u64, name_offset: u64))]
#[derive(BinRead, Debug)]
pub enum FsNode {
    #[br(magic = 0u8)]
    File {
        #[br(offset = name_offset)]
        #[br(parse_with = FilePtr24::parse)]
        #[br(map = NullString::into_string)]
        name: String,
        offset: u32,
        size: u32,
    },

    #[br(magic = 1u8)]
    Directory {
        #[br(offset = name_offset)]
        #[br(parse_with = FilePtr24::parse)]
        #[br(map = NullString::into_string)]
        name: String,
        parent_index: u32,
        end_index: u32,
    },
}

impl FsNode {
    const SIZE: u32 = 0xC;
}

#[derive(BinRead, Clone, Copy)]
struct U24([u8; 3]);

impl IntoSeekFrom for U24 {
    fn into_seek_from(self) -> SeekFrom {
        u32::from(self).into_seek_from()
    }
}

impl From<U24> for u32 {
    fn from(U24(x): U24) -> Self {
        u32::from_be_bytes([0, x[0], x[1], x[2]])
    }
}

impl fmt::Debug for GameId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match core::str::from_utf8(&self.0[..]) {
            Ok(id) => fmt::Debug::fmt(id, f),
            Err(_) => write!(f, "GameId({:02x?})", &self.0[..])
        }
    }
}

mod dol;
mod error;
mod dir_listing;
pub use error::GcmError;
pub use dir_listing::*;
pub use dol::*;

impl GcmFile {
    /// Parse a GcmFile from a reader that implements `io::Read` and `io::Seek`
    pub fn from_reader<R>(reader: &mut R) -> Result<Self, GcmError>
        where R: io::Read + io::Seek,
    {
        Ok(reader.read_be::<GcmTop>()?.0)
    }
}

#[cfg(not(feature = "no_std"))]
use ::std::path::Path;

#[cfg(not(feature = "no_std"))]
impl GcmFile {
    /// Open a file from a given bath as a GcmFile.
    pub fn open<P>(path: P) -> Result<Self, GcmError>
        where P: AsRef<Path>,
    {
        let mut reader = ::std::io::BufReader::new(::std::fs::File::open(path)?);
        Ok(reader.read_be::<GcmTop>()?.0)
    }
}