#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Decode a logic-analyser capture of a real 65C02 and tabulate cycles per opcode. Runs ``decode6502`` (hoglet67/6502Decoder, GPL-3.0, built outside this repository by emu-tools-gpl's 6502decoder tool since 2026-11-25: ``$EMU_TOOLS_GPL/tools/6502decoder/build/decode6502``, which scripts/build_tools.py has built) over one capture and reports, from its output: - how many instructions decoded and how many lines report a failed prediction (the decoder models the CPU and memory and checks every later sample); - for every opcode seen, the cycle counts it took **as delimited by the chip's SYNC pin** (the 16-bit captures sample SYNC, RnW, RDY and RST with the data bus), so the counts are measurements, not the decoder's table; - the reset and interrupt sequences' lengths; - where the program ended (a ``JMP *`` trap: the last address repeated). python -I scripts/decode_capture.py master dormann_d65c10 python -I scripts/decode_capture.py beebr65c02 dormann_d65c11 python -I scripts/decode_capture.py beebr65c02 clark_bcd_full python -I scripts/decode_capture.py master reset --show 12 ``machine`` picks the capture directory and the decoder options: ``master`` is a BBC Master (GTE/CMD G65SC12: no bit instructions), ``beebr65c02`` a BBC B with a Rockwell R65C02. Captures: ``reset`` is in the decoder's repository; the others are in reference/captures/hoglet-extended/ (unzip hoglet-extended_tests.zip there). The captures hold no address bus: addresses in the output are the decoder's reconstruction. """ from __future__ import annotations import argparse import gzip import os import shutil import subprocess import sys from collections import Counter, defaultdict from pathlib import Path ROOT = Path(__file__).resolve().parents[1] DECODER = ( Path(os.environ.get("EMU_TOOLS_GPL", "$EMU_TOOLS_GPL")) / "tools/6502decoder/build/decode6502" ) CAPTURES = ( ROOT / "reference" / "src" / "6502Decoder" / "test", ROOT / "reference" / "captures" / "hoglet-extended", ) OPTIONS = { "master": ["--machine=master"], "beebr65c02": ["--machine=beeb", "--cpu=r65c02"], "beeb": ["--machine=beeb"], "elk": ["--machine=elk"], } def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("machine", choices=sorted(OPTIONS)) parser.add_argument( "capture", help="reset, dormann_d65c10, dormann_d65c11, clark_bcd_full, ..." ) parser.add_argument("--show", type=int, default=0, help="print the first N decoded lines") args = parser.parse_args() for base in CAPTURES: packed = base / args.machine / f"{args.capture}.bin.gz" if packed.exists(): break else: raise SystemExit(f"no capture {args.machine}/{args.capture}.bin.gz under reference/") if not DECODER.exists(): print(f"{DECODER} not found: set EMU_TOOLS_GPL, then python -I scripts/build_tools.py " "--only decoder", file=sys.stderr) # fmt: skip return 3 raw = ROOT / "reference" / "build" / f"{args.machine}_{args.capture}.bin" if not raw.exists(): with gzip.open(packed, "rb") as source, raw.open("wb") as target: shutil.copyfileobj(source, target, 1 << 20) command = [ str(DECODER), "--phi2=", "--mem=00F", *OPTIONS[args.machine], "-a", "-h", "-i", "-y", str(raw), ] process = subprocess.Popen(command, stdout=subprocess.PIPE, text=True, errors="replace") cycles: dict[str, Counter] = defaultdict(Counter) names: dict[str, str] = {} special: dict[str, Counter] = defaultdict(Counter) instructions = failures = shown = 0 last = [] assert process.stdout is not None for line in process.stdout: if "failed" in line: failures += 1 fields = [field.strip() for field in line.split(" : ")] if len(fields) < 4 or not fields[3].isdigit(): continue if shown < args.show: print(line.rstrip()) shown += 1 count = int(fields[3]) if "!!" in fields[2]: special[fields[2]][count] += 1 continue instructions += 1 opcode = fields[1][:2] cycles[opcode][count] += 1 names.setdefault(opcode, " ".join(fields[2].split()[:1])) last = (last + [fields[0]])[-3:] process.wait() print( f"{args.machine}/{args.capture}: {instructions} instructions, {failures} lines with 'failed'" ) for name, counter in special.items(): print(f" {name}: " + ", ".join(f"{n} cycles x{k}" for n, k in sorted(counter.items()))) print(f" last addresses: {' '.join(last)}") print("opcode mnemonic cycles(xcount)") for opcode in sorted(cycles): seen = " ".join(f"{n}(x{k})" for n, k in sorted(cycles[opcode].items())) print(f" {opcode} {names[opcode]:<5} {seen}") return 0 if __name__ == "__main__": sys.exit(main())