#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Instruction coverage of a MAME GSU trace: which opcodes, in which prefix state, ran. Reads a ``gsu.log.gz`` written by ``mame_gsu_trace.py`` and the cartridge it traced (read in place: ``.sfc``, or the ``.zip``/``.7z`` member is read with ``zipfile``/the extracted copy in the run directory). For each traced instruction the opcode is read from ROM at ``pc`` (MAME's ``(PBR << 16 | R15) - 1``) when PBR is a ROM bank (``00-5F``); code run from Game Pak RAM (PBR ``70-71``) is counted as such, its bytes being in RAM, not in the file. The prefix state comes from the SFR the trace logged **before** the instruction (ALT1 bit 8, ALT2 bit 9, B bit 12). python -I scripts/trace_coverage.py tests/mame_traces/RUN [--rom CART.sfc] [--json out.json] Prints the instruction forms seen with counts (prefixes counted as their own opcodes, as the chip executes them), the forms never seen, ROM vs RAM code, and the deepest facts the docs quote (PLOT/RPIX counts, CACHE and LJMP, the CBR values, the distinct PBR/ROMBR/RAMBR values). """ from __future__ import annotations import argparse import gzip import json import sys import zipfile from collections import Counter from pathlib import Path ALT_NAMES = {0: "", 1: "ALT1 ", 2: "ALT2 ", 3: "ALT3 "} def form(op: int, alt: int, b: bool) -> str: """The instruction an opcode is, given the prefix state (start-here.md opcode map).""" hi, lo = op >> 4, op & 15 a1, a2 = alt & 1, alt >> 1 fixed = {0x00: "STOP", 0x01: "NOP", 0x02: "CACHE", 0x03: "LSR", 0x04: "ROL", 0x3C: "LOOP", 0x3D: "ALT1", 0x3E: "ALT2", 0x3F: "ALT3", 0x4D: "SWAP", 0x4F: "NOT", 0x70: "MERGE", 0x90: "SBK", 0x95: "SEX", 0x97: "ROR", 0x9E: "LOB", 0xC0: "HIB"} # fmt: skip if op in fixed: return fixed[op] if 0x05 <= op <= 0x0F: return ["BRA", "BGE", "BLT", "BNE", "BEQ", "BPL", "BMI", "BCC", "BCS", "BVC", "BVS"][op - 5] if hi == 1: return "MOVE" if b else "TO" if hi == 2: return "WITH" if hi == 3: return "STB" if a1 else "STW" if hi == 4 and lo < 12: return "LDB" if a1 else "LDW" if op == 0x4C: return "RPIX" if a1 else "PLOT" if op == 0x4E: return "CMODE" if a1 else "COLOR" if hi == 5: return ["ADD", "ADC", "ADD#", "ADC#"][alt] if hi == 6: return ["SUB", "SBC", "SUB#", "CMP"][alt] if hi == 7: return ["AND", "BIC", "AND#", "BIC#"][alt] if hi == 8: return ["MULT", "UMULT", "MULT#", "UMULT#"][alt] if 0x91 <= op <= 0x94: return "LINK" if op == 0x96: return "DIV2" if a1 else "ASR" if 0x98 <= op <= 0x9D: return "LJMP" if a1 else "JMP" if op == 0x9F: return "LMULT" if a1 else "FMULT" if hi == 0xA: return "LMS" if a1 else "SMS" if a2 else "IBT" if hi == 0xB: return "MOVES" if b else "FROM" if hi == 0xC: return ["OR", "XOR", "OR#", "XOR#"][alt] if hi == 0xD and lo < 15: return "INC" if op == 0xDF: return "ROMB" if alt == 3 else "RAMB" if a2 else "GETC" if hi == 0xE and lo < 15: return "DEC" if op == 0xEF: return ["GETB", "GETBH", "GETBL", "GETBS"][alt] if hi == 0xF: return "LM" if a1 else "SM" if a2 else "IWT" return f"?{op:02X}" ALL_FORMS = sorted( {form(op, alt, b) for op in range(256) for alt in range(4) for b in (False, True)} ) def rom_bytes(run: Path, rom: Path | None) -> bytes: if rom is None: found = sorted(p for p in run.iterdir() if p.suffix.lower() in {".sfc", ".smc"}) found = [p for p in found if not p.name.startswith("mirrored-")] or found if not found: raise SystemExit("no cartridge in the run directory: pass --rom") rom = found[0] if rom.suffix.lower() == ".zip": with zipfile.ZipFile(rom) as archive: name = next(n for n in archive.namelist() if n.lower().endswith((".sfc", ".smc"))) return archive.read(name) return rom.read_bytes() def gsu_rom_read(rom: bytes, address: int) -> int | None: """A ROM byte as the GSU addresses it (start-here.md "Memory as the GSU sees it").""" bank, offset = address >> 16, address & 0xFFFF if bank < 0x40: index = (bank << 15) | (offset & 0x7FFF) elif bank < 0x60: index = ((bank - 0x40) << 16) | offset else: return None return rom[index % len(rom)] def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("run", type=Path, help="run directory with gsu.log.gz") parser.add_argument("--rom", type=Path) parser.add_argument("--json", type=Path) args = parser.parse_args() rom = rom_bytes(args.run, args.rom) forms: Counter = Counter() where: Counter = Counter() banks = {"PBR": Counter(), "ROMBR": Counter(), "RAMBR": Counter(), "CBR": Counter()} g = None last = None total = 0 # The first instruction after a start executes the pipeline byte, not [pc]: # NOP (01h) after a STOP or at power-on; after the S-CPU's GO = 0, whatever # was prefetched (start-here.md "The pipeline"). Counted apart. pipelined = True with gzip.open(args.run / "gsu.log.gz", "rt", encoding="utf-8") as trace: for line in trace: kind = line[:2] if kind == "G ": g = line.split() continue if kind == "W " and line.split()[1][-4:] in ("301F", "3030"): pipelined = True continue if kind == "H " and g is not None: h = line.split() last = (g, h) repeat = 1 elif kind == "L " and last is not None: g, h = last repeat = int(line.split()[1]) else: continue pc = int(g[1], 16) sfr, pbr, rombr, rambr, cbr = (int(x, 16) for x in h[5:10]) alt = sfr >> 8 & 3 b = bool(sfr >> 12 & 1) op = gsu_rom_read(rom, pc) if pipelined: pipelined = False where["pipeline byte"] += 1 forms["(pipeline byte)"] += 1 total += 1 repeat -= 1 # an "L n" repeats the same registers, so the same pc if not repeat: g = None continue if op is None: where["RAM-resident"] += repeat name = "(RAM code)" else: where["ROM-resident"] += repeat name = form(op, alt, b) # a prefix after a prefix counts as itself pipelined = name == "STOP" forms[name] += repeat banks["PBR"][pbr] += repeat banks["ROMBR"][rombr] += repeat banks["RAMBR"][rambr] += repeat banks["CBR"][cbr] += repeat total += repeat g = None unseen = [f for f in ALL_FORMS if f not in forms and not f.startswith("?")] print(f"{total} instructions; {dict(where)}") print("forms:", ", ".join(f"{k} {v}" for k, v in forms.most_common())) print("never seen:", ", ".join(unseen)) for name, counter in banks.items(): print(f"{name}:", ", ".join(f"{k:X}:{v}" for k, v in counter.most_common(8))) if args.json: args.json.write_text( json.dumps({"total": total, "where": where, "forms": forms, "unseen": unseen, "banks": {k: {f"{a:X}": n for a, n in c.items()} for k, c in banks.items()}}, indent=1) + "\n", encoding="utf-8") # fmt: skip return 0 if __name__ == "__main__": sys.exit(main())