#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Survey the HG51B program inside the Mega Man X2/X3 cartridges: versions, instruction mix, contested corners. The Cx4 has no program ROM of its own: it caches 256-word pages from the cartridge ROM (fullsnes "SNES Cart Capcom CX4 - Functions": the program is at SNES 02:8000-9FFF, base register $7F49 = 028000h, pages 0000h-000Fh). This script reads each cartridge in place (``.zip`` from the No-Intro set, or a loose ``.sfc``), takes the 16 pages at LoROM file offset 10000h-11FFFh, and reports: - the SHA-1 of the program region per cartridge and which words differ between versions (fullsnes: X2 and X3 differ in two words only); - the instruction mix, decoded with byuu's table (ares ``component/processor/hg51b/instruction.cpp`` l.13-636, ISC) and named the same way, with fullsnes' names where they differ; - every use of an encoding the sources disagree on (docs/undocumented-behavior.md C-entries): opcodes fullsnes lists as unused, immediate shift counts >= 24, reads of MH/ML right after a multiply, far jumps and calls, the register operands each instruction family touches (bus port 2Eh/2Fh, PC 20h, P 28h, the mirror 70h-7Fh), ``LD P,reg`` with bits 7-4 set, stores to special registers. Nothing is written; no ROM byte leaves this process. Run with ``python -I``:: python -I scripts/survey_program.py # the default No-Intro set python -I scripts/survey_program.py --list "Mega Man X2 (USA).sfc" """ from __future__ import annotations import argparse import hashlib import os import sys import zipfile from collections import Counter from pathlib import Path NO_INTRO = Path( os.environ.get("SNES_NO_INTRO") or Path(os.environ.get("NO_INTRO_DIR", "")) / "Nintendo - Super Nintendo Entertainment System" ) # the player's own No-Intro set: SNES_NO_INTRO, or NO_INTRO_DIR's SNES directory GAMES = ( "Mega Man X2 (USA)", "Mega Man X2 (Europe)", "Rockman X2 (Japan)", "Rockman X2 (Japan) (Beta 1)", "Rockman X2 (Japan) (Beta 2)", "Mega Man X3 (USA)", "Mega Man X3 (Europe)", "Rockman X3 (Japan)", "Rockman X3 (Japan) (Beta 1)", "Rockman X3 (Japan) (Beta 2)", "Rockman X3 (Japan) (Beta 3)", ) PROGRAM = 0x10000 # LoROM file offset of SNES 02:8000 (bank 2 * 32 KiB) PAGES = 16 WORDS = PAGES * 256 SHIFTS = ( 0, 1, 8, 16, ) # the 2-bit shift field: A, A<<1, A<<8, A<<16 (ares `shifts`, fullsnes A*2/A*100h/A*10000h) JUMPS = {0x02: "JMP", 0x03: "JMP EQ", 0x04: "JMP GE", 0x05: "JMP MI", 0x06: "JMP VS"} CALLS = {0x0A: "JSR", 0x0B: "JSR EQ", 0x0C: "JSR GE", 0x0D: "JSR MI", 0x0E: "JSR VS"} ALU = { 0x20: "ADD", 0x22: "SUBR", 0x24: "SUB", 0x28: "XNOR", 0x2A: "XOR", 0x2C: "AND", 0x2E: "OR", 0x12: "CMPR", 0x14: "CMP", } # fmt: skip SHIFT_OPS = {0x30: "SHR", 0x32: "ASR", 0x34: "ROR", 0x36: "SHL"} # Encodings fullsnes "CX4 Opcodes" lists as "-" (unused/unknown) that byuu's model (ares) gives a meaning. FULLSNES_UNUSED = { 0x06: "JMP VS", 0x0E: "JSR VS", 0x1D: "RDROM imm", 0x28: "XNOR reg", 0x29: "XNOR imm", 0x3E: "CLEAR", } SPECIAL = {0x00: "A", 0x01: "MH", 0x02: "ML", 0x03: "MDR", 0x08: "ROM", 0x0C: "RAM", 0x13: "MAR", 0x1C: "DPR", 0x20: "PC", 0x28: "P", 0x2E: "BUS(ROM)", 0x2F: "BUS(RAM)"} # fmt: skip def register_name(reg: int) -> str: reg &= 0x7F # bit 7 of the operand is ignored (ares `null` in the decode; U5) if reg in SPECIAL: return SPECIAL[reg] if 0x50 <= reg <= 0x5F: return f"#K{reg & 15:X}" # the sixteen constant registers if 0x60 <= reg <= 0x6F: return f"R{reg & 15}" if 0x70 <= reg <= 0x7F: return f"R{reg & 15}'" # the mirror ares decodes; fullsnes lists only 60h-6Fh return f"?{reg:02X}" # reads 0 in ares (provisional: U5) def decode(word: int) -> tuple[str, str | None]: """(mnemonic class, register operand name or None) per byuu's table (ares instruction.cpp).""" top, sub, low = word >> 10, word >> 8 & 3, word & 0xFF if top in JUMPS: return JUMPS[top] + (" far" if word & 0x200 else ""), None if top in CALLS: return CALLS[top] + (" far" if word & 0x200 else ""), None if top == 0x07: return "WAIT", None # fullsnes "finish ext_dta" if top == 0x09: return "SKIP " + ("V", "C", "Z", "N")[sub] + ("1" if word & 1 else "0"), None if top == 0x0F: return "RTS", None if top == 0x10: return "INC MAR", None if top in ALU: return f"{ALU[top]} A<<{SHIFTS[sub]},reg", register_name(low) if top - 1 in ALU: return f"{ALU[top - 1]} A<<{SHIFTS[sub]},imm", None if top == 0x16: return ("NOP(58)", "SXB", "SXW", "NOP(5B)")[sub], None if top == 0x18: dest = ("A", "MDR", "MAR", "P")[sub] if dest == "P": return "LD P,Rn" + (" (bits 7-4 set)" if low & 0xF0 else ""), f"R{low & 15}" return f"LD {dest},reg", register_name(low) if top == 0x19: return f"LD {('A', 'MDR', 'MAR', 'P')[sub]},imm", None if top == 0x1A: return (f"RDRAM {sub},A" if sub < 3 else "NOP(6B)"), None if top == 0x1B: return (f"RDRAM {sub},DPR+imm" if sub < 3 else "NOP(6F)"), None if top == 0x1C: return "RDROM A", None if top == 0x1D: return "RDROM imm", None if top == 0x1F: return ("LD PL,imm", "LD PH,imm", "NOP(7E)", "NOP(7F)")[sub], None if top in (0x26, 0x27): return ("MUL reg", register_name(low)) if top == 0x26 else ("MUL imm", None) if top in SHIFT_OPS: return f"{SHIFT_OPS[top]} reg", register_name(low) if top - 1 in SHIFT_OPS: return f"{SHIFT_OPS[top - 1]} imm", None if top == 0x38: return ("ST reg,A", "ST reg,MDR", "NOP(E2)", "NOP(E3)")[sub], ( register_name(low) if sub < 2 else None ) if top == 0x3A: return (f"WRRAM {sub},A" if sub < 3 else "NOP(EB)"), None if top == 0x3B: return (f"WRRAM {sub},DPR+imm" if sub < 3 else "NOP(EF)"), None if top == 0x3C: return "SWAP A,Rn", None if top == 0x3E: return "CLEAR", None if top == 0x3F: return "HALT", None return ( f"NOP({word >> 8 & 0xFC:02X})", None, ) # 0000h, 0400h, 2000h, 4400h, 5C00h, 7800h, E400h, F400h def read_rom(path: Path) -> bytes: if path.suffix.lower() == ".zip": with zipfile.ZipFile(path) as archive: name = next(n for n in archive.namelist() if n.lower().endswith((".sfc", ".smc"))) data = archive.read(name) else: data = path.read_bytes() return data[512:] if len(data) % 0x8000 == 512 else data # a copier header def program_words(rom: bytes) -> list[int]: region = rom[PROGRAM : PROGRAM + WORDS * 2] return [ region[i] | region[i + 1] << 8 for i in range(0, len(region), 2) ] # little-endian (fullsnes) FLAG_SETTERS = ( set(ALU) | {t + 1 for t in ALU} | set(SHIFT_OPS) | {t + 1 for t in SHIFT_OPS} | {0x16} ) FLAG_READERS = {0x03, 0x04, 0x05, 0x06, 0x09, 0x0B, 0x0C, 0x0D, 0x0E} def flags_reader(words: list[int], at: int) -> str: """The first later instruction (straight-line, up to 8) that reads the flags, or 'none'.""" for follower in words[at + 1 : at + 9]: top = follower >> 10 if top in FLAG_READERS: return decode(follower)[0].replace(" far", "") if top in FLAG_SETTERS or top in (0x02, 0x0A, 0x0F, 0x3F): # overwritten, or control leaves return "none" return "none" def survey(words: list[int]) -> dict: mix: Counter[str] = Counter() operands: Counter[str] = Counter() notes: Counter[str] = Counter() for at, word in enumerate(words): name, operand = decode(word) mix[name.split(" (")[0]] += 1 if operand: operands[f"{name.split(',')[0]} <- {operand}"] += 1 if ( operand in ("PC", "P", "BUS(ROM)", "BUS(RAM)") or operand.startswith("?") or operand.endswith("'") ): notes[f"register operand {operand} in {name}"] += 1 top = word >> 10 if top in FULLSNES_UNUSED: notes[f"{FULLSNES_UNUSED[top]} (fullsnes: unused)"] += 1 if name.startswith("NOP(") and word != 0: notes[f"non-zero NOP encoding {word:04X}"] += 1 if top - 1 in SHIFT_OPS and word & 0x1F >= 24: notes[f"{SHIFT_OPS[top - 1]} imm by {word & 0x1F} (>= 24)"] += 1 if top in (0x26, 0x27) and at + 1 < len(words): follower, operand2 = decode(words[at + 1]) if operand2 in ("MH", "ML"): notes[f"MH/ML read right after MUL ({follower})"] += 1 if ( top in (0x20, 0x22, 0x24, 0x12, 0x14) or top - 1 in (0x20, 0x22, 0x24, 0x12, 0x14) ) and word >> 8 & 3: # A< 0: cut to 24 bits before the ALU in byuu's model (ares); C2. reader = flags_reader(words, at) notes[ f"shifted {ALU.get(top) or ALU.get(top - 1)} A<<{SHIFTS[word >> 8 & 3]}, flags then read by {reader}" ] += 1 if "far" in name: notes["far jump/call (P -> program page)"] += 1 if name == "LD P,Rn (bits 7-4 set)": notes["LD P,Rn with bits 7-4 set"] += 1 if name.startswith("ST") and operand in ("PC", "P", "BUS(ROM)", "BUS(RAM)", "MH", "ML"): notes[f"store to {operand}"] += 1 return {"mix": mix, "operands": operands, "notes": notes} def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument( "roms", nargs="*", type=Path, help="cartridges (default: the No-Intro Cx4 set)" ) parser.add_argument( "--list", action="store_true", help="print the instruction mix and operands in full" ) args = parser.parse_args() paths = args.roms or [NO_INTRO / f"{g}.zip" for g in GAMES] reference: list[int] | None = None shown = False for path in paths: if not path.exists(): print(f"missing: {path.name}") continue rom = read_rom(path) words = program_words(rom) digest = hashlib.sha1(rom[PROGRAM : PROGRAM + WORDS * 2]).hexdigest() line = f"{path.stem:34s} rom {len(rom):8d} program sha1 {digest[:16]}" if reference is None: reference = words else: diff = [i for i in range(WORDS) if words[i] != reference[i]] where = ", ".join( f"{i >> 8:04X}:{i & 0xFF:02X} {reference[i]:04X}->{words[i]:04X}" for i in diff[:4] ) line += f" differs from the first in {len(diff)} words {where}" print(line) if not shown: shown = True result = survey(words) halts = [i for i, w in enumerate(words) if w >> 10 == 0x3F] print(f" {WORDS} words; HALT at {len(halts)} places; all-zero words {words.count(0)}") print(" contested or rare encodings (count):") for note, count in sorted(result["notes"].items()): print(f" {count:5d} {note}") if args.list: print(" instruction mix:") for name, count in result["mix"].most_common(): print(f" {count:5d} {name}") print(" register operands:") for name, count in sorted(result["operands"].items()): print(f" {count:5d} {name}") return 0 if __name__ == "__main__": sys.exit(main())