Skip to content

Commit

Permalink
Cartridge: fixed crash on broken rom files if we can fix it
Browse files Browse the repository at this point in the history
This hasn't happened before, but the mbc1 test rom in gbmicrotest is not correct. We can gracefully fix it.
  • Loading branch information
Amjad50 committed Mar 14, 2024
1 parent 3a051bc commit fa3c8cc
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
21 changes: 19 additions & 2 deletions mizu-core/src/cartridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,10 +281,27 @@ impl Cartridge {
return Err(CartridgeError::InvalidRomSizeIndex(data[0x148]));
}

let rom_size = 0x8000 << num_rom_banks;
let mut rom_size = 0x8000 << num_rom_banks;

if rom_size != data.len() {
return Err(CartridgeError::InvalidRomSize(rom_size));
// try to fix it, sometimes the rom will have `0` as the num_rom_banks
let mut fixed = false;
if rom_size < data.len() && data.len() % rom_size == 0 {
let div = data.len() / rom_size;
if div.is_power_of_two() && div.ilog2() < 8 {
println!(
"WARN: invalid cartridge header. Using rom size {:X} instead of {:X}",
data.len(),
rom_size,
);
rom_size = data.len();
fixed = true;
}
}

if !fixed {
return Err(CartridgeError::InvalidRomSize(rom_size));
}
}

let ram_size = match data[0x149] {
Expand Down
2 changes: 1 addition & 1 deletion mizu-core/src/tests/gbmicrotest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ gbmicrotest_tests!(
// lyc2_int_halt_a,
lyc2_int_halt_b,
mbc1_ram_banks,
// mbc1_rom_banks,
mbc1_rom_banks,
// minimal,
// mode2_stat_int_to_oam_unlock,
// oam_int_halt_a,
Expand Down

0 comments on commit fa3c8cc

Please sign in to comment.