#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Trace the Xbox's Pentium III in MAME 0.285 (a closed-box detector, tier 5). Runs MAME headless on its `xbox` machine (driver status "preliminary"), switches the debugger's instruction trace on at frame --start and off --frames later, and exits. Each trace line is MAME's own disassembly, prefixed with the registers named by --regs (MAME's state symbols for its i386-family core: EAX ... EDI, EIP, EFLAGS, CR0, CS ...; see docs/mame-oracle.md for the list read from `cpu.state`). MAME_ROMPATH=... python -I scripts/mame_trace.py --bios bios3 --start 0 --frames 2 From reset the first instructions are the MCPX boot ROM's, then the flash's x-code interpreter loop and the second-stage loader: **Microsoft's code**. The trace therefore stays in the git-ignored tests/mame_traces/ like a dump would, and only counts and the shape of a line are written into the documents. The run's cwd is that directory, so error.log, cfg/ and nvram/ land there too. The firmware comes from $MAME_ROMPATH, never from the repository. """ from __future__ import annotations import argparse import collections import os import re import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] RUNS = ROOT / "tests" / "mame_traces" LUA = """ dbg = manager.machine.debugger cpu = manager.machine.devices[':maincpu'] if {start} == 0 then dbg:command('trace {out},maincpu,noloop{action}') end dbg:command('go') frames = 0 sub = emu.add_machine_frame_notifier(function() frames = frames + 1 if frames == {start} and {start} > 0 then dbg:command('trace {out},maincpu,noloop{action}') end if frames == {stop} then dbg:command('trace off,maincpu') print(string.format("WINDOW %.6f s", manager.machine.time:as_double())) print("STATE " .. table.concat({{ {names} }}, " ")) manager.machine:exit() end end) """ def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--machine", default="xbox") parser.add_argument("--bios", default="bios3", help="MAME biosset: bios0 4134, bios1 3944, bios2 4034, bios3 4817") parser.add_argument("--start", type=int, default=0, help="frame at which tracing starts (0 = from reset)") parser.add_argument("--frames", type=int, default=2) parser.add_argument("--regs", default="EAX,ESP,EFLAGS,CR0", help="comma-separated MAME symbols, or empty") parser.add_argument("--out", type=Path, default=RUNS / "xbox.trace") parser.add_argument("--mame", default="mame") args = parser.parse_args() rompath = os.environ.get("MAME_ROMPATH") if not rompath: print("set MAME_ROMPATH (MAME's ';'-separated rompath holding xbox.zip)", file=sys.stderr) return 2 RUNS.mkdir(parents=True, exist_ok=True) out = args.out.resolve() regs = [r for r in args.regs.split(",") if r] action = "" if regs: fmt = " ".join(f"{r}=%08X" for r in regs) + " " action = ',{tracelog "' + fmt + '",' + ",".join(regs) + "}" # The state symbols printed at the end, so the docs can list what MAME exposes. names = 'cpu.state["EIP"] and string.format("EIP=%08X", cpu.state["EIP"].value) or "?"' script = RUNS / "trace.lua" script.write_text(LUA.format(start=args.start, stop=args.start + args.frames, out=out.as_posix(), action=action, names=names), encoding="utf-8") command = [ "nice", "taskset", "-c", "24-31", args.mame, args.machine, "-bios", args.bios, "-rompath", rompath, "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-debug", "-debugger", "none", "-autoboot_script", str(script), "-seconds_to_run", str(max(5, (args.start + args.frames) // 60 + 5)), ] result = subprocess.run(command, cwd=RUNS, capture_output=True, text=True, check=False) for line in result.stdout.splitlines(): if line.startswith(("WINDOW", "STATE")): print(line) if not out.exists(): print(result.stdout[-2000:], result.stderr[-2000:], sep="\n", file=sys.stderr) return 1 count = 0 mnemonics: collections.Counter[str] = collections.Counter() regions: collections.Counter[str] = collections.Counter() pattern = re.compile(r"([0-9A-F]{8}): (\S+)") with out.open(encoding="utf-8", errors="replace") as handle: for line in handle: count += 1 match = pattern.search(line) if match: address = int(match.group(1), 16) regions["MCPX ROM window FFFFFE00+" if address >= 0xFFFFFE00 else "flash window FF000000+" if address >= 0xFF000000 else "RAM below 64 MiB" if address < 0x04000000 else "other"] += 1 mnemonics[match.group(2)] += 1 print(f"{count} instructions traced to {out}") for region, n in regions.most_common(): print(f" {region}: {n}") print(" most frequent mnemonics: " + ", ".join(f"{m} {n}" for m, n in mnemonics.most_common(12))) return 0 if __name__ == "__main__": sys.exit(main())