"""Write or check the hardware-required GBA cartridge header (stdlib only).""" import argparse from pathlib import Path # Standard GBA boot-logo bytes, required by the console's cartridge check. # These are hardware header data, not game graphics. LOGO = bytes.fromhex( "24ffae51699aa2213d84820a84e409ad11248b98c0817f21a352be199309ce20" "10464a4af82731ec58c7e83382e3cebf85f4df94ce4b09c194568ac01372a7fc" "9f844d73a3ca9a615897a327fc039876231dc7610304ae56bf38840040a70efd" "ff52fe036f9530f197fbc08560d68025a963be03014e38e2f9a234ffbb3e0344" "780090cb88113a9465c07c6387f03cafd625e48b380aac7221d4f807" ) def verify(rom): if len(rom) < 192 or len(rom) > 32 * 1024 * 1024: raise ValueError("ROM size is outside the GBA cartridge range") if rom[3] != 0xEA: raise ValueError("Missing ARM entry branch") displacement = int.from_bytes(rom[:3], "little") if displacement & 0x800000: displacement -= 0x1000000 entry = 8 + displacement * 4 if not 192 <= entry < len(rom): raise ValueError("Entry branch does not point to game code") if rom[4:160] != LOGO or rom[178] != 0x96: raise ValueError("Invalid hardware header") if (sum(rom[160:190]) + 0x19) & 0xFF: raise ValueError("Invalid header checksum") if len(rom) & (len(rom) - 1): raise ValueError("ROM is not padded to a power of two") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--check", action="store_true") parser.add_argument("rom", type=Path) args = parser.parse_args() rom = bytearray(args.rom.read_bytes()) if not args.check: if len(rom) < 192: raise ValueError("Missing cartridge header space") rom[4:160] = LOGO rom[160:172] = b"FIRSTQUEST".ljust(12, b"\0") rom[172:176] = b"FQ01" rom[176:178] = b"00" rom[178:189] = bytes([0x96]) + bytes(10) rom[189] = (-0x19 - sum(rom[160:189])) & 0xFF rom[190:192] = b"\0\0" size = max(32768, 1 << (len(rom) - 1).bit_length()) rom.extend(b"\xff" * (size - len(rom))) verify(rom) args.rom.write_bytes(rom) else: verify(rom) print(f"ROM header OK: {args.rom} ({len(rom):,} bytes)") if __name__ == "__main__": main()