# SPDX-License-Identifier: MIT """Rung 4: the core's multiplies judged by zayd's Booth-array model (docs/validation.md). The model (``reference/src/multiplication-algorithm``, built into ``reference/build/mul_model.so`` by scripts/build_referees.py) was fuzzed against a GBA, so it is hardware-corrected for results and the carry flag (U11). Each case runs the real instruction through the core, MUL, MLA, UMULL, UMLAL, SMULL, SMLAL with S set and Thumb's MUL, and compares the result registers, C, and ``m``: the core's internal cycles less the fixed extra ones (MLA 1, long 1, long accumulate 2) against the model's iteration count. """ from __future__ import annotations import ctypes import random from pathlib import Path from arm7tdmi_python import ARM7TDMI, CPUState ROOT = Path(__file__).resolve().parents[1] LIBRARY = ROOT / "reference" / "build" / "mul_model.so" FLAG_C = 1 << 29 # (opcode with Rd/RdHi = r4, RdLo/Rn = r3, Rs = r2, Rm = r1, S set; extra I cycles; model) FORMS = { "MUL": (0xE0140291, 0, "mul"), "MLA": (0xE0343291, 1, "mul"), "UMULL": (0xE0943291, 1, "umull"), "UMLAL": (0xE0B43291, 2, "umull"), "SMULL": (0xE0D43291, 1, "smull"), "SMLAL": (0xE0F43291, 2, "smull"), "THUMB MUL": (0x4348, 0, "mul"), # MUL r0, r1: r0 = r1 x r0 } EDGES = [ 0, 1, 2, 0x7F, 0x80, 0xFF, 0x100, 0x7FFF, 0x8000, 0xFFFF, 0x10000, 0x7FFFFF, 0x800000, 0xFFFFFF, 0x1000000, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFF80, 0xFFFFFF7F, 0xFFFF8000, 0xFFFF7FFF, 0xFF800000, 0xFF7FFFFF, 0x40000000, 0xC0000000, 0xBFFFFFFF, 0x3FFFFFFF, 0x55555555, 0xAAAAAAAA, ] # fmt: skip def library() -> ctypes.CDLL: lib = ctypes.CDLL(str(LIBRARY)) out = ctypes.POINTER(ctypes.c_int) lib.model_mul.argtypes = [ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32, out, out] for name in ("model_umull", "model_smull"): getattr(lib, name).argtypes = [ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint64, out, out] for name in ("model_mul", "model_umull", "model_smull"): getattr(lib, name).restype = ctypes.c_uint64 return lib def operand(rng: random.Random) -> int: """A random 32-bit operand spread over 1-4 significant bytes, both signs, or an edge.""" pick = rng.random() if pick < 0.1: return rng.choice(EDGES) value = rng.getrandbits(8 * rng.randint(1, 4)) return (~value) & 0xFFFFFFFF if rng.random() < 0.5 else value class Judge: def __init__(self) -> None: self.lib = library() self.carry = ctypes.c_int() self.m = ctypes.c_int() self.idles = 0 self.cpu = ARM7TDMI(lambda a, w, acc: 0, lambda *a: None, self._idle) def _idle(self, address: int) -> None: self.idles += 1 def model(self, kind: str, rm: int, rs: int, acc: int) -> tuple[int, int, int]: value = getattr(self.lib, f"model_{kind}")( rm, rs, acc, ctypes.byref(self.carry), ctypes.byref(self.m) ) return value, self.carry.value, self.m.value def check(self, form: str, rm: int, rs: int, lo: int, hi: int) -> str | None: """Run one multiply; return a description of any disagreement.""" op, extra, kind = FORMS[form] thumb = form == "THUMB MUL" registers = [0] * 16 if thumb: registers[1], registers[0] = rm, rs # MUL r0, r1: Rs-as-multiplier is Rd registers[15] = 0x08000004 else: registers[1], registers[2], registers[3], registers[4] = rm, rs, lo, hi registers[15] = 0x08000008 self.cpu.restore_state( CPUState(registers=registers, cpsr=0x1F | (0x20 if thumb else 0), pipeline=[op, 0]) ) self.idles = 0 self.cpu.step() accumulate = form in ("MLA", "UMLAL", "SMLAL") if kind == "mul": want, carry, m = self.model("mul", rm, rs, lo if accumulate else 0) got = self.cpu.r[0] if thumb else self.cpu.r[4] want &= 0xFFFFFFFF else: acc = (hi << 32 | lo) if accumulate else 0 want, carry, m = self.model(kind, rm, rs, acc) got = self.cpu.r[4] << 32 | self.cpu.r[3] got_c = 1 if self.cpu.cpsr & FLAG_C else 0 got_m = self.idles - extra if (got, got_c, got_m) != (want, carry, m): return ( f"{form} rm={rm:08x} rs={rs:08x} acc={hi:08x}:{lo:08x}: core {got:x} C={got_c} " f"m={got_m}; model {want:x} C={carry} m={m}" ) return None def judge(form: str, count: int, seed: int) -> tuple[int, list[str]]: """Run ``count`` cases of one form; return (failures, the first few descriptions).""" rng = random.Random(seed) judge = Judge() failures, examples = 0, [] for index in range(count): if index < len(EDGES) ** 2: rm, rs = EDGES[index % len(EDGES)], EDGES[index // len(EDGES)] else: rm, rs = operand(rng), operand(rng) problem = judge.check(form, rm, rs, operand(rng), operand(rng)) if problem: failures += 1 if len(examples) < 5: examples.append(problem) return failures, examples