#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Survey the eight SNES uPD7725/uPD96050 programs: formats, instruction mix, contested fields. Reads MAME's device sets in place (BYOR; nothing is copied or written but the JSON report): ``sns_dsp1leg.zip`` ... ``sns_seta11leg.zip`` from the folders on ``MAME_ROMPATH`` (``;``-separated, as MAME's ``-rompath``). Each holds one image in the PROM's own byte layout (the uPD77P25 data sheet, "Figure 13. Instruction ROM"): every program word is three big-endian bytes and one dummy byte, then the data ROM as big-endian 16-bit words at byte $2000 (uPD7725) or $10000 (uPD96050) - fullsnes' "Oldest Files" format, and the layout MAME's ``bus/snes/upd.cpp`` ``get_prg`` reads. python -I scripts/survey_programs.py # print the table python -I scripts/survey_programs.py --json out.json # and keep the counts Static counts (every program word, reachable or not), for docs/validation.md and the C-items in docs/undocumented-behavior.md: - instruction types OP/RT/JP/LD; ALU ops; P select; SRC and DST fields; DPL/DPHM/RPDCR use; BRCH codes; - the combinations the sources disagree on or prohibit: an ALU op whose DST is its own accumulator (the data sheet makes the ALU a NOP: C-entry), DST=DP with a DP modify, DST=RP with RPDEC, SRC=DST, P=RAM with DST=@MEM, @KLR/@KLM with SRC=K/L, SGN (SRC 7), serial sources/destinations, JMPSO, the uPD96050-only BRCH codes and NA bank bits on the uPD7725; - the data ROM's SHA-1 and the "JRQM $" signature fullsnes uses to tell formats. """ from __future__ import annotations import argparse import hashlib import json import os import sys import zipfile from collections import Counter from pathlib import Path #: The folders on MAME_ROMPATH (';'-separated, as MAME's -rompath). ROMPATH = [Path(part) for part in os.environ.get("MAME_ROMPATH", "").split(";") if part.strip()] def find_set(set_name: str) -> Path | None: """The first ``.zip`` on MAME_ROMPATH, or None.""" for folder in ROMPATH: if (folder / f"{set_name}.zip").exists(): return folder / f"{set_name}.zip" return None # set name -> (member, chip, program words, data words) PROGRAMS = { "sns_dsp1leg": ("dsp1.bin", "uPD7725", 2048, 1024), "sns_dsp1bleg": ("dsp1b.bin", "uPD7725", 2048, 1024), "sns_dsp2leg": ("dsp2.bin", "uPD7725", 2048, 1024), "sns_dsp3leg": ("dsp3.bin", "uPD7725", 2048, 1024), "sns_dsp4leg": ("dsp4.bin", "uPD7725", 2048, 1024), "sns_seta10leg": ("st010.bin", "uPD96050", 16384, 2048), "sns_seta11leg": ("st011.bin", "uPD96050", 16384, 2048), } # sns_dsp1leg_hi holds the same dsp1.bin as sns_dsp1leg (checked by SHA-1 below) # The SHA-1 MAME 0.285 names for each image (src/devices/bus/snes/upd.cpp ROM_LOAD). MAME_SHA1 = { "sns_dsp1leg": "0a03ccb1fd2bea91151c745a4d1f217ae784f889", "sns_dsp1bleg": "3a218b0e4572a8eba6d0121b17fdac9529609220", "sns_dsp2leg": "06dd9fcb118d18f6bbe234e013cb8780e06d6e63", "sns_dsp3leg": "1b133741fad810eb7320c21ecfdd427d25a46da1", "sns_dsp4leg": "76fd25f7dc26c3b3f7868a3aa78c7684068713e5", "sns_seta10leg": "cc1984e989cb94e3dcbb5f99e085b5414e18a017", "sns_seta11leg": "1375b8c1efc8cae4962b57dfe22f6b78e1ddacc8", } BINARY = {1, 2, 3, 4, 5, 6, 7} # the ALU ops that read P (OR ... ADC); the rest ignore it ALU = [ "NOP", "OR", "AND", "XOR", "SUB", "ADD", "SBB", "ADC", "DEC", "INC", "CMP", "SHR1", "SHL1", "SHL2", "SHL4", "XCHG", ] SRC = [ "TRB", "A", "B", "TR", "DP", "RP", "RO", "SGN", "DR", "DRNF", "SR", "SIM", "SIL", "K", "L", "MEM", ] DST = [ "NON", "A", "B", "TR", "DP", "RP", "DR", "SR", "SOL", "SOM", "K", "KLR", "KLM", "L", "TRB", "MEM", ] PSEL = ["RAM", "IDB", "M", "N"] BRCH = { 0x000: "JMPSO", 0x100: "JMP", 0x101: "HJMP", 0x140: "CALL", 0x141: "HCALL", 0x080: "JNCA", 0x082: "JCA", 0x084: "JNCB", 0x086: "JCB", 0x088: "JNZA", 0x08A: "JZA", 0x08C: "JNZB", 0x08E: "JZB", 0x090: "JNOVA0", 0x092: "JOVA0", 0x094: "JNOVB0", 0x096: "JOVB0", 0x098: "JNOVA1", 0x09A: "JOVA1", 0x09C: "JNOVB1", 0x09E: "JOVB1", 0x0A0: "JNSA0", 0x0A2: "JSA0", 0x0A4: "JNSB0", 0x0A6: "JSB0", 0x0A8: "JNSA1", 0x0AA: "JSA1", 0x0AC: "JNSB1", 0x0AE: "JSB1", 0x0B0: "JDPL0", 0x0B1: "JDPLN0", 0x0B2: "JDPLF", 0x0B3: "JDPLNF", 0x0B4: "JNSIAK", 0x0B6: "JSIAK", 0x0B8: "JNSOAK", 0x0BA: "JSOAK", 0x0BC: "JNRQM", 0x0BE: "JRQM", } # fmt: skip def load(set_name: str) -> tuple[bytes, str]: member = PROGRAMS.get(set_name, PROGRAMS["sns_dsp1leg"])[0] path = find_set(set_name) if path is None: raise SystemExit(f"{set_name}.zip is not on MAME_ROMPATH; bring your own") with zipfile.ZipFile(path) as archive: data = archive.read(member) return data, hashlib.sha1(data).hexdigest() def words(image: bytes, count: int) -> list[int]: return [int.from_bytes(image[4 * i : 4 * i + 3], "big") for i in range(count)] def survey(set_name: str) -> dict: member, chip, program_words, data_words = PROGRAMS[set_name] image, sha1 = load(set_name) program = words(image, program_words) data_at = 4 * program_words data = image[data_at : data_at + 2 * data_words] pad = Counter(image[4 * i + 3] for i in range(program_words)) # The program's length: the last word that is not 0 and not all ones. used = max((i for i, w in enumerate(program) if w not in (0, 0xFFFFFF)), default=-1) + 1 report: dict = { "set": set_name, "member": member, "chip": chip, "bytes": len(image), "sha1": sha1, "matches_mame": sha1 == MAME_SHA1[set_name], "data_rom_sha1": hashlib.sha1(data).hexdigest(), "pad_bytes": dict(pad), "first_words": [f"{w:06X}" for w in program[:4]], # fullsnes: "All existing ROMs contain 'JRQM $' within first four opcodes". "jrqm_self_in_first_four": any(w >> 13 == 0x4BE and (w >> 2 & 0x7FF) == i for i, w in enumerate(program[:4])), "words_used": used, } # fmt: skip kinds: Counter = Counter() alu: Counter = Counter() psel: Counter = Counter() src: Counter = Counter() dst: Counter = Counter() brch: Counter = Counter() flags: Counter = Counter() for word in program[:used]: kind = word >> 22 if kind in (0, 1): kinds["RT" if kind else "OP"] += 1 op, s, d = word >> 16 & 15, word >> 4 & 15, word & 15 asl, dpl, dphm, rpdcr = word >> 15 & 1, word >> 13 & 3, word >> 9 & 15, word >> 8 & 1 p = word >> 20 & 3 alu[ALU[op]] += 1 src[SRC[s]] += 1 dst[DST[d]] += 1 if op: psel[PSEL[p]] += 1 if d == 1 + asl: flags["alu_dst_is_own_acc"] += 1 if p == 0 and d == 15: flags["psel_ram_with_dst_mem (prohibited)"] += 1 if op in BINARY: flags[" of which a binary op that reads P"] += 1 if op in (6, 7, 12): flags["uses_other_carry (SBB/ADC/SHL1)"] += 1 if dpl: flags[f"dpl_{['', 'inc', 'dec', 'clr'][dpl]}"] += 1 if dphm: flags["dphm_nonzero"] += 1 if dphm & 8: flags["dphm_M8_MF (bit 7 of DP)"] += 1 if rpdcr: flags["rpdec"] += 1 if d == 4 and (dpl or dphm): flags["dst_dp_with_dp_modify"] += 1 if d == 5 and rpdcr: flags["dst_rp_with_rpdec"] += 1 if d in (11, 12) and s in (13, 14): flags["klr_klm_from_k_or_l (prohibited)"] += 1 if SRC[s] == DST[d] and d not in (0,): flags["src_equals_dst (prohibited)"] += 1 if s == 7: flags["src_sgn"] += 1 if s in (11, 12) or d in (8, 9): flags["serial_io"] += 1 if s == 9: flags["src_drnf"] += 1 if d == 7: flags["dst_sr (MOV)"] += 1 elif kind == 2: kinds["JP"] += 1 code = word >> 13 & 0x1FF brch[BRCH.get(code, f"?{code:03X}")] += 1 if word & 3: flags["jp_bank_bits_set"] += 1 if code in (0x000, 0x101, 0x141): flags["uPD96050_only_brch"] += 1 else: kinds["LD"] += 1 d = word & 15 dst[f"LD:{DST[d]}"] += 1 if word >> 4 & 3: flags["ld_reserved_bits_set"] += 1 if d == 7: flags["ld_sr"] += 1 report.setdefault("ld_sr_values", set()).add(f"{word >> 6 & 0xFFFF:04X}") report["ld_sr_values"] = sorted(report.get("ld_sr_values", [])) for name, counter in (("kinds", kinds), ("alu", alu), ("psel", psel), ("src", src), ("dst", dst), ("brch", brch), ("flags", flags)): # fmt: skip report[name] = dict(counter.most_common()) return report def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--json", type=Path, help="write the full report here") args = parser.parse_args() if find_set("sns_dsp1leg") is None: print("no MAME device sets on MAME_ROMPATH; bring your own", file=sys.stderr) return 1 reports = [survey(name) for name in PROGRAMS] hi = load("sns_dsp1leg_hi")[1] same = hi == reports[0]["sha1"] print( f"sns_dsp1leg_hi dsp1.bin is {'identical to' if same else 'DIFFERENT from'} sns_dsp1leg's" ) for r in reports: match = "matches MAME" if r["matches_mame"] else "DIFFERS from MAME's hash" print(f"\n== {r['set']} ({r['chip']}, {r['bytes']} bytes, SHA-1 {r['sha1'][:12]} {match}, " f"{r['words_used']} words used, pad {r['pad_bytes']}, first {r['first_words']})") # fmt: skip for key in ("kinds", "alu", "psel", "src", "dst", "brch", "flags", "ld_sr_values"): print(f" {key}: {r[key]}") if args.json: args.json.write_text(json.dumps(reports, indent=1) + "\n", encoding="utf-8") return 0 if __name__ == "__main__": sys.exit(main())