#!/usr/bin/env python3 """Compare a Phoenix Edition program image with MAME's decryption of a keyed set. A Phoenix set (``spf2td``) is not a plain decryption. Each 16-bit word of its program ROM is one of three things: - the **decrypted opcode** word (equal to the word in MAME's ``opcodes`` space of the keyed set): code, and only code, needs decrypting; - the **raw** word of the encrypted ROM (equal to MAME's ``program`` space): data the 68000 reads as data, which the hardware never decrypts; - **neither**: Capcom-free patches (the exception vectors pointed into a handler block near the top of the encrypted range, a few dozen words in the boot code). This script counts the three classes inside the encrypted range and checks that outside it the Phoenix image equals the raw ROM. Inputs: ``opcodes.bin`` and ``program.bin`` written by ``scripts/mame_trace.py --dump N`` (read from ``tests/mame_traces//``), the Phoenix set's program files read in place from the MAME non-merged zip, laid out by MAME 0.285 ``-listxml``. python -I scripts/mame_trace.py spf2tu --no-trace --dump 0x100000 --seconds 1 python -I scripts/phoenix_pair.py spf2td spf2tu The ``--patches`` option lists the "neither" runs (address, length). """ from __future__ import annotations import argparse import os import re import sys import xml.etree.ElementTree as ET import zipfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] XML = ROOT / "reference" / "mame-listxml" / "cps2.xml" ROMPATH = Path(os.environ.get("MAME_ROMPATH") or sys.exit("set MAME_ROMPATH to the MAME (non-merged) ROM folder")) def program_image(name: str) -> bytes: machine = ET.parse(XML).getroot().find(f"machine[@name='{name}']") if machine is None: raise SystemExit(f"{name} is not in {XML}") image = bytearray() with zipfile.ZipFile(ROMPATH / f"{name}.zip") as archive: for rom in machine.findall("rom[@region='maincpu']"): offset = int(rom.get("offset"), 16) data = archive.read(rom.get("name")) # ROM_LOAD16_WORD_SWAP: the file is little-endian words. swapped = bytes(b for i in range(0, len(data), 2) for b in (data[i + 1], data[i])) image[len(image) : offset + len(swapped)] = b"\0" * max(0, offset + len(swapped) - len(image)) image[offset : offset + len(swapped)] = swapped return bytes(image) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("phoenix", help="the Phoenix set, for example spf2td") parser.add_argument("keyed", help="the keyed set it was made from, for example spf2tu") parser.add_argument("--patches", action="store_true", help="list the patched runs") args = parser.parse_args() run = ROOT / "tests" / "mame_traces" / args.keyed opcodes = (run / "opcodes.bin").read_bytes() program = (run / "program.bin").read_bytes() log = (run / "error.log").read_text(encoding="utf-8", errors="replace") found = re.search(r"cps2 decrypt (0x[0-9a-f]+),(0x[0-9a-f]+),(0x[0-9a-f]+),(0x[0-9a-f]+)", log) if not found: raise SystemExit(f"no 'cps2 decrypt' line in {run / 'error.log'}") lower, upper = int(found[3], 16), int(found[4], 16) phoenix = program_image(args.phoenix) span = min(len(phoenix), len(opcodes), len(program)) end = min(upper, span) same = cipher = raw = 0 patched: list[int] = [] for i in range(lower, end, 2): word, dec, enc = phoenix[i : i + 2], opcodes[i : i + 2], program[i : i + 2] if dec == enc: same += 1 elif word == dec: cipher += 1 elif word == enc: raw += 1 else: patched.append(i) outside = sum(phoenix[i : i + 2] != program[i : i + 2] for i in range(end, span, 2)) print(f"{args.phoenix} against {args.keyed}: encrypted range {lower:#x}-{upper:#x} (bytes)") print(f" words where decryption changes nothing: {same:,}") print(f" Phoenix word == decrypted opcode: {cipher:,}") print(f" Phoenix word == raw ROM (data): {raw:,}") print(f" Phoenix word == neither (patched): {len(patched):,}") print(f" outside the range, Phoenix != raw ROM: {outside:,} of {(span - end) // 2:,} words compared") if args.patches: runs: list[list[int]] = [] for address in patched: if runs and address == runs[-1][1] + 2: runs[-1][1] = address else: runs.append([address, address]) for first, last in runs: print(f" patch {first:#08x} {(last - first) // 2 + 1} words") return 0 if __name__ == "__main__": sys.exit(main())