#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Check the corpus's multiplies against zayd's Booth-multiplier model and the TRM's m rule. zayd's model (``reference/src/multiplication-algorithm``, fuzzed against a GBA; docs/undocumented-behavior.md U11) is built by ``scripts/build_referees.py`` into ``reference/build/mul_model.so``. For every executed multiply in the corpus (ARM MUL/MLA/UMULL/UMLAL/SMULL/SMLAL and Thumb MUL) this compares: - the result registers, model against corpus; - the C flag, for the S forms, model against corpus; - the model's iteration count against the TRM's m rule (docs/timing.md). python scripts/multiply_model.py """ from __future__ import annotations import ctypes import sys from collections import Counter from pathlib import Path from struct import unpack_from ROOT = Path(__file__).resolve().parents[1] CORPUS = ROOT / "reference" / "src" / "SingleStepTests-ARM7TDMI" / "v1" LIBRARY = ROOT / "reference" / "build" / "mul_model.so" MAGIC = 0xD33DBAE0 BANK = {0x11: "fiq", 0x12: "irq", 0x13: "svc", 0x17: "abt", 0x1B: "und"} SHORT_OFFSET = {"svc": 23, "abt": 25, "irq": 27, "und": 29} def view(v: tuple[int, ...]) -> list[int]: """The 16 registers the current mode sees (the corpus stores R8-R14 of the user bank).""" regs = list(v[0:16]) bank = BANK.get(v[31] & 0x1F) if bank == "fiq": regs[8:15] = v[16:23] elif bank: regs[13:15] = v[SHORT_OFFSET[bank] : SHORT_OFFSET[bank] + 2] return regs def cases(path: Path): buf = path.read_bytes() magic, count = unpack_from(" bool: n, z, c, v = (cpsr >> 31) & 1, (cpsr >> 30) & 1, (cpsr >> 29) & 1, (cpsr >> 28) & 1 return bool( [z, not z, c, not c, n, not n, v, not v, c and not z, not c or z, n == v, n != v, not z and n == v, z or n != v, 1, 0][cond] ) # fmt: skip def trm_m(rs: int, signed: bool) -> int: """TRM 6.20 / DS 4.8.3: how many 8-bit multiplier array cycles Rs needs.""" for m, shift in ((1, 8), (2, 16), (3, 24)): top = rs >> shift if top == 0 or (signed and top == (0xFFFFFFFF >> shift)): return m return 4 def main() -> int: if not LIBRARY.exists(): print("no model; run scripts/build_referees.py", file=sys.stderr) return 1 lib = ctypes.CDLL(str(LIBRARY)) c_int_p = ctypes.POINTER(ctypes.c_int) for name, acc in (("model_mul", ctypes.c_uint32), ("model_umull", ctypes.c_uint64), ("model_smull", ctypes.c_uint64)): # fmt: skip fn = getattr(lib, name) fn.restype = ctypes.c_uint64 fn.argtypes = [ctypes.c_uint32, ctypes.c_uint32, acc, c_int_p, c_int_p] tally: Counter = Counter() carry, m = ctypes.c_int(), ctypes.c_int() for file in ("arm_mul_mla", "arm_mull_mlal", "thumb_data_proc"): for initial, final, op in cases(CORPUS / f"{file}.json.bin"): regs, out = view(initial), view(final) # A multiply reads R15 as its address + 12 (U12): the PC has # advanced by the time the operands are read (NBA, the corpus). regs[15] = (regs[15] + (2 if file.startswith("thumb") else 4)) & 0xFFFFFFFF thumb = file.startswith("thumb") if thumb: if (op >> 6) & 0x3FF != 0x10D: # format 4, opcode 1101: MUL Rd, Rs continue # MUL Rd, Rs is MULS Rd, Rs, Rd (DS table 5-5): Rd is the multiplier. rd = op & 7 rm, rs, acc, setflags, kind = regs[(op >> 3) & 7], regs[rd], 0, True, "Thumb MUL" got = lib.model_mul(rm, rs, 0, ctypes.byref(carry), ctypes.byref(m)) checks = [(out[rd], got & 0xFFFFFFFF)] else: if not passes(op >> 28, initial[31]): continue setflags = bool(op >> 20 & 1) rm, rs = regs[op & 15], regs[(op >> 8) & 15] if file == "arm_mul_mla": rd, rn = (op >> 16) & 15, (op >> 12) & 15 accumulate = bool(op >> 21 & 1) kind = "MLA" if accumulate else "MUL" acc = regs[rn] if accumulate else 0 got = lib.model_mul(rm, rs, acc, ctypes.byref(carry), ctypes.byref(m)) checks = [(out[rd], got & 0xFFFFFFFF)] if rd != 15 else [] else: hi, lo = (op >> 16) & 15, (op >> 12) & 15 accumulate, signed = bool(op >> 21 & 1), bool(op >> 22 & 1) kind = ("S" if signed else "U") + ("MLAL" if accumulate else "MULL") acc = (regs[hi] << 32 | regs[lo]) if accumulate else 0 fn = lib.model_smull if signed else lib.model_umull got = fn(rm, rs, acc, ctypes.byref(carry), ctypes.byref(m)) checks = [] if 15 in (hi, lo) or hi == lo else [ (out[lo], got & 0xFFFFFFFF), (out[hi], got >> 32)] # fmt: skip tally[(kind, "result agrees")] += bool(checks) and all(a == b for a, b in checks) tally[(kind, "results compared")] += bool(checks) if setflags: tally[(kind, "carry compared")] += 1 tally[(kind, "carry agrees")] += (final[31] >> 29 & 1) == carry.value signed = kind in ("MUL", "Thumb MUL", "MLA", "SMULL", "SMLAL") tally[(kind, "m agrees with TRM")] += m.value == trm_m(rs, signed) tally[(kind, "cases")] += 1 for kind in ("MUL", "MLA", "UMULL", "UMLAL", "SMULL", "SMLAL", "Thumb MUL"): t = {k[1]: v for k, v in tally.items() if k[0] == kind} print(f"{kind:9} cases={t['cases']:6} result {t['result agrees']}/{t['results compared']} " f"carry {t['carry agrees']}/{t['carry compared']} " f"m=TRM {t['m agrees with TRM']}/{t['cases']}") # fmt: skip return 0 if __name__ == "__main__": sys.exit(main())