# SPDX-License-Identifier: MIT """The Game Pak ROM image and what the ROM chip answers on the cartridge bus. The cartridge bus carries 16-bit data multiplexed with the low 16 address bits; the ROM chip latches the address on a non-sequential access and increments it on each sequential one (GBATEK §GBA Cartridge ROM; DOC; docs/cartridge.md "The Game Pak bus"). The latch itself is kept by the bus (gba_python.bus), which decides N and S; this module only answers "the halfword at halfword index i". """ from __future__ import annotations from pathlib import Path from gba_python.files import read_image MAX_ROM = 0x2000000 # 32 MB (GBATEK §GBA Memory Map; DOC) class GamePakROM: """The ROM image as halfwords, with what reads beyond the chip return.""" def __init__(self, data: bytes) -> None: if len(data) > MAX_ROM: raise ValueError(f"a Game Pak ROM is at most 32 MB, this is {len(data)} bytes") if len(data) & 1: data = data + b"\x00" self.data = bytes(data) self.size = len(self.data) self.title = self.data[0xA0:0xAC].rstrip(b"\x00").decode("ascii", "replace") self.code = self.data[0xAC:0xB0].decode("ascii", "replace") @classmethod def from_path(cls, path: str | Path) -> GamePakROM: return cls(read_image(path, (".gba", ".agb", ".bin", ".mb"))) def halfword(self, index: int) -> int: """The halfword at halfword index ``index`` (0 to 0xFFFFFF) of the 32 MB space. Beyond the chip the data lines still hold the address the chip was given, so the area reads as "incrementing 16bit values (Address/2 AND FFFFh)" (GBATEK §GBA Unpredictable Things, said of an empty slot; DOC). The mGBA suite expects the same past the end of its own ROM ("ROM out-of-bounds load"; TEST ROM); jsmolka's unsafe/README reports otherwise from a flash cart (U-MEM-3, flagged). """ offset = index << 1 if offset < self.size: data = self.data return data[offset] | data[offset + 1] << 8 return index & 0xFFFF