# SPDX-License-Identifier: MIT """Run GSU code in the minimal harness: ``python -m gsu_python``. python -m gsu_python GSUADD.sfc --krom # krom's PASS/FAIL rows python -m gsu_python GAME.sfc --start 01:8A60 --clsr 1 --max-clocks 2000000 python -m gsu_python GAME.sfc --start 01:8A60 --trace run.jsonl python -m gsu_python GAME.sfc --start 01:8A60 --debug -c "break 01:8A70" -c continue --batch ROM is a cartridge image (``.sfc``/``.smc``, or a ``.zip`` holding one, read in memory: BYOR, nothing is extracted). Without ``--krom`` the host sets CLSR, CFGR (IRQ masked) and SCMR (RON, RAN), writes PBR and R15 from ``--start`` and runs until STOP or ``--max-clocks``, then prints the registers. ``--trace`` writes one JSON Line per instruction and S-CPU access. """ from __future__ import annotations import argparse import io import sys import zipfile from pathlib import Path from gsu_python.console import CommandDebugger, CommandError, format_state, parse_address from gsu_python.core import GSU from gsu_python.debug import DebugSession from gsu_python.harness import run_krom from gsu_python.model import MODELS from gsu_python.trace import encode def load_rom(path: Path) -> bytes: if path.suffix.lower() == ".zip": with zipfile.ZipFile(io.BytesIO(path.read_bytes())) as archive: names = [n for n in archive.namelist() if n.lower().endswith((".sfc", ".smc"))] if not names: raise SystemExit(f"no .sfc/.smc in {path}") data = archive.read(names[0]) else: data = path.read_bytes() if len(data) % 0x8000 == 0x200: # a copier header data = data[0x200:] return data def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser( prog="python -m gsu_python", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument("rom", type=Path) parser.add_argument("--model", choices=sorted(MODELS), default="gsu2") parser.add_argument("--start", default="00:8000", metavar="BANK:ADDR") parser.add_argument("--clsr", type=int, choices=(0, 1), default=1) parser.add_argument("--scmr", type=lambda t: int(t, 0), default=0x18) parser.add_argument("--ram-size", type=lambda t: int(t, 0), default=0x20000) parser.add_argument("--max-clocks", type=int, default=50_000_000, metavar="N") parser.add_argument("--trace", type=Path, metavar="FILE", help="write a JSONL trace") parser.add_argument("--krom", action="store_true", help="run krom's GSUTest protocol") parser.add_argument("--debug", action="store_true", help="open the command debugger") parser.add_argument("-c", dest="commands", action="append", default=[], help="debugger command") parser.add_argument("--batch", action="store_true", help="exit after the -c commands") args = parser.parse_args(argv) rom = load_rom(args.rom) model = MODELS[args.model] if args.krom: result = run_krom(rom, gsu=GSU(rom, bytearray(0x8000), model=model)) for row in result.rows: verdict = "PASS" if row.passed else "FAIL" print(f"{row.index:3} R{row.register:<2} {row.value:04X} (expected {row.expected:04X})" f" SFR {row.sfr:02X} ({row.expected_sfr:02X}) {verdict}") # fmt: skip print(f"{result.passed} of {len(result.rows)} rows PASS") return 0 if result.passed == len(result.rows) else 1 gsu = GSU(rom, bytearray(args.ram_size), model=model) start = parse_address(args.start) gsu.write_io(0x3039, args.clsr) gsu.write_io(0x3037, 0x80) gsu.write_io(0x303A, args.scmr) gsu.write_io(0x3034, start >> 16) gsu.write_io(0x301E, start & 0xFF) gsu.write_io(0x301F, start >> 8 & 0xFF) if args.debug: debugger = CommandDebugger(DebugSession(gsu)) for command in ["registers", "disassemble", *args.commands]: print(f"gsu> {command}") try: result = debugger.execute(command) except CommandError as exc: print(f"error: {exc}") continue print(*result.lines, sep="\n") if result.quit: return 0 if not args.batch: debugger.interact(sys.stdin, sys.stdout) return 0 instructions = 0 if args.trace is not None: session = DebugSession(gsu, history_limit=0) with args.trace.open("w", encoding="utf-8") as stream: while gsu.running and gsu.clock < args.max_clocks: stream.write(encode(session.step()) + "\n") instructions += 1 else: while gsu.running and gsu.clock < args.max_clocks: gsu.step() instructions += 1 status = "STOP" if not gsu.running else "clock budget" print(f"[{instructions} instructions, {gsu.clock} input clocks, {status}]", file=sys.stderr) print(*format_state(gsu.capture_state(cache=False)), sep="\n") return 0 if __name__ == "__main__": raise SystemExit(main())