"""Record a Mega Drive game's Z80 as a replayable benchmark workload. Runs a cartridge on megadrive-python (a sibling checkout; run this with its interpreter) from power-on for ``--frames`` frames, with no pad input, and records every call the board makes on its Z80: each ``step()`` together with the byte values the core read during it (memory and ports, in order), and between steps the lifecycle requests, ``restore_state`` calls (the board's bus probe runs a step on a scratch bus and restores), and the host's direct register writes. ``benchmarks/speed.py`` replays the recording into either core: the replay host hands back the recorded values, so both cores execute exactly the instruction stream the game's sound driver executed, and the final state is checked against the one recorded here. ../megadrive-python/.venv-pypy/bin/python benchmarks/record_megadrive.py \\ "/data/emu/roms/megadrive/Sonic 3 (Europe).zip" --frames 600 \\ --out benchmarks/workloads/sonic3.z80rec The recordings hold the driver's code and data as read from the cartridge, so they are not committed (benchmarks/workloads/ is ignored). """ from __future__ import annotations import argparse import gzip import json import sys import time from array import array from dataclasses import astuple, fields from pathlib import Path MEGADRIVE = Path(__file__).resolve().parents[2] / "megadrive-python" sys.path[:0] = [str(MEGADRIVE / "src")] from megadrive_python.cartridge import Cartridge, load_image # noqa: E402 from megadrive_python.machine import MACHINES # noqa: E402 from megadrive_python.system import System # noqa: E402 # Event codes in the op stream. STEPS n is n consecutive plain steps. STEPS, INT, INT_CLEAR, RESET, RESET_CLEAR, NMI, SET, RESTORE = range(1, 9) #: Registers a host may write directly; SET carries an index into this. REGISTERS = ( *("a", "b", "c", "d", "e", "h", "l", "ix", "iy", "sp", "pc", "wz", "i", "r"), *("iff1", "iff2", "im", "af_", "bc_", "de_", "hl_", "q", "halted"), ) class Recording: def __init__(self) -> None: self.ops = array("I") self.reads = bytearray() self.pending_steps = 0 self.in_step = False def event(self, *words: int) -> None: if self.pending_steps: self.ops.extend((STEPS, self.pending_steps)) self.pending_steps = 0 self.ops.extend(words) def _recording_class(base: type) -> type: class RecordingZ80(base): def step(self) -> int: rec = self._rec read_byte, read_port = self.read_byte, self.read_port reads = rec.reads def logged_read(address: int) -> int: value = read_byte(address) reads.append(value) return value def logged_port(port: int) -> int: value = read_port(port) reads.append(value) return value object.__setattr__(self, "read_byte", logged_read) object.__setattr__(self, "read_port", logged_port) rec.in_step = True try: t_states = base.step(self) finally: rec.in_step = False object.__setattr__(self, "read_byte", read_byte) object.__setattr__(self, "read_port", read_port) rec.pending_steps += 1 return t_states def request_maskable_interrupt(self, vector_byte: int = 0xFF) -> None: if self.capture_state().maskable_interrupt_vector != vector_byte: self._rec.event(INT, vector_byte) base.request_maskable_interrupt(self, vector_byte) def clear_maskable_interrupt(self) -> None: if self.capture_state().maskable_interrupt_vector is not None: self._rec.event(INT_CLEAR) base.clear_maskable_interrupt(self) def request_reset(self) -> None: self._rec.event(RESET) base.request_reset(self) def clear_reset(self) -> None: self._rec.event(RESET_CLEAR) base.clear_reset(self) def request_non_maskable_interrupt(self) -> None: self._rec.event(NMI) base.request_non_maskable_interrupt(self) def restore_state(self, state: object) -> None: values = [(0x100 if value is None else int(value)) for value in astuple(state)] rec = self._rec rec.event(RESTORE, *values) rec.in_step = True # the restore's own register writes are not host writes try: base.restore_state(self, state) finally: rec.in_step = False def __setattr__(self, name: str, value: object) -> None: rec = self.__dict__.get("_rec") if rec is not None and not rec.in_step and name in REGISTERS: rec.event(SET, REGISTERS.index(name), int(value)) object.__setattr__(self, name, value) return RecordingZ80 def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("rom", type=Path) parser.add_argument("--frames", type=int, default=600) parser.add_argument("--out", type=Path, required=True) args = parser.parse_args() image = load_image(args.rom) system = System(MACHINES["genesis"], Cartridge.from_image(image)) z80 = system.z80 rec = Recording() # The board built its Z80 and held it in reset before we got here; start # the recording from that state. initial = [(0x100 if v is None else int(v)) for v in astuple(z80.capture_state())] object.__setattr__(z80, "_rec", rec) z80.__class__ = _recording_class(type(z80)) started = time.time() for frame in range(args.frames): system.run_frame() if frame % 60 == 59: print(f" frame {frame + 1}, {time.time() - started:.0f} s", file=sys.stderr) rec.event() # flush the last run of steps final = [(0x100 if v is None else int(v)) for v in astuple(z80.capture_state())] header = { "rom": args.rom.name, "frames": args.frames, "board": "megadrive-python " + _git_head(MEGADRIVE), "fields": [f.name for f in fields(type(z80.capture_state()))], "registers": list(REGISTERS), "initial": initial, "final": final, "ops": len(rec.ops), "reads": len(rec.reads), "z80_instructions": system.z80_instructions, } args.out.parent.mkdir(parents=True, exist_ok=True) with gzip.open(args.out, "wb") as out: blob = json.dumps(header).encode() out.write(len(blob).to_bytes(4, "little") + blob) out.write(len(rec.ops).to_bytes(4, "little") + rec.ops.tobytes()) out.write(rec.reads) print(json.dumps(header | {"initial": "...", "final": "..."})) return 0 def _git_head(path: Path) -> str: import subprocess return subprocess.run( ["git", "-C", str(path), "rev-parse", "--short", "HEAD"], capture_output=True, text=True ).stdout.strip() if __name__ == "__main__": raise SystemExit(main())