#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Compare ``arm7tdmi_python.disasm`` with mGBA's, MAME's and GNU objdump's disassemblers, and assemble its text back with GNU as. The three disassemblers are **detectors**, not judges: they are other people's reading of the same encodings, and no hardware decides how an instruction is written down. The judges of the decode are the data sheet's encoding diagrams and the core's own tables, which the disassembler shares; what this script finds is text that a second reader would not write. The **round trip** is the one check with a pass/fail answer: our text for a standard encoding, given to an assembler, must give back the same bits. - mGBA: the pinned tree's ``src/arm/decoder*.c`` behind ``referees/mgba/mgba_disasm.c`` (``reference/build/mgba_disasm``, built by ``scripts/build_referees.py``). - MAME: ``unidasm -arch arm7`` / ``arm7thumb``, MAME 0.285 (the pinned tree's version; the Debian ``mame-tools`` package provides the binary). - GNU binutils: ``arm-none-eabi-objdump -m armv4t`` and ``arm-none-eabi-as`` from the Arm GNU Toolchain 14.3.rel1 that gba-python pins (read in place, ``--binutils`` to point elsewhere; skipped when absent). Every Thumb halfword (65,536) is compared, and an ARM sample of 32 words per decode-table index (131,072 words; 24 of the 32 with condition AL, the rest any condition, seeded so the run repeats). Each side is reduced to a canonical form (lower case, ``R13``-``R15`` as names, numbers as integers, register lists as sets), then the **syntax rules** below rewrite notation that differs without meaning anything different; what still differs must match a **disagreement rule**, a named difference in what the encoding means, each explained in docs/disassembly.md. Anything left is *unexplained* and fails the run. The round trip leaves out the encodings that are not standard ARMv4T (undefined, nonstandard, NV, LDRD/STRD, lone BL halves, the reserved Thumb forms, unpredictable ones); a standard encoding that does not come back exact must match a named class, or it fails the run too. python scripts/build_referees.py # builds reference/build/mgba_disasm python scripts/disasm_judge.py # every tool, both states python scripts/disasm_judge.py --tool mgba --state thumb --examples 5 python scripts/disasm_judge.py --tool gas --binutils /path/to/arm-none-eabi/bin """ from __future__ import annotations import argparse import collections import random import re import shutil import struct import subprocess import sys import tempfile from collections.abc import Callable from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from arm7tdmi_python._tables import ARM_HANDLERS, THUMB_HANDLERS # noqa: E402 from arm7tdmi_python.disasm import ( # noqa: E402 NONSTANDARD, Instruction, disassemble_arm, disassemble_thumb, ) MGBA = ROOT / "reference" / "build" / "mgba_disasm" # gba-python pins the Arm GNU Toolchain; the core reads it in place rather than pinning a copy BINUTILS = ( ROOT.parent / "gba-python/reference/tools/arm-gnu-toolchain-14.3.rel1-x86_64-arm-none-eabi/bin" ) NAMES = {"sp": 13, "lr": 14, "pc": 15} NUMBERS = {13: "sp", 14: "lr", 15: "pc"} # ---------------------------------------------------------------------- canonical form def _register_number(name: str) -> int: return NAMES[name] if name in NAMES else int(name[1:]) def _register_set(match: re.Match[str]) -> str: if not re.fullmatch(r"[\s,\-]*((r\d+|sp|lr|pc)[\s,\-]*)*", match.group(1)): return match.group(0) # not a register list (objdump's ``nop {6}`` hint) registers: set[int] = set() for part in match.group(1).split(","): part = part.strip() if not part: continue if "-" in part: first, last = (_register_number(p) for p in part.split("-")) registers.update(range(first, last + 1)) else: registers.add(_register_number(part)) return "{" + ",".join(NUMBERS.get(r, f"r{r}") for r in sorted(registers)) + "}" def _number(match: re.Match[str]) -> str: text = match.group(0) return str(int(text, 16) if text.startswith("0x") else int(text)) def canon(text: str) -> str: """Lower case, no comment, no ``#``, aliases for R13-R15, numbers in decimal, register lists as sorted sets, no spaces after commas.""" text = text.lower().split(";")[0] text = re.sub(r"\br1([345])\b", lambda m: NUMBERS[int("1" + m.group(1))], text) text = text.replace("#", "") text = re.sub(r"0x[0-9a-f]+|(? tuple[str, list[str]]: mnemonic, _, rest = text.partition(" ") return mnemonic, _operands(rest) def _operands(rest: str) -> list[str]: """Split on commas outside brackets and braces.""" parts, depth, current = [], 0, "" for char in rest: if char in "[{": depth += 1 elif char in "]}": depth -= 1 if char == "," and depth == 0: parts.append(current) current = "" else: current += char if current: parts.append(current) return parts def _join(mnemonic: str, operands: list[str]) -> str: return mnemonic if not operands else f"{mnemonic} {','.join(operands)}" # ---------------------------------------------------------------------- the rules # A syntax rule takes (instruction, handler, ours, theirs) in canonical form and returns the # pair rewritten, or None when it does not apply. They run in order, each on the output of # the last, until the two sides are equal. SyntaxRule = Callable[[Instruction, str, str, str], "tuple[str, str] | None"] # A disagreement rule says whether a remaining difference is a known one. DisagreementRule = Callable[[Instruction, str, str, str], bool] CONDS = ["eq", "ne", "cs", "cc", "mi", "pl", "vs", "vc", "hi", "ls", "ge", "lt", "gt", "le", "nv"] DATA = [ "and", "eor", "sub", "rsb", "add", "adc", "sbc", "rsc", "tst", "teq", "cmp", "cmn", "orr", "mov", "bic", "mvn", ] def plain_immediate(ins, handler, ours, theirs): """Ours writes ``#imm8, rot`` when the encoding is not the smallest rotation (the rotation decides the shifter's carry); the tools write the value.""" if ins.thumb or not (handler[5:] in DATA or handler == "_arm_msr"): return None mnemonic, operands = _split(ours) if len(operands) >= 2 and operands[-1].isdigit() and operands[-2].isdigit(): imm8, rot = int(operands[-2]), int(operands[-1]) value = ((imm8 >> rot) | (imm8 << (32 - rot))) & 0xFFFFFFFF return _join(mnemonic, [*operands[:-2], str(value)]), theirs return None def unsigned_immediate(ins, handler, ours, theirs): """mGBA prints a data-processing immediate as a signed 32-bit number.""" if handler[5:] in DATA or handler == "_arm_msr": fixed = re.sub(r"(?<=[ ,])-(\d+)$", lambda m: str((-int(m.group(1))) & 0xFFFFFFFF), theirs) return (ours, fixed) if fixed != theirs else None return None def _text(mnemonic: str, operands: tuple[str, ...]) -> str: return mnemonic if not operands else f"{mnemonic} {', '.join(operands)}" def condition_dropped(ins, handler, ours, theirs): """mGBA ignores condition NV and prints the instruction unconditional.""" if ins.thumb or ins.data[3] >> 4 != 0xF: return None name = handler[5:] base = name[:3] if name[:3] in ("ldr", "str", "und") else name mnemonic, operands = _split(ours) if mnemonic.startswith(base + "nv"): return _join(base + mnemonic[len(base) + 2 :], operands), theirs return None def compare_p(ins, handler, ours, theirs): """Ours marks a compare with Rd = R15 ``TEQP`` (it also restores CPSR, U13); the tools ignore Rd.""" if handler[5:] in ("tst", "teq", "cmp", "cmn"): mnemonic, operands = _split(ours) if mnemonic.endswith("p"): return _join(mnemonic[:-1], operands), theirs return None def _resolve(ins, ours, bracketed): if not ins.comment.startswith("="): return None address = str(int(re.match(r"=\[?(0x[0-9A-F]+)", ins.comment).group(1), 16)) mnemonic, operands = _split(ours) last = operands[-1] if operands else "" if last.startswith("[pc") and last.rstrip("!").endswith("]"): bang = "!" if last.endswith("!") else "" form = f"[{address}]{bang}" if bracketed else f"{address}{bang}" return _join(mnemonic, [*operands[:-1], form]) if mnemonic.startswith(("add", "sub")) and len(operands) == 3 and operands[1] == "pc": return None if bracketed else _join("adr" + mnemonic[3:], [operands[0], address]) return None def resolve_pc_relative(ins, handler, ours, theirs): """mGBA prints the address a PC-relative load uses, in brackets, where ours prints the operand and puts the address in the comment.""" text = _resolve(ins, ours, bracketed=True) if text is None and ins.thumb and ins.mnemonic == "ADD" and ins.operands[1] == "PC": text = _join("mov", [_split(ours)[1][0], "pc"]) if theirs.startswith("mov") else None return None if text is None else (text, theirs) def mame_pc_relative(ins, handler, ours, theirs): """MAME prints the address a PC-relative load uses bare, and ``ADD Rd, PC, #n`` as ``ADR Rd, address``.""" text = _resolve(ins, ours, bracketed=False) return None if text is None else (text, theirs) def zero_offset(ins, handler, ours, theirs): """``[Rn, #0]`` and ``[Rn]`` are the same operand, and so is ours ``[Rn, #-0x0]`` (U clear, which ours keeps visible). The tools also print a post-indexed zero offset, ours ``[Rn], #0x0``, as ``[Rn]``: the address and the base end up the same.""" fixed = re.sub(r"\[(\w+),-?0\]", r"[\1]", theirs) mine = re.sub(r"\[(\w+),-0\]|\[(\w+)\],-?0$", lambda m: f"[{m.group(1) or m.group(2)}]", ours) return (mine, fixed) if (mine, fixed) != (ours, theirs) else None def psr_fields(ins, handler, ours, theirs): """MSR field letters in any order.""" def sort(text): return re.sub( r"(cpsr|spsr)_([a-z]+)", lambda m: f"{m.group(1)}_{''.join(sorted(m.group(2)))}", text ) a, b = sort(ours), sort(theirs) return (a, b) if (a, b) != (ours, theirs) else None def thumb_aliases(ins, handler, ours, theirs): """PUSH/POP for STMDB SP!/LDMIA SP!, ``ADD SP, #-n`` for ``SUB SP, #n``, ``LSR``/``ASR #32`` (what immediate 0 means, U10) for ``#0``, ``ADD Rd, Rs, #0`` for ``MOV Rd, Rs``.""" mnemonic, operands = _split(ours) candidates = [] if mnemonic == "push": candidates.append(_join("stmdb", ["sp!", *operands])) if mnemonic == "pop": candidates.append(_join("ldmia", ["sp!", *operands])) if mnemonic == "add" and operands[:1] == ["sp"] and operands[1].startswith("-"): candidates.append(_join("sub", ["sp", operands[1][1:]])) if mnemonic in ("lsr", "asr") and operands[-1] == "32": candidates.append(_join(mnemonic, [*operands[:-1], "0"])) if mnemonic == "add" and len(operands) == 3 and operands[2] == "0": candidates.append(_join("mov", operands[:2])) return next(((c, theirs) for c in candidates if c == theirs), None) def mgba_bl_half(ins, handler, ours, theirs): """mGBA prints a lone BL half as ``bl`` with no operand.""" if ins.mnemonic in ("BL.HI", "BL.LO") and theirs == "bl": return theirs, theirs return None def mame_bl_half(ins, handler, ours, theirs): """MAME prints a lone BL half as ``BL (HI)`` with the offset shifted into place.""" if ins.mnemonic not in ("BL.HI", "BL.LO"): return None imm = int.from_bytes(ins.data[:2], "little") & 0x7FF if ins.mnemonic == "BL.HI": value = ((imm - 0x800 if imm & 0x400 else imm) << 12) & 0xFFFFFFFF return f"bl (hi) {value}", theirs return f"bl (lo) {imm << 1}", theirs def undefined_ill(ins, handler, ours, theirs): """``UND`` is mGBA's ``ill``.""" mnemonic, _ = _split(ours) if mnemonic.startswith("und") and theirs.startswith("ill"): return "ill" + mnemonic[3:], theirs return None def mame_two_operand(ins, handler, ours, theirs): """MAME drops the first source when it equals the destination: ``ADD R4, R10, LSL #2`` for ``ADD R4, R4, R10, LSL #2``.""" mnemonic, operands = _split(ours) if ( len(operands) >= 3 and operands[0] == operands[1] and not mnemonic.startswith(("mul", "mla", "umul", "umla", "smul", "smla")) ): return _join(mnemonic, [operands[0], *operands[2:]]), theirs return None _SUFFIXES = ("sb", "sh", "h", "d", "b", "t", "bt") def mame_condition_last(ins, handler, ours, theirs): """MAME writes the condition after the size (``LDRSBMI``, ``STRHLT``, ``LDRDNE``, as UAL does); ours puts it before, as the data sheet does (``LDRMISB``).""" mnemonic, operands = _split(ours) match = re.fullmatch(r"(ldr|str)(" + "|".join(CONDS) + r")(sb|sh|h|d)", mnemonic) if match: return _join(match.group(1) + match.group(3) + match.group(2), operands), theirs return None _STACK = { # (load, addressing mode) -> MAME's stack name when the base is SP ("ldm", "ia"): "fd", ("ldm", "ib"): "ed", ("ldm", "da"): "fa", ("ldm", "db"): "ea", ("stm", "ia"): "ea", ("stm", "ib"): "fa", ("stm", "da"): "ed", ("stm", "db"): "fd", } def mame_stack_names(ins, handler, ours, theirs): """With SP as the base MAME writes the stack names (``LDMFD SP!``), DS figure 4-18.""" mnemonic, operands = _split(ours) match = re.fullmatch(r"(ldm|stm)(\w\w)?(ia|ib|da|db)", mnemonic) if match and operands and operands[0].startswith("sp"): stack = _STACK[(match.group(1), match.group(3))] return _join(match.group(1) + (match.group(2) or "") + stack, operands), theirs return None def mame_shift_mnemonic(ins, handler, ours, theirs): """MAME writes ``MOV Rd, Rm, LSL #n`` as ``LSL Rd, Rm, #n`` (UAL's form).""" mnemonic, operands = _split(ours) match = re.fullmatch(r"mov(\w\w)?(s)?", mnemonic) if match and len(operands) == 3 and operands[2][:3] in ("lsl", "lsr", "asr", "ror"): shift, _, amount = operands[2].partition(" ") new = shift + (match.group(1) or "") + (match.group(2) or "") return _join(new, [operands[0], operands[1], amount]), theirs if match and len(operands) == 3 and operands[2] == "rrx": return _join("rrx" + (match.group(1) or "") + (match.group(2) or ""), operands[:2]), theirs return None def mame_empty_mask(ins, handler, ours, theirs): """MSR with no fields: MAME writes ``CPSR_``, ours ``CPSR`` (and says so in the comment).""" fixed = re.sub(r"\b(cpsr|spsr)_(?=,|$)", r"\1", theirs) return (ours, fixed) if fixed != theirs else None def mame_cdp_opc2(ins, handler, ours, theirs): """MAME leaves out CDP's opcode 2 when it is 0.""" mnemonic, operands = _split(ours) if mnemonic.startswith("cdp") and operands[-1] == "0": return _join(mnemonic, operands[:-1]), theirs return None def mame_thumb_short(ins, handler, ours, theirs): """MAME writes a Thumb ``LSL Rd, Rs, #n`` / ``ADD Rd, Rs, Rn`` with Rd = Rs as two operands (``LSL R0, #0``).""" mnemonic, operands = _split(ours) if len(operands) == 3 and operands[0] == operands[1]: return _join(mnemonic, [operands[0], operands[2]]), theirs return None def ual_coprocessor_post(ins, handler, ours, theirs): """A post-indexed LDC/STC with write-back: DS 4.15 writes ``[Rn], #off!``, UAL and MAME ``[Rn], #off`` (UAL has no post-indexed form without write-back; MAME prints W = 0 the same way, so its text does not tell the two apart).""" if handler in ("_arm_ldc", "_arm_stc") and ours.endswith("!") and "]," in ours: return ours[:-1], theirs return None MGBA_SYNTAX: list[SyntaxRule] = [ plain_immediate, unsigned_immediate, condition_dropped, compare_p, resolve_pc_relative, zero_offset, psr_fields, thumb_aliases, mgba_bl_half, undefined_ill, ] MAME_SYNTAX: list[SyntaxRule] = [ plain_immediate, compare_p, mame_pc_relative, ual_coprocessor_post, zero_offset, psr_fields, mame_bl_half, mame_condition_last, mame_stack_names, mame_shift_mnemonic, mame_cdp_opc2, mame_empty_mask, mame_two_operand, thumb_aliases, mame_thumb_short, ] def _candidates_equal(candidates, theirs): return next(((c, theirs) for c in candidates if c == theirs), None) _UAL_BASES = "|".join( [ *DATA, "mul", "mla", "umull", "umlal", "smull", "smlal", "ldr", "str", "ldm", "stm", "ldc", "stc", "swp", ] ) def ual_mnemonic(ins, handler, ours, theirs): """objdump writes UAL: the condition goes last (``ADDEQS`` is ``addseq``, ``LDREQB`` ``ldrbeq``, ``LDMEQIA`` ``ldmiaeq``, ``STCEQL`` ``stcleq``), ``SWI`` is ``svc``, and ``IA`` is left off LDM/STM.""" mnemonic, operands = _split(ours) if ins.thumb: new = _join(re.sub(r"^swi", "svc", mnemonic), operands) return (new, theirs) if new != ours else None conds = "|".join(CONDS) match = re.fullmatch(rf"({_UAL_BASES})({conds})(ia|ib|da|db|sb|sh|bt|b|t|h|d|s|p|l)", mnemonic) if match: mnemonic = match.group(1) + match.group(3) + match.group(2) mnemonic = re.sub(r"^swi", "svc", mnemonic) if not theirs.startswith(("ldmia", "stmia")): # objdump keeps IA only with a condition mnemonic = re.sub(r"^(ldm|stm)ia", r"\1", mnemonic) new = _join(mnemonic, operands) return (new, theirs) if new != ours else None def ual_aliases(ins, handler, ours, theirs): """UAL's preferred spellings: PUSH/POP for STMDB/LDMIA with SP!, ``LSL Rd, Rm, #n`` for a shifted MOV (also ``RRX``), ``NOP`` for ``MOV R0, R0`` (ARM) and ``MOV R8, R8`` (Thumb), and ``MOVS Rd, Rs`` for Thumb ``LSL Rd, Rs, #0``.""" mnemonic, operands = _split(ours) candidates = [] match = re.fullmatch(r"(ldm|stm)(ia|db)?(\w\w)?", mnemonic) if match and operands and operands[0] == "sp!": stem = {"ldm": "pop", "stm": "push"}[match.group(1)] candidates.append(_join(stem + (match.group(3) or ""), operands[1:])) match = re.fullmatch(r"mov(s)?(\w\w)?", mnemonic) # already in UAL order: movseq if match and len(operands) == 3 and operands[2][:3] in ("lsl", "lsr", "asr", "ror"): shift, _, amount = operands[2].partition(" ") new = shift + (match.group(1) or "") + (match.group(2) or "") candidates.append(_join(new, [operands[0], operands[1], amount])) if match and len(operands) == 3 and operands[2] == "rrx": candidates.append( _join("rrx" + (match.group(1) or "") + (match.group(2) or ""), operands[:2]) ) if ours in ("mov r0,r0", "mov r8,r8"): candidates.append("nop") if ins.thumb and mnemonic == "lsl" and operands[-1:] == ["0"]: candidates.append(_join("mov", operands[:2])) return _candidates_equal(candidates, theirs) _THUMB_FLAG_SETTING = { op + "s" for op in [ "and", "eor", "lsl", "lsr", "asr", "adc", "sbc", "ror", "neg", "orr", "mul", "bic", "mvn", "mov", "add", "sub", ] } def objdump_thumb_flags(ins, handler, ours, theirs): """objdump marks a flag-setting Thumb instruction with UAL's ``S`` (``adds``, ``lsls``, ``muls``) and an unconditional or conditional branch with ``.n``; the data sheet's Thumb writes neither.""" if not ins.thumb: return None mnemonic, operands = _split(theirs) fixed = mnemonic[:-2] if mnemonic.endswith(".n") else mnemonic if fixed in _THUMB_FLAG_SETTING: fixed = fixed[:-1] if mnemonic == "muls" and len(operands) == 3 and operands[0] == operands[2]: operands = operands[:2] new = _join(fixed, operands) return (ours, new) if new != theirs else None def objdump_thumb_ldm(ins, handler, ours, theirs): """UAL writes a Thumb LDMIA whose base is in the list without ``!`` (the load wins); ARMv4T's format 15 is one encoding either way and ours keeps the ``!``.""" if ins.thumb and ours.startswith("ldmia") and theirs == ours.replace("!", "", 1): return theirs, theirs return None def objdump_coprocessor_opc2(ins, handler, ours, theirs): """objdump always prints MRC/MCR's opcode 2; ours leaves it out when it is 0.""" mnemonic, operands = _split(ours) if handler in ("_arm_mrc", "_arm_mcr") and len(operands) == 5: return _join(mnemonic, [*operands, "0"]), theirs return None def objdump_mrc_flags(ins, handler, ours, theirs): """MRC with Rd = R15 sets the flags; UAL writes that Rd ``APSR_nzcv``.""" if handler == "_arm_mrc": fixed = theirs.replace("apsr_nzcv", "pc") return (ours, fixed) if fixed != theirs else None return None def objdump_rotation(ins, handler, ours, theirs): """objdump also writes a non-smallest rotation as ``#imm8, rot`` but only for some instructions; bring its side to the value as ``plain_immediate`` does for ours.""" if ins.thumb or not (handler[5:] in DATA or handler == "_arm_msr"): return None mnemonic, operands = _split(theirs) if len(operands) >= 2 and operands[-1].isdigit() and operands[-2].isdigit(): imm8, rot = int(operands[-2]), int(operands[-1]) value = ((imm8 >> rot) | (imm8 << (32 - rot))) & 0xFFFFFFFF return ours, _join(mnemonic, [*operands[:-2], str(value)]) return None def objdump_undefined(ins, handler, ours, theirs): """objdump's ```` and ``udf`` are ours ``UND``.""" if _split(ours)[0].startswith("und") and (theirs == "undefined" or theirs.startswith("udf")): return theirs, theirs return None OBJDUMP_SYNTAX: list[SyntaxRule] = [ plain_immediate, objdump_rotation, unsigned_immediate, objdump_mrc_flags, mame_empty_mask, ual_coprocessor_post, zero_offset, psr_fields, ual_mnemonic, objdump_thumb_flags, ual_aliases, objdump_thumb_ldm, objdump_coprocessor_opc2, objdump_undefined, thumb_aliases, ] SYNTAX = {"mgba": MGBA_SYNTAX, "mame": MAME_SYNTAX, "objdump": OBJDUMP_SYNTAX} COPROCESSOR = ("_arm_cdp", "_arm_ldc", "_arm_stc", "_arm_mrc", "_arm_mcr") def _nonstandard(ins, handler, ours, theirs): return NONSTANDARD in ins.comment def _nv(ins, handler, ours, theirs): return not ins.thumb and ins.data[3] >> 4 == 0xF DISAGREEMENTS: dict[str, list[tuple[str, DisagreementRule]]] = { "mgba": [ ("should-be bits differ: the tool rejects what the core's table decodes", _nonstandard), ( "no coprocessor disassembly in mGBA", lambda i, h, o, t: h in COPROCESSOR and t.startswith("ill"), ), ( "ARMv5 LDRD/STRD encoding (U21)", lambda i, h, o, t: h in ("_arm_ldrd", "_arm_strd") and t.startswith("ill"), ), ("post-indexed PC base printed as a literal address", lambda i, h, o, t: "[pc]," in o), ( "Thumb BX with H1 = 1 (hardware: plain BX, U19)", lambda i, h, o, t: h == "_thumb_bx" and t == "ill", ), ( "Thumb 0xBExx: mGBA decodes ARMv5's BKPT", lambda i, h, o, t: h == "_thumb_undefined" and t.startswith("bkpt"), ), ], "objdump": [ ( "should-be bits differ: the tool rejects or reinterprets what the core's table decodes", _nonstandard, ), ("condition NV: objdump decodes ARMv5's BLX/PLD/xxx2 there or rejects it", _nv), ( "pre-indexed write-back with PC as the base: objdump leaves out the ! (W = 1)", lambda i, h, o, t: "[pc," in o and o.endswith("]!") and t == o[:-1], ), ( "pre-indexed LDC/STC write-back with offset 0: objdump leaves out the ! (W = 1)", lambda i, h, o, t: ( h in ("_arm_ldc", "_arm_stc") and o.endswith("]!") and re.sub(r",-?0\]$", "]", t) == o[:-1] ), ), ( "empty register list: objdump marks it UNPREDICTABLE (); the core runs it (U2)", lambda i, h, o, t: "" in t, ), ( "Thumb 0xE800-0xFFFF alone: objdump reads the first half of a 32-bit Thumb-2 " "instruction (BL halves, 0xE8xx C8)", lambda i, h, o, t: i.thumb and int.from_bytes(i.data, "little") >= 0xE800, ), ( "Thumb undefined space: objdump decodes later architectures there (CBZ, SXTH, REV, " "BKPT, HLT, UDF; ARMv5-v8-M) whatever -m says", lambda i, h, o, t: h == "_thumb_undefined", ), ( "Thumb BX with H1 = 1: objdump decodes ARMv5's BLX (hardware: plain BX, U19)", lambda i, h, o, t: h == "_thumb_bx" and t.startswith(("blx", "undefined")), ), ( "ARM undefined space: objdump decodes ARMv6 media instructions there", lambda i, h, o, t: h == "_arm_undefined", ), ( "ARMv5 LDRD/STRD encoding (U21): objdump decodes ARMv5TE's LDRD/STRD", lambda i, h, o, t: h in ("_arm_ldrd", "_arm_strd"), ), ( "LDC/STC post-indexed with W = 0: objdump reads ARMv5's unindexed form " "([Rn], {option})", lambda i, h, o, t: h in ("_arm_ldc", "_arm_stc") and "{" in t, ), ( "coprocessors 10 and 11 (and some others): objdump decodes VFP/MVE syntax, or " "rejects what VFP leaves undefined", lambda i, h, o, t: h in COPROCESSOR and t.startswith(("v", "undefined", " list[int]: rng = random.Random(20261104) words = [] for index in range(4096): for k in range(32): word = rng.getrandbits(32) & ~0x0FF000F0 word |= ((index >> 4) << 20) | ((index & 0xF) << 4) if k < 24: word = (word & 0x0FFFFFFF) | 0xE0000000 words.append(word) return words def _mame(words: list[int], thumb: bool) -> list[str]: if shutil.which("unidasm") is None: raise SystemExit("unidasm (MAME 0.285, Debian mame-tools) is not on PATH") with tempfile.TemporaryDirectory() as scratch: path = Path(scratch) / "code.bin" path.write_bytes(b"".join(struct.pack(" list[str]: if not MGBA.exists(): raise SystemExit(f"{MGBA.relative_to(ROOT)} is missing: run scripts/build_referees.py") step = 2 if thumb else 4 request = "".join(f"{'T' if thumb else 'A'} {w:x} {step * i:x}\n" for i, w in enumerate(words)) out = subprocess.run( [str(MGBA)], input=request, capture_output=True, text=True, check=True ).stdout return out.splitlines() def _objdump_lines(binutils: Path, data: bytes, thumb: bool) -> dict[int, str]: """objdump's text by address, with its notation brought to the others' shape: the ``@`` comment dropped, ``70 <.text+0x70>`` targets as ``0x70``, ``15``/``cr0``/``{0}`` coprocessor operands as ``p15``/``c0``/``0``.""" with tempfile.TemporaryDirectory() as scratch: path = Path(scratch) / "code.bin" path.write_bytes(data) command = [ str(binutils / "arm-none-eabi-objdump"), "-z", "-D", "-b", "binary", "-m", "armv4t", ] out = subprocess.run( [*command, "-M", "reg-names-std" + (",force-thumb" if thumb else ""), str(path)], capture_output=True, text=True, check=True, ).stdout lines = {} for line in out.splitlines(): match = re.match(r"^\s*([0-9a-f]+):\t[0-9a-f ]+\t(.*)$", line) if not match: continue text = match.group(2).split("@")[0].replace("\t", " ").strip() if not text and "" in match.group(2): text = "undefined" text = re.sub(r"\b([0-9a-f]+) <[^>]*>", r"0x\1", text) if re.match(r"(mrc|mcr|cdp|ldc|stc)", text): text = re.sub(r"(?<=\s)(\d+),", r"p\1,", text, count=1) text = re.sub(r"\bcr(\d+)\b", r"c\1", text) if not re.match(r"(ldc|stc)", text): # LDC/STC's {n} is ARMv5's option field text = re.sub(r"\{(\d+)\}", r"\1", text) lines[int(match.group(1), 16)] = text return lines def _objdump(binutils: Path, words: list[int], thumb: bool) -> list[str]: """One text per word. Each Thumb halfword is followed by a zero halfword, so a word that objdump reads as the first half of a 32-bit encoding does not swallow the next test.""" if thumb: data = b"".join(struct.pack(" int: """Every BL first half with 16 second halves, combined, against mGBA's ``ARMDecodeThumbCombine`` (MAME prints the halves separately).""" rng = random.Random(20261104) pairs = [(0xF000 | hi, 0xF800 | rng.getrandbits(11)) for hi in range(0x800) for _ in range(16)] request = "".join(f"P {a:x} {b:x} {4 * i:x}\n" for i, (a, b) in enumerate(pairs)) if not MGBA.exists(): raise SystemExit(f"{MGBA.relative_to(ROOT)} is missing: run scripts/build_referees.py") out = subprocess.run([str(MGBA)], input=request, capture_output=True, text=True, check=True) wrong = [] for i, ((a, b), theirs) in enumerate(zip(pairs, out.stdout.splitlines(), strict=True)): ours = disassemble_thumb(a, 4 * i, b) if canon(ours.text) != canon(theirs): wrong.append(f"{a:04X} {b:04X} ours {ours.text!r} mgba {theirs!r}") print(f"\nmgba / thumb BL pairs: {len(pairs):,} pairs, {len(pairs) - len(wrong):,} equal") for line in wrong[:10]: print(f" {line}") return len(wrong) def judge_bl_pairs_objdump(binutils: Path) -> int: """The same BL pairs against objdump, which also combines them.""" rng = random.Random(20261104) pairs = [(0xF000 | hi, 0xF800 | rng.getrandbits(11)) for hi in range(0x800) for _ in range(16)] data = b"".join(struct.pack("> 4 == 0xF), ("ARMv5 LDRD/STRD (U21)", lambda ins: "(U21)" in ins.comment), ("Thumb BL half on its own", lambda ins: ins.mnemonic in ("BL.HI", "BL.LO")), ( "reserved Thumb form (U19: BX with H1 = 1, hi-register op on low registers)", lambda ins: ins.thumb and "(U19)" in ins.comment, ), ( "unpredictable (halfword post-indexed with W set, DS 4.10)", lambda ins: "unpredictable" in ins.comment, ), ] def _relative(target: int, address: int) -> str: delta = ((target - address + 0x80000000) & 0xFFFFFFFF) - 0x80000000 return f". + {delta}" if delta >= 0 else f". - {-delta}" def gas_text(ins: Instruction) -> tuple[str | None, str]: """Our text as GNU as writes it under ``.syntax divided``, or None and the reason when the encoding has no GNU spelling. The mapping is small: - a branch target becomes ``. + offset`` (the text holds the absolute address); - a post-indexed LDC/STC: ours ``[Rn], #off!`` (W = 1) is GNU's ``[Rn], #off``; ours ``[Rn], #off`` (W = 0) is GNU's ``[Rn], {off/4}`` (the option field, U = 1 only); - Thumb ``ADD SP, #-n`` is GNU's ``SUB SP, #n`` (it would read ``#-0`` as +0). """ text = ins.text if ins.target is not None: mnemonic = text.split(" ", 1)[0] return f"{mnemonic} {_relative(ins.target, ins.address)}", "" if ins.mnemonic.startswith(("LDC", "STC")): match = re.search(r"\], #(-?)0x([0-9A-F]+)(!?)$", text) if match: minus, value, bang = match.groups() if bang: text = text[:-1] elif minus: return None, "LDC/STC post-indexed down without write-back: no GNU spelling" else: text = text[: match.start()] + f"], {{{int(value, 16) >> 2}}}" if ins.thumb and text.startswith("ADD SP, #-"): text = "SUB SP, #" + text[len("ADD SP, #-") :] # GNU as reads #-0 as +0 if text.startswith("MSR") and re.search(r"#0x[0-9A-F]+, \d+$", text): return None, "MSR immediate with an explicit rotation: GNU as has no such form" if re.search(r"MSR\w* (CPSR|SPSR),", text): return None, "MSR with an empty field mask: GNU as reads a bare CPSR as CPSR_fc" return text, "" def _assemble( binutils: Path, lines: list[str], thumb: bool, raw: list[bytes] ) -> tuple[bytes, dict]: """Assemble one line per slot. A line GNU as rejects is replaced by its raw bytes and the file assembled again, so every slot keeps its address; returns the bytes and the error text per rejected slot.""" header = [".syntax divided", ".arch armv4t", ".thumb" if thumb else ".arm"] errors: dict[int, str] = {} body = list(lines) with tempfile.TemporaryDirectory() as scratch: source, obj, out = (Path(scratch) / n for n in ("code.s", "code.o", "code.bin")) for _ in range(4): source.write_text("\n".join(header + body) + "\n") result = subprocess.run( [ str(binutils / "arm-none-eabi-as"), "-mno-warn-deprecated", "-W", "-o", str(obj), str(source), ], capture_output=True, text=True, ) failed = {} for line in result.stderr.splitlines(): match = re.match(r".*?:(\d+): Error: (.*)$", line) if match: failed[int(match.group(1)) - len(header) - 1] = match.group(2).split(" -- `")[0] if result.returncode == 0 and not failed: break for slot, message in failed.items(): errors.setdefault(slot, message) body[slot] = ".byte " + ", ".join(str(b) for b in raw[slot]) else: raise SystemExit("GNU as still fails after replacing the rejected lines") subprocess.run( [ str(binutils / "arm-none-eabi-objcopy"), "-O", "binary", "-j", ".text", str(obj), str(out), ], check=True, ) return out.read_bytes(), errors def _cp9(ins: Instruction) -> bool: return ins.mnemonic.startswith(("LDC", "STC")) and ins.operands[0] == "p9" _CP9 = ( "LDC/STC on coprocessor 9: GNU as reads them as ARMv8.2's half-precision VLDR/VSTR " "(pre-indexed offsets in halfwords, limited range)" ) # Named reasons a standard encoding assembles back to a different word: two encodings with # the same text, where GNU as picks the other one, or an assembler quirk. ROUND_TRIP_CLASSES: list[tuple[str, Callable[[Instruction, int], bool]]] = [ (_CP9, lambda ins, got: _cp9(ins)), ( "two spellings: Thumb ADD/SUB Rd, Rd, #imm3 (format 2) is also format 3's " "#imm8, which GNU as picks; same result and flags", lambda ins, got: ( ins.thumb and int.from_bytes(ins.data, "little") & 0xFC00 == 0x1C00 and got & 0xE000 == 0x2000 ), ), ] # Named reasons GNU as rejects a standard encoding's text. _R15_REFUSALS = ( "r15 not allowed here", "cannot use register index with PC-relative addressing", "pc may not be used with write-back", "cannot use writeback with PC-relative addressing", "ldr to register 15 must be 4-byte aligned", ) REJECT_CLASSES: list[tuple[str, Callable[[Instruction, str], bool]]] = [ (_CP9, lambda ins, message: _cp9(ins) and message == "co-processor offset out of range"), ( "empty register list (U2): GNU as has no spelling for it", lambda ins, message: "{}" in ins.text, ), ( "R15 where the data sheet says it must not be used (multiply operands, PC as an " "index or as a written-back base): GNU as refuses", lambda ins, message: message in _R15_REFUSALS, ), ( "ADD Rd, PC, #imm with imm >= 0x80000000: GNU as turns it into a PC-relative fixup " "and rejects the result", lambda ins, message: message.startswith("invalid constant") and "after fixup" in message, ), ] def round_trip(binutils: Path, state: str, examples: int) -> int: """Assemble our text with GNU as and compare the bytes with the original encoding.""" if state == "pairs": rng = random.Random(20261104) items = [ disassemble_thumb(0xF000 | hi, 4 * i, 0xF800 | rng.getrandbits(11)) for i, hi in enumerate(h for h in range(0x800) for _ in range(16)) ] thumb, size = True, 4 elif state == "thumb": items = [disassemble_thumb(w, 2 * w) for w in range(0x10000)] thumb, size = True, 2 else: items = [disassemble_arm(w, 4 * i) for i, w in enumerate(_arm_sample())] thumb, size = False, 4 classes: collections.Counter[str] = collections.Counter() samples: dict[str, list[str]] = collections.defaultdict(list) lines, raw, slots = [], [], [] for ins in items: reason = next((name for name, test in _NOT_STANDARD if test(ins)), None) if reason: classes["not standard, left out: " + reason] += 1 continue text, why = gas_text(ins) if text is None: classes["no GNU spelling: " + why] += 1 continue lines.append(text) raw.append(bytes(ins.data)) slots.append(ins) code, errors = _assemble(binutils, lines, thumb, raw) for k, ins in enumerate(slots): word = code[k * size : (k + 1) * size] name = "exact" if k in errors: name = next( (label for label, rule in REJECT_CLASSES if rule(ins, errors[k])), "GNU AS REJECTS: " + errors[k], ) name = name if name.startswith("GNU AS") else "rejected, known: " + name elif word != bytes(ins.data): got = int.from_bytes(word, "little") name = next((label for label, rule in ROUND_TRIP_CLASSES if rule(ins, got)), "MISMATCH") name = name if name == "MISMATCH" else "class: " + name classes[name] += 1 if len(samples[name]) < examples: got = int.from_bytes(word, "little") samples[name].append( f"{int.from_bytes(ins.data, 'little'):0{2 * size}X} ours {ins.text!r}" f" gas {lines[k]!r} -> {got:0{2 * size}X}" ) print(f"\nGNU as round trip / {state}: {len(items):,} encodings") for name, count in sorted(classes.items(), key=lambda kv: (kv[0] != "exact", -kv[1])): print(f" {count:7,} {name}") if name.startswith(("MISMATCH", "GNU AS")) or examples > 1: for line in samples[name]: print(f" {line}") return sum(n for name, n in classes.items() if name.startswith(("MISMATCH", "GNU AS"))) def judge(tool: str, state: str, examples: int, binutils: Path | None = None) -> int: thumb = state == "thumb" words = list(range(0x10000)) if thumb else _arm_sample() if tool == "objdump": theirs_all = _objdump(binutils, words, thumb) else: theirs_all = (_mgba if tool == "mgba" else _mame)(words, thumb) syntax = SYNTAX[tool] classes: collections.Counter[str] = collections.Counter() samples: dict[str, list[str]] = collections.defaultdict(list) step = 4 if tool == "objdump" else 2 if thumb else 4 for i, word in enumerate(words): ins = disassemble_thumb(word, step * i) if thumb else disassemble_arm(word, step * i) handler = ( THUMB_HANDLERS[word >> 6] if thumb else ARM_HANDLERS[((word >> 16) & 0xFF0) | ((word >> 4) & 0xF)] ) ours, theirs = canon(ins.text), canon(theirs_all[i]) used = [] for rule in syntax: if ours == theirs: break result = rule(ins, handler, ours, theirs) if result is not None and result != (ours, theirs): ours, theirs = result used.append(rule.__name__) if ours == theirs: name = "equal" if not used else "syntax: " + " + ".join(used) else: name = next( (label for label, rule in DISAGREEMENTS[tool] if rule(ins, handler, ours, theirs)), "UNEXPLAINED", ) name = name if name == "UNEXPLAINED" else "meaning: " + name classes[name] += 1 if len(samples[name]) < examples: samples[name].append( f"{word:0{4 if thumb else 8}X} ours {ins.text!r} {tool} {theirs_all[i]!r}" ) print(f"\n{tool} / {state}: {len(words):,} encodings") for name, count in sorted(classes.items(), key=lambda kv: (kv[0] != "equal", -kv[1])): print(f" {count:7,} {name}") if name == "UNEXPLAINED" or examples > 1: for line in samples[name]: print(f" {line}") return classes["UNEXPLAINED"] def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--tool", choices=("mgba", "mame", "objdump", "gas"), action="append") parser.add_argument("--state", choices=("arm", "thumb"), action="append") parser.add_argument("--examples", type=int, default=1, help="examples per class (default 1)") parser.add_argument( "--binutils", type=Path, default=BINUTILS, help="directory holding arm-none-eabi-as/objdump/objcopy (default: gba-python's " "pinned Arm GNU Toolchain, if present)", ) args = parser.parse_args() have_binutils = (args.binutils / "arm-none-eabi-objdump").exists() tools = args.tool or ["mgba", "mame", *(["objdump", "gas"] if have_binutils else [])] if not have_binutils: if {"objdump", "gas"} & set(tools): raise SystemExit(f"no arm-none-eabi binutils in {args.binutils}: pass --binutils") print(f"(no arm-none-eabi binutils in {args.binutils}: objdump and the round trip skipped)") unexplained = 0 for tool in tools: for state in args.state or ("thumb", "arm"): if tool == "gas": unexplained += round_trip(args.binutils, state, max(args.examples, 1)) if state == "thumb": unexplained += round_trip(args.binutils, "pairs", max(args.examples, 1)) continue unexplained += judge(tool, state, max(args.examples, 1), args.binutils) if tool == "mgba" and state == "thumb": unexplained += judge_bl_pairs() if tool == "objdump" and state == "thumb": unexplained += judge_bl_pairs_objdump(args.binutils) print(f"\n{unexplained:,} unexplained" if unexplained else "\nno unexplained differences") return 1 if unexplained else 0 if __name__ == "__main__": sys.exit(main())