# SPDX-License-Identifier: MIT """Run the core in the harness on a cartridge: ``python -m hg51b_python``. python -m hg51b_python "Mega Man X2 (USA).zip" # the built-in test python -m hg51b_python CART --test-function 0E:89 # one routine, R0-R15 python -m hg51b_python CART --test-function 0E:54 --r0 0x123456 --trace run.jsonl python -m hg51b_python CART --replay tests/mesen_traces/x2-boot # rung 4 python -m hg51b_python CART --test-function 0E:00 --debug -c "step 4" -c registers --batch CART is a BYOR cartridge read in place (``.zip`` or ``.sfc``). With no other option the games' built-in Cx4 test runs, item by item, against the expectations in the cartridge's own test code (``harness.selftest``). ``--test-function PB:PC`` configures the chip as the games do, sets R0 (``--r0``), preloads PB, starts PC, runs to the HALT and prints the registers. ``--trace`` writes one JSON line per instruction, S-CPU access, cache load and DMA (``trace.py``); ``--debug`` opens the command debugger at that start. """ from __future__ import annotations import argparse import sys from pathlib import Path from hg51b_python.console import CommandDebugger, CommandError, format_state, parse_address from hg51b_python.debug import DebugSession from hg51b_python.harness import Harness, read_cartridge, selftest from hg51b_python.trace import TraceWriter def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser( prog="python -m hg51b_python", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument("cartridge", type=Path) parser.add_argument("--test-function", metavar="PB:PC", help="run one routine, e.g. 0E:89") parser.add_argument("--r0", type=lambda s: int(s, 0), default=0, help="R0 before the start") parser.add_argument("--page", type=int, default=0, help="cache page to preload into") parser.add_argument("--trace", type=Path, metavar="FILE", help="write a JSONL trace") parser.add_argument("--replay", type=Path, metavar="DIR", help="replay a Mesen2 recording") 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 = read_cartridge(args.cartridge) if args.replay: from hg51b_python.replay import replay report = replay(rom, args.replay) print(*report.summary(), sep="\n") return 0 if not report.divergences else 1 if not args.test_function: result = selftest(rom) print("Cx4 TEST", *result.lines(), sep="\n") return 0 if result.ok else 1 where = parse_address(args.test_function) harness = Harness(rom) harness.configure() harness.set_register(0, args.r0) if args.debug: session = DebugSession(harness) _start(harness, where, args.page) debugger = CommandDebugger(session, harness) for command in ["registers", "disassemble", *args.commands]: print(f"hg51b> {command}") try: outcome = debugger.execute(command) except (CommandError, ValueError) as exc: print(f"error: {exc}") continue print(*outcome.lines, sep="\n") if outcome.quit: return 0 if not args.batch: debugger.interact(sys.stdin, sys.stdout) return 0 if args.trace: session = DebugSession(harness, history_limit=0) with args.trace.open("w", encoding="utf-8") as stream: writer = TraceWriter(session, stream) _start(harness, where, args.page) while writer.step() is not None: pass writer.flush() session.close() print(f"[{writer.records} trace records: {args.trace}]", file=sys.stderr) else: harness.call(where >> 8, where & 0xFF, args.page) cx = harness.cx print( f"{where >> 8:02X}:{where & 0xFF:02X}: " + " ".join(f"R{i}={v:06X}" for i, v in enumerate(cx.r)) ) print(f"[{cx.instructions} instructions, {cx.clock} clocks]", file=sys.stderr) print(*format_state(cx.capture_state(memory=False)), sep="\n", file=sys.stderr) return 0 def _start(harness: Harness, where: int, page: int) -> None: """The games' start sequence without the final wait (the caller steps the chip).""" harness.wait_idle() harness.write(0x7F4D, where >> 8 & 0xFF) harness.write(0x7F4E, where >> 16) harness.write(0x7F48, page) harness.wait_idle() harness.write(0x7F4F, where & 0xFF) if __name__ == "__main__": raise SystemExit(main())