#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Run a short program of our own on MAME 0.285's PowerPC core and record its trace. MAME is a detector here, never a judge (docs/mame-oracle.md, tier 5). MAME has no Gekko: its GameCube driver (``gcjp`` and clones, nintendo/gamecube.cpp) is a skeleton that names an "IBM PowerPC 603" at 4.85 MHz and stops at start-up with a fatal clock error (OBSERVED, 2026-11-26). Its ``triforce`` driver (sega/triforce.cpp, also a skeleton, the same 603 device) does start, so this script uses it as a carrier for MAME's base PowerPC core: 1. MAME boots ``triforce`` (its boot ROM is read in place from ``$MAME_ROMPATH``, never copied; nothing of it is traced: the trace starts only at our own program). 2. At the first frame, the Lua script writes our program (``PROGRAM`` below, assembled here from the Programming Environments Manual's encodings) into RAM at 0x3000, sets MSR to 0 (translation off, exception prefix 0, interrupts off: by then the boot ROM has turned translation on, and the first run went to the 603's TLB-miss vector at 0x1000), points PC at it, and a breakpoint there switches the debugger's trace on. 3. The program ends in ``b .``; ``noloop`` collapses it. After two frames MAME exits. Each trace line is ``T pc r3..r16 cr xer``. The script then checks every result against the value the PEM's definitions give (computed below by plain Python arithmetic), so a run says both what MAME did and whether it agrees with our reading of the manual. Paired singles, quantized loads, dcbz_l, the locked cache and the write-gather pipe do not exist in MAME's core: nothing Gekko-specific can be detected this way. MAME_ROMPATH=... python -I scripts/mame_trace.py Output goes to a fresh directory under tests/mame_traces/ (ignored). """ from __future__ import annotations import argparse import os import resource import subprocess import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] MAME = os.environ.get("MAME", "mame") # the MAME 0.285 binary; $MAME overrides BASE = 0x3000 MASK = 0xFFFFFFFF def d_form(opcd: int, rt: int, ra: int, imm: int) -> int: return (opcd << 26) | (rt << 21) | (ra << 16) | (imm & 0xFFFF) def xo_form(rt: int, ra: int, rb: int, xo: int, oe: int = 0, rc: int = 0) -> int: return (31 << 26) | (rt << 21) | (ra << 16) | (rb << 11) | (oe << 10) | (xo << 1) | rc def x_form(rs: int, ra: int, rb: int, xo: int, rc: int = 0) -> int: return (31 << 26) | (rs << 21) | (ra << 16) | (rb << 11) | (xo << 1) | rc def rlwinm(ra: int, rs: int, sh: int, mb: int, me: int) -> int: return (21 << 26) | (rs << 21) | (ra << 16) | (sh << 11) | (mb << 6) | (me << 1) def mtspr(spr: int, rs: int) -> int: split = ((spr & 0x1F) << 5) | (spr >> 5) return (31 << 26) | (rs << 21) | (split << 11) | (467 << 1) # (word, text). Encodings: PEM (MPCFPE32B rev 2) chapter 8 and appendix A. PROGRAM = [ (d_form(14, 0, 0, 0), "li r0,0"), (mtspr(1, 0), "mtxer r0"), (d_form(14, 3, 0, 0x7FFF), "li r3,0x7fff"), (d_form(15, 4, 0, 0x8000), "lis r4,0x8000"), (d_form(13, 5, 4, -1), "addic. r5,r4,-1"), (xo_form(6, 3, 4, 8), "subfc r6,r3,r4"), (xo_form(7, 4, 4, 266, oe=1, rc=1), "addo. r7,r4,r4"), (xo_form(8, 3, 3, 235), "mullw r8,r3,r3"), (xo_form(9, 4, 3, 75), "mulhw r9,r4,r3"), (xo_form(10, 4, 3, 491), "divw r10,r4,r3"), (xo_form(11, 4, 3, 459), "divwu r11,r4,r3"), (rlwinm(12, 4, 1, 31, 31), "rlwinm r12,r4,1,31,31"), (x_form(3, 13, 0, 26), "cntlzw r13,r3"), (x_form(4, 14, 4, 824), "srawi r14,r4,4"), (d_form(14, 15, 0, -1), "li r15,-1"), (xo_form(16, 15, 15, 266, rc=1), "add. r16,r15,r15"), (0x48000000, "b ."), ] def s32(value: int) -> int: value &= MASK return value - (1 << 32) if value & 0x80000000 else value def expected() -> dict[str, int]: """The PEM's definitions, by plain arithmetic (our reading, not hardware).""" r3, r4 = 0x7FFF, 0x80000000 return { "R5": (r4 - 1) & MASK, "R6": (r4 - r3) & MASK, "R7": (r4 + r4) & MASK, "R8": (r3 * r3) & MASK, "R9": ((s32(r4) * s32(r3)) >> 32) & MASK, "R10": int(s32(r4) / s32(r3)) & MASK, # rounds toward zero, as divw does "R11": (r4 // r3) & MASK, "R12": 1, "R13": 17, "R14": (s32(r4) >> 4) & MASK, "R16": 0xFFFFFFFE, } REGS = [f"R{n}" for n in range(3, 17)] END = BASE + 4 * (len(PROGRAM) - 1) # the closing "b ." def lua_script() -> str: writes = "\n".join( f" space:write_u32(0x{BASE + 4 * i:X}, 0x{word:08X}) -- {text}" for i, (word, text) in enumerate(PROGRAM) ) fields = ",".join(["pc", *(r.lower() for r in REGS), "cr", "xer"]) fmt = " ".join(["T"] + ["%X"] * (fields.count(",") + 1)) trace = f"trace T.trace,:maincpu,noloop,{{logerror \\\"{fmt}\\\\n\\\",{fields}}}" # The trace is switched on only by a breakpoint at our own program, so no boot-ROM # instruction is ever traced, even if the PC change below did not take. return f"""local cpu = manager.machine.devices[":maincpu"] local space = cpu.spaces["program"] local dbg = manager.machine.debugger dbg.visible_cpu = cpu frames = 0 sub = emu.add_machine_frame_notifier(function() frames = frames + 1 if frames == 1 then {writes} dbg:command("bpset {BASE:X},1,{{{trace};go}}") dbg:command("bpset {END:X},1,{{trace off;go}}") dbg:command("msr = 0") dbg:command("pc = {BASE:X}") dbg:command("go") elseif frames >= 3 then dbg:command("trace off") manager.machine:exit() end end) """ def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--max-mb", type=int, default=5) args = parser.parse_args() rompath = os.environ.get("MAME_ROMPATH") if not rompath: print("set MAME_ROMPATH to the folder holding triforce.zip") return 2 out = ROOT / "tests" / "mame_traces" / time.strftime("triforce-ppc603-%Y%m%d-%H%M%S") out.mkdir(parents=True, exist_ok=False) (out / "trace.lua").write_text(lua_script(), encoding="utf-8") command = [ "nice", MAME, "triforce", "-rompath", rompath, "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-debug", "-debugger", "none", "-log", "-autoboot_script", "trace.lua", "-seconds_to_run", "5", ] cap = args.max_mb << 20 def limit() -> None: resource.setrlimit(resource.RLIMIT_FSIZE, (cap, cap)) result = subprocess.run(command, cwd=out, preexec_fn=limit, check=False, capture_output=True, text=True) log = out / "error.log" lines = [line.split() for line in log.open(encoding="latin-1") if line.startswith("T ")] if log.exists() else [] print(f"exit {result.returncode}; {len(lines)} trace lines in {log.relative_to(ROOT)}") if not lines: print(result.stdout[-2000:], result.stderr[-2000:]) return 1 names = ["T", "PC", *REGS, "CR", "XER"] done = [line for line in lines if len(line) == len(names) and int(line[1], 16) == END] if not done: print("the program did not reach its closing branch") return 1 final = dict(zip(names, done[0])) want = expected() agree = 0 for reg, value in want.items(): got = int(final[reg], 16) mark = "agree" if got == value else "DIFFER" agree += got == value print(f" {reg:4} MAME {got:08X} PEM {value:08X} {mark}") print(f" CR {int(final['CR'], 16):08X} XER {int(final['XER'], 16):08X}") print(f"{agree}/{len(want)} results agree with the PEM's definitions") return 0 if __name__ == "__main__": sys.exit(main())