#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Which 64/128 KiB SuperGame dumps run code at $4000-$7FFF, from their own bytes. The CC0 software list types every plain SuperGame board of these sizes as ``a78_sg`` and says nothing about $4000-$7FFF; Stolberg's guide (tier 3): "some games have bank 6 fixed at this area". This decides it per dump from the dump alone: 1. Recursive descent through bank 7 (the bank fixed at $C000-$FFFF on every SuperGame board) from the NMI, reset and IRQ vectors, following JSR, JMP and branches inside $C000-$FFFF and recording every JSR/JMP whose target lies in $4000-$7FFF. Nothing banked ($8000-$BFFF) is followed, so every call found is in code the fixed bank certainly reaches by its own flow (a lower bound: banked code may call there too). 2. From each such target, the same descent through **bank 6** placed at $4000: the number of distinct instructions reached and the number of undocumented opcodes met on the way. Thousands of instructions and none undocumented is code; data would hit an undocumented opcode within a few dozen bytes. A dump with calls from (1) and clean code in (2) needs bank 6 at $4000, and the table holds it as a row confirmed from the dump's own bytes (``cartridge/table.py`` ``_BANK6``). With ``--check`` the script exits 1 if a dump with such calls lacks the row or a row lacks the calls (the gate; its seeded fault is ``--fault drop-row``). python scripts/scan_4000.py ".../Atari - Atari 7800 (BIN)" [--check] """ from __future__ import annotations import argparse import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from a7800_python.cartridge import formats, table # noqa: E402 _MODES = { 1: "00 08 0A 18 28 2A 38 40 48 4A 58 60 68 6A 78 88 8A 98 9A A8 AA B8 BA C8 CA D8 E8 EA F8", 2: "01 05 06 09 10 11 15 16 24 25 26 29 30 31 35 36 41 45 46 49 50 51 55 56 61 65 66 69 70 " "71 75 76 81 84 85 86 90 91 94 95 96 A0 A1 A2 A4 A5 A6 A9 B0 B1 B4 B5 B6 C0 C1 C4 C5 C6 " "C9 D0 D1 D5 D6 E0 E1 E4 E5 E6 E9 F0 F1 F5 F6", 3: "0D 0E 19 1D 1E 20 2C 2D 2E 39 3D 3E 4C 4D 4E 59 5D 5E 6C 6D 6E 79 7D 7E 8C 8D 8E 99 9D " "AC AD AE B9 BC BD BE CC CD CE D9 DD DE EC ED EE F9 FD FE", } # fmt: skip LENGTH = {int(h, 16): n for n, s in _MODES.items() for h in s.split()} # documented opcodes BRANCHES = {0x10, 0x30, 0x50, 0x70, 0x90, 0xB0, 0xD0, 0xF0} ENDS = {0x00, 0x40, 0x60, 0x4C, 0x6C} # BRK, RTI, RTS, JMP, JMP () def descend(bank: bytes, base: int, starts) -> tuple[int, int, list[tuple[int, int]]]: """(instructions reached, undocumented opcodes met, [(site, target)] leaving the bank).""" end = base + len(bank) - 1 seen: set[int] = set() undocumented, leaving = 0, [] todo = list(starts) def byte(address: int) -> int: return bank[(address - base) % len(bank)] while todo: pc = todo.pop() while base <= pc <= end and pc not in seen: seen.add(pc) op = byte(pc) if op not in LENGTH: undocumented += 1 break if op in (0x20, 0x4C): target = byte(pc + 1) | byte(pc + 2) << 8 (todo.append(target) if base <= target <= end else leaving.append((pc, target))) # fmt: skip elif op in BRANCHES: offset = byte(pc + 1) todo.append(pc + 2 + offset - (256 if offset > 127 else 0)) if op in ENDS: break pc += LENGTH[op] return len(seen), undocumented, leaving def scan(payload: bytes) -> dict: """The evidence for one SuperGame payload of 64 or 128 KiB. Bank numbers are masked to the dump's bank count as the board masks them, so on a 64 KiB dump "bank 6" is its third 16 KiB (Stolberg: PAL Karateka "only uses banks 4-7 ... and bank 6 is also fixed at $4000-$7fff"). A vector that itself points into $4000-$7FFF counts as a call from the vector's address.""" banks = len(payload) // 0x4000 bank7 = payload[-0x4000:] six = 6 % banks bank6 = payload[six * 0x4000 : (six + 1) * 0x4000] vectors = [bank7[v] | bank7[v + 1] << 8 for v in (0x3FFA, 0x3FFC, 0x3FFE)] reached, _, leaving = descend(bank7, 0xC000, [v for v in vectors if v >= 0xC000]) leaving += [(0xFFFA + 2 * i, v) for i, v in enumerate(vectors)] calls = sorted({(s, t) for s, t in leaving if 0x4000 <= t < 0x8000}) code, bad = descend(bank6, 0x4000, [t for _, t in calls])[:2] return {"bank7": reached, "calls": calls, "bank6_code": code, "bank6_undocumented": bad} def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("folder", type=Path) parser.add_argument("--check", action="store_true") parser.add_argument("--fault", choices=("drop-row",)) args = parser.parse_args() rows = dict(table._BANK6) if args.fault == "drop-row": rows.pop(next(iter(rows))) failures = 0 for path in sorted(args.folder.glob("*.zip")): try: desc = formats.load(path) except Exception: # the documented refusal continue if desc.console != "7800" or desc.scheme != "supergame" or desc.size not in ( 0x10000, 0x20000 ): continue found = scan(desc.payload) needs = bool(found["calls"]) and found["bank6_undocumented"] == 0 has = desc.sha256 in rows behaviour = desc.sha256 in table._BANK6_BEHAVIOUR # confirmed by uses_4000.py instead verdict = "ok" if needs == has or (behaviour and not needs) else "MISMATCH" failures += verdict != "ok" sites = " ".join(f"{s:04X}->{t:04X}" for s, t in found["calls"][:3]) print(f"{verdict:8} {path.stem[:40]:40} {desc.at_4000:11} bank7 {found['bank7']:5} " f"calls {len(found['calls']):2} {sites:32} bank6 code {found['bank6_code']:5} " f"undocumented {found['bank6_undocumented']} {desc.sha256[:16]}") # fmt: skip print(f"{failures} mismatches between the scan and table._BANK6") return 1 if args.check and failures else 0 if __name__ == "__main__": sys.exit(main())