#!/usr/bin/env python3 """Check the monitor's disassembler: disassemble every opcode form (host build of monitor.c), assemble each line back with sdasz80 and compare the bytes. Undocumented forms sdasz80 doesn't know are listed, not failed. monitor/test-disasm.py """ import os import re import subprocess import sys import tempfile here = os.path.dirname(os.path.abspath(__file__)) tmp = tempfile.mkdtemp() exe = os.path.join(tmp, "dis") subprocess.check_call(["gcc", "-O1", "-w", "-o", exe, os.path.join(here, "monitor.c")]) lines = subprocess.check_output([exe], text=True).splitlines() UNDOC = re.compile(r"IX[HL]|IY[HL]|SLL|NOP\*|\),[A-L]$|IN \(C\)|OUT \(C\),0|^DB |IM 0$") def to_asx(t): """Zilog text as printed by the monitor -> sdasz80 syntax.""" m = re.match(r"(\S+)\s*(.*)", t) mn, ops = m.group(1), m.group(2) out = [] for o in [x for x in ops.split(",")] if ops else []: o = re.sub(r"\b([0-9][0-9A-F]*)H\b", lambda k: "0x" + k.group(1), o) im = re.match(r"\((I[XY])([+-])(0x[0-9A-F]+)\)$", o) if im: o = ("-" if im.group(2) == "-" else "") + im.group(3) + "(" + im.group(1) + ")" elif re.match(r"0x[0-9A-F]+$", o) and mn in ("JR", "DJNZ"): o = ".+" + o # sdasz80 takes a bare number as the offset elif re.match(r"0x[0-9A-F]+$", o) and mn not in ("JP", "CALL", "RST"): o = "#" + o out.append(o) return (mn + " " + ",".join(out)).lower() def alias(hexb, text): """Undocumented duplicates, shown as the documented instruction.""" if hexb[:2] in ("DD", "FD") and hexb[2:4] != "CB" and "IX" not in text and "IY" not in text: return True # prefix with no effect if hexb[:2] == "ED" and hexb[2:4] in ("4C 54 5C 64 6C 74 7C 55 5D 65 6D 75 7D " "4E 66 6E 76 7E 63 6B").split(): return True if hexb[2:4] == "CB" and text.startswith("BIT") and int(hexb[6:8], 16) & 7 != 6: return True # DDCB BIT with a register field return False ok = bad = skipped = aliases = 0 for ln in lines: hexb, text = ln.split("\t") if UNDOC.search(text): skipped += 1 continue src = os.path.join(tmp, "t.s") with open(src, "w") as f: f.write("\t.area\tA (ABS)\n\t.org\t0\n\t%s\n" % to_asx(text)) r = subprocess.run(["sdasz80", "-l", "-o", src], capture_output=True, text=True) got = "" lst = src[:-2] + ".lst" if r.returncode == 0 and os.path.exists(lst): for l in open(lst): m = re.match(r"\s+0+\s+((?:[0-9A-F]{2}\s)+)", l) if m: got = m.group(1).replace(" ", "") if got.upper() == hexb[:len(got)].upper() and got and len(got) == len(hexb): ok += 1 elif got and alias(hexb, text): aliases += 1 else: bad += 1 print("MISMATCH %-10s %-24s asm %-22s -> %s %s" % (hexb, text, to_asx(text), got or "error", r.stderr.strip()[:60])) print("%d match, %d undocumented duplicates shown as the documented form, %d mismatch, " "%d undocumented forms sdasz80 can't assemble" % (ok, aliases, bad, skipped)) sys.exit(1 if bad else 0)