# SPDX-License-Identifier: MIT """Cartridges: the image, its header, and the plain memory maps. DOC: fullsnes "SNES Cartridge ROM Header" (where the header is, its fields, the copier header), "SNES Cart LoROM Mapping" and "SNES Cart HiROM Mapping" (the boards' ROM, mirror and SRAM areas), "ROM Size / Checksum Notes" (odd sizes: the bigger power-of-two part at 0, then the rest mirrored). The header score is this board's own rule (DESIGN, below): each candidate header earns points for what fullsnes says a valid header holds. It is written from fullsnes alone; a census over the licensed set (scripts/count_carts.py) is the check on it (milestone 4). The connector protocol: ``read(address, mdr) -> int`` and ``write(address, value)`` for every access the board does not own; unmapped reads return ``mdr`` (open bus). """ from __future__ import annotations from dataclasses import dataclass LOROM, HIROM, EXHIROM = "lorom", "hirom", "exhirom" _HEADER_AT = {LOROM: 0x7FC0, HIROM: 0xFFC0, EXHIROM: 0x40FFC0} def mirror(offset: int, size: int) -> int: """A ROM offset in the rounded-up space to a byte of a ``size``-byte image. DOC: fullsnes "ROM Size / Checksum Notes": "the bigger half is mapped to address 0, followed by the smaller half, then followed by mirror(s) of the smaller half"; a power-of-two image simply repeats. """ base = 0 while size: p = 1 << (size.bit_length() - 1) if p == size: return base + offset % size offset %= p << 1 if offset < p: return base + offset offset -= p base += p size -= p return 0 @dataclass(frozen=True) class Header: """The fields of an internal header (DOC: fullsnes).""" kind: str offset: int title: str map_mode: int chipset: int rom_size: int ram_size: int country: int checksum: int complement: int reset_vector: int score: int def _names_map(map_mode: int, kind: str) -> bool: """The map mode byte names this map (DOC: fullsnes "FFD5h": low nibble 0 LoROM, 1 HiROM, 2 LoROM+S-DD1, 3 LoROM+SA-1, 5 ExHiROM, A HiROM+SPC7110; bit 4 FastROM; bit 5 always set).""" low = map_mode & 0x0F if map_mode & 0xE0 != 0x20: return False if kind == LOROM: return low in (0, 2, 3) if kind == HIROM: return low in (1, 0xA) return low in (5, 0xA) def _believable(header: Header) -> bool: """A real header names its own map or carries a valid checksum pair.""" return _names_map(header.map_mode, header.kind) or ( header.checksum ^ header.complement == 0xFFFF ) def _score(rom: bytes, kind: str) -> Header | None: """DESIGN (own rule, from fullsnes's field descriptions; HYPOTHESIS until the census): points for each field that looks as fullsnes describes.""" at = _HEADER_AT[kind] if at + 0x40 > len(rom): return None h = rom[at : at + 0x40] map_mode = h[0x15] complement = h[0x1C] | h[0x1D] << 8 checksum = h[0x1E] | h[0x1F] << 8 reset = h[0x3C] | h[0x3D] << 8 score = 0 # The map mode byte (_names_map). if map_mode & 0xE0 == 0x20: score += 2 if _names_map(map_mode, kind): score += 4 if checksum ^ complement == 0xFFFF: score += 4 # The reset vector points into the ROM half of bank 0 (fullsnes: # "valid entrypoints in range 8000h..FFFEh"). if 0x8000 <= reset < 0xFFFF: score += 3 else: score -= 4 if all(0x20 <= c < 0x7F for c in h[0x00:0x15]): score += 1 if 0x07 <= h[0x17] <= 0x0D: score += 1 if h[0x18] <= 0x08: score += 1 if kind == EXHIROM and len(rom) <= 0x400000: return None return Header( kind=kind, offset=at, title=bytes(h[0x00:0x15]).decode("latin-1").rstrip(), map_mode=map_mode, chipset=h[0x16], rom_size=h[0x17], ram_size=h[0x18], country=h[0x19], checksum=checksum, complement=complement, reset_vector=reset, score=score, ) def _starts_up(rom: bytes, header: Header) -> bool: """The reset vector lands on SEI ($78) or CLC ($18) in this map (DESIGN, find_header).""" vector = header.reset_vector if not 0x8000 <= vector < 0xFFFF: return False if header.kind == LOROM: offset = vector - 0x8000 elif header.kind == HIROM: offset = vector else: offset = 0x400000 + vector return offset < len(rom) and rom[offset] in (0x78, 0x18) def find_header(rom: bytes) -> Header: """The best-scoring header; ties go to LoROM, then HiROM (DESIGN). DESIGN (provisional, from the census of 2026-11-23, docs/cartridge.md "Header census"): when no candidate is believable (none names its own map or has a valid checksum pair) the image has no real header, and it is taken as LoROM. The two such images in the licensed set (a burn-in test cartridge and a kiosk demo) are LoROM boards by MAME's software list (CC0) and run only as LoROM; the score alone picked HiROM by one point from stray bytes. DESIGN (provisional, from the full sweep of 2026-11-24, docs/status.md "The full sweep"): the LoROM fallback needs LoROM's reset vector to point into the ROM half of bank 0 (fullsnes: "valid entrypoints in range 8000h..FFFEh"). A prototype whose header is only a title and vectors (Final Fight 3 (USA) (Beta): map mode, sizes and checksum all zero, a HiROM board by MAME's software list) has no LoROM entry point at all, and the fallback ran it from $0480 into a blank screen. DESIGN (provisional, same sweep): a tie in score goes to the candidate whose reset vector lands on SEI or CLC, the first instruction of the usual start-up (SEI; CLC; XCE to leave emulation mode, WDC's datasheet); only then to LoROM. Mortal Kombat II (USA) (Beta) carries a believable developer's header at $7FC0 ("LEINGANG WAS HERE") beside its HiROM one; both score 16, and only the HiROM entry starts SEI, CLD, CLC, XCE. The same test keeps the LoROM fallback from a HiROM-only start-up: Marvel Super Heroes in War of the Gems (USA) (Beta) has no believable header, and only its HiROM vector lands on start-up code. """ best: Header | None = None lorom: Header | None = None for kind in (LOROM, HIROM, EXHIROM): header = _score(rom, kind) if kind == LOROM: lorom = header if header is not None and ( best is None or header.score > best.score or header.score == best.score and _starts_up(rom, header) and not _starts_up(rom, best) ): best = header if best is None: raise ValueError("image too small for a header") if ( lorom is not None and not _believable(best) and not _believable(lorom) and 0x8000 <= lorom.reset_vector < 0xFFFF and (_starts_up(rom, lorom) or not _starts_up(rom, best)) ): return lorom return best class Cartridge: """A plain ROM (+ SRAM) cartridge on the connector.""" def __init__(self, image: bytes, kind: str | None = None) -> None: # DOC: fullsnes: a copier header is present when size mod 1024 = 512. if len(image) % 1024 == 512: image = image[512:] self.rom = bytes(image) self.header = find_header(self.rom) self.kind = kind or self.header.kind ram = self.header.ram_size # DOC: fullsnes "FFD8h": RAM size (1 << n) KiB, 0 = none. # HYPOTHESIS: SRAM with no save file loaded reads zeros. Real SRAM keeps # whatever the battery held; MAME 0.285 reads $FF from a fresh one # (OBSERVED, Chrono Trigger, docs/mame-oracle.md "The lockstep"). self.sram = bytearray((1 << ram) * 1024 if 0 < ram <= 8 else 0) self.title = self.header.title # DOC: SNESdev wiki "ROM header" $FFD6: low nibble 2 ROM+RAM+battery, # 5 +coprocessor+RAM+battery, 6 +coprocessor+battery. self.has_battery = bool(self.sram) and self.header.chipset & 0x0F in (2, 5, 6) # -- saves ----------------------------------------------------------------- def battery(self) -> bytes | None: """The battery-backed SRAM to save, or None (docs/cartridge.md "Protocol"). DOC: SNESdev wiki "Save file formats": a .srm is "a simple dump of the battery backed cartridge save RAM", from its lowest address; the header's $FFD8 gives the size. """ return bytes(self.sram) if self.has_battery else None def load_battery(self, data: bytes) -> None: """Load a .srm. A file of another size is taken as far as both reach (DESIGN: frontends pad or cut .srm files; the X5 writes its own size).""" n = min(len(data), len(self.sram)) self.sram[:n] = data[:n] # -- the connector ------------------------------------------------------- def rom_offset(self, address: int) -> int | None: """The image offset an address reads, or None when not ROM.""" bank = address >> 16 offset = address & 0xFFFF if self.kind == LOROM: # DOC: fullsnes "Plain LoROM": ROM at 00-7D,80-FF:8000-FFFF, # mirrors at 40-7D,C0-FF:0000-7FFF. if offset & 0x8000 or bank & 0x40 and (bank & 0x7F) < 0x7E: if (bank & 0x7F) >= 0x70 and not offset & 0x8000: return None return mirror((bank & 0x7F) << 15 | offset & 0x7FFF, len(self.rom)) return None if self.kind == HIROM: # DOC: fullsnes "Plain HiROM": ROM at 40-7D,C0-FF:0000-FFFF, # mirrors at 00-3F,80-BF:8000-FFFF. if bank & 0x40 or offset & 0x8000: return mirror((bank & 0x3F) << 16 | offset, len(self.rom)) return None # ExHiROM (DOC: fullsnes "SHVC-LJ3M-01": banks 00-7D hold other ROM # banks than 80-FF): 80-FF the first 4 MiB, 00-7D the rest. if bank & 0x40 or offset & 0x8000: high = 0 if bank & 0x80 else 0x400000 return mirror(high | (bank & 0x3F) << 16 | offset, len(self.rom)) return None def sram_offset(self, address: int) -> int | None: if not self.sram: return None bank = address >> 16 offset = address & 0xFFFF if self.kind == LOROM: # DOC: fullsnes "LoROM with SRAM": 70-7D,F0-FF, the lower 32 KiB on # the newer boards (the older map the whole bank; the lower half # is what both share). if (bank & 0x7F) >= 0x70 and (bank & 0x7F) < 0x7E and not offset & 0x8000: return ((bank & 0x0F) << 15 | offset) % len(self.sram) return None if 0x6000 <= offset < 0x8000: # DOC: fullsnes "HiROM with SRAM": 20-3F,A0-BF:6000-7FFF (ExHiROM: # 80-BF:6000-7FFF). if self.kind == HIROM and bank & 0x60 == 0x20: return ((bank & 0x1F) << 13 | offset - 0x6000) % len(self.sram) if self.kind == EXHIROM and bank & 0xC0 == 0x80: return ((bank & 0x3F) << 13 | offset - 0x6000) % len(self.sram) return None def read(self, address: int, mdr: int) -> int: s = self.sram_offset(address) if s is not None: return self.sram[s] r = self.rom_offset(address) if r is not None: return self.rom[r] return mdr def write(self, address: int, value: int) -> None: s = self.sram_offset(address) if s is not None: self.sram[s] = value __all__ = ["EXHIROM", "HIROM", "LOROM", "Cartridge", "Header", "find_header", "mirror"]