#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Write the lockstep scenarios: the reference's own test programs, and seeded fuzz. make_scenarios.py SH2_PYTHON OUT_DIR [--fuzz N] [--seed S] Families (one JSON file each; scripts/reference_trace.py has the format): - ``figure-*``: every figure of sh2-python's tests/test_pipeline.py (``FIGURES``), on its board (``_board``: one-state memory, its registers, waits, IRL), the scheduler's log on; each twice, as the test runs it (``drawn``: every fetch an ``if`` unless the figure assumes contention) and with real fetches (``real``). - ``pipeline-*``: the programs of that file's other tests (table 7.2's states, C18, SLEEP, load-use, overrun fetches, board waits, the state round trip). - ``rung4-*``: tests/test_rung4.py's write-buffer and CCR-purge programs, 32xspd's cached-read loop, and every runnable DN P2 loop and the purge-order values on the CPS3-like board of validation/rung4/dn.py (memory images as it loads them). - ``bench-*``: benchmarks/harness_speed.py's loop on the minimal harness, cache off and on; and ``bench-*fresh*``, the same loop saved half way into a fresh chip on the same board, on the minimal harness and on the 32X's bus, cache off and on, with modules running (the methodology's save-state gate). - ``edge-*``: short programs for the paths random programs seldom reach: PC in on-chip space, odd or in the arrays; wrong-size on-chip accesses; the purge, address- and data-array and reserved spaces; TAS.B off memory; illegal slots, undefined code, interrupts held off by slots and LDC/STS, external vectors, NMI edges, SLEEP, TRAPA, manual reset, DIVU overflow, module access sizes, BCR1.MASTER; DMA address errors (``edge-dma-ae-*``) and a DMAC register sweep with DE and DME allowed. - ``fuzz-*``: seeded random programs over every form, with random BSC, cache, FRT, WDT, INTC, DMAC, DIVU and SCI settings, pins changed between steps, save-state round trips, direct on-chip register accesses and resets. - ``fresh-*``: the same programs, every save-state round trip into a fresh chip. Nothing is read from outside the reference checkout; stdlib only. """ from __future__ import annotations import argparse import json import random import struct import sys from pathlib import Path def words(ws: list[int]) -> str: return b"".join(struct.pack(">H", w & 0xFFFF) for w in ws).hex() def write(out: Path, name: str, scenario: dict) -> None: (out / f"{name}.json").write_text(json.dumps(scenario, separators=(",", ":")) + "\n") # -- the reference's pipeline tests ---------------------------------------------------------- def figure_scenario(tp, fig, *, contention: bool, steps: int = 30, cache: bool = False, pc: int | None = None) -> dict: # fmt: skip """tests/test_pipeline.py ``_board`` and ``run``, as operations.""" code, data, stack, handler = tp.CODE, tp.DATA, tp.STACK, tp.HANDLER memory = bytearray(0x10000) low = bytearray(0x400) for vector, address in tp.VECTORS.items(): low[4 * vector : 4 * vector + 4] = address.to_bytes(4, "big") base = code + fig.offset blob = bytes.fromhex(words(fig.program)) memory[base - code : base - code + len(blob)] = blob memory[handler - code : handler - code + 64] = struct.pack(">H", tp.NOP) * 32 memory[stack - code : stack - code + 8] = struct.pack(">II", code + 0x100, 0) memory[0x100:0x140] = struct.pack(">H", tp.NOP) * 32 regions = [ {"base": 0, "size": 0x400, "chunks": [[0, low.hex()]]}, {"base": code, "size": 0x10000, "chunks": [[0, memory.hex()]]}, ] ops: list = [["cycle_states", [1, 1, 1, 1]]] r = [data + 0x40 * i for i in range(16)] r[14] = data + 1 r[15] = stack ops += [["r", i, v] for i, v in enumerate(r)] ops += [["set", "gbr", 0x10], ["set", "sr", fig.sr], ["set", "pc", base]] if cache: ops.append(["module_write", 0xFFFFFE92, 8, 0x01]) if pc is not None: ops.append(["set", "pc", pc]) if not contention: ops.append(["set", "free_fetch", 1]) ops += [["set", "pipeline_log", 1], ["restart"]] for n in range(steps): if n == fig.irl_after: ops.append(["set", "irl", 5]) ops.append(["step", 1]) board = {"regions": regions, "address_waits": {str(a): w for a, w in fig.waits.items()}} return {"board": board, "ops": ops, "slice": 0} def pipeline_family(tp, out: Path) -> int: count = 0 for fig in tp.FIGURES: for mode, contention in (("drawn", fig.contention), ("real", True)): write(out, f"figure-{fig.number}-{mode}", figure_scenario(tp, fig, contention=contention)) count += 1 F = tp.Figure NOP = tp.NOP table = [ ([tp.NOP], 0), ([tp.LOAD], 0), ([tp.STORE], 0), ([tp.MAC_W], 0), ([tp.MAC_L], 0), ([tp.MULS_W], 0), ([tp.DMULS_L], 0), ([tp.AND_B], 0), ([tp.TAS], 0), ([tp.BT_8], 1), ([tp.BT_8], 0), ([tp.BT_S_8], 1), ([tp.BT_S_8], 0), ([tp.BRA_8], 0), ([tp.LDC_L], 0), ([tp.STC_L], 0), ([tp.LDS_L_PR], 0), ([tp.STS_L_PR], 0), ([tp.LDS_MACL], 0), ([tp.LDS_L_MACL], 0), ([tp.STS_MACL], 0), ([tp.STS_L_MACL], 0), ([tp.RTE], 0), ([tp.TRAPA], 0), ([tp.UNDEFINED], 0), ] # fmt: skip for i, (ws, sr) in enumerate(table): fig = F("", "", [*ws, NOP, NOP, NOP, NOP, NOP], [], sr=sr) write(out, f"pipeline-table72-{i:02d}", figure_scenario(tp, fig, contention=False)) count += 1 for mac in (tp.MAC_W, tp.MAC_L): for offset in (0, 2): fig = F("", "", [mac, NOP, NOP, NOP, NOP, NOP, NOP], [], offset=offset) write(out, f"pipeline-c18-{mac:04x}-{offset}", figure_scenario(tp, fig, contention=True)) count += 1 fig = F("", "", [tp.SLEEP, NOP, NOP], [], irl_after=1) write(out, "pipeline-sleep", figure_scenario(tp, fig, contention=False)) count += 1 loads = [ [0x6101, tp.ADD], [0x6101, 0x343C], [0x6101, 0x6133], [0x6101, 0x6131], [0x6101, 0x421F], [0x6101, 0x6312], [tp.LDS_L_PR, 0x000B], ] # fmt: skip for i, pair in enumerate(loads): fig = F("", "", [*pair, NOP, NOP, NOP, NOP], [], offset=0) write(out, f"pipeline-loaduse-{i}", figure_scenario(tp, fig, contention=True)) count += 1 fig = F("", "", [tp.BT_8, NOP, 0xFFFF, 0xFFFF, NOP, NOP, NOP, NOP], [], sr=1) write(out, "pipeline-overrun", figure_scenario(tp, fig, contention=True, steps=4)) ws = [NOP] * 6 + [tp.BT_8, NOP] + [NOP] * 8 fig = F("", "", ws, [], sr=1) scenario = figure_scenario(tp, fig, contention=True, steps=4, cache=True, pc=tp.CODE + 0x0C) write(out, "pipeline-overrun-fill", scenario) fig = F("", "", [tp.LOAD, NOP, NOP, NOP, NOP, NOP], [], waits={tp.DATA + 0x40 * 9: 3}) write(out, "pipeline-waits-ma", figure_scenario(tp, fig, contention=True)) fig = F("", "", [NOP] * 8, [], waits={tp.CODE + 4: 2}) write(out, "pipeline-waits-if", figure_scenario(tp, fig, contention=True)) program = [tp.MAC_L, tp.STS_MACL, tp.LOAD, tp.ADD, tp.BT_8, NOP, NOP, NOP, NOP, NOP] fig = F("", "", program, [], sr=1) scenario = figure_scenario(tp, fig, contention=True, steps=0) scenario["ops"] += [["step", 2], ["save_restore"], ["cycle_states", [1, 1, 1, 1]], ["step", 6]] write(out, "pipeline-roundtrip", scenario) scenario = figure_scenario(tp, fig, contention=True, steps=0) scenario["ops"] += [["step", 2], ["fresh_restore"], ["cycle_states", [1, 1, 1, 1]], ["step", 6]] write(out, "pipeline-fresh-roundtrip", scenario) return count + 6 # -- benchmarks/harness_speed.py -------------------------------------------------------------- def bench_family(root: Path, out: Path) -> int: sys.path.insert(0, str(root / "benchmarks")) import harness_speed image = harness_speed.program() count = 0 for cache in (False, True): regions = [ {"base": 0, "size": 4 << 20, "span": 0x02000000, "chunks": [[0, image.hex()]]}, {"base": 0x06000000, "size": 4 << 20, "span": 0x02000000}, ] ops: list = [["reset", True], ["write", 0xFFFFFFE8, 32, 0xA55A0000]] if cache: ops.append(["write", 0xFFFFFE92, 8, 0x11]) # harness_speed.run: at the BRA $ start again (chip.pc = 0x100). for _ in range(40): ops.append(["run_until", 0x100 + 2 * 13, 2000]) ops.append(["set", "pc", 0x100]) write(out, f"bench-{'cache' if cache else 'nocache'}", {"board": {"regions": regions}, "ops": ops, "slice": 500}) count += 1 # The methodology's save-state gate: half way, the state goes into a fresh chip on the # same board (``fresh_restore``) and must continue as the uninterrupted run would; on # the minimal harness and on the 32X's bus (16-bit area 0, CS3 SDRAM bank active with # refresh: the boot ROMs' BCR1, BCR2, WCR, MCR, RTCSR, RTCOR), the last with the FRT, # the WDT and a cycle-steal DMA running too (the reference's tests/test_state.py). key = 0xA55A0000 bus32x = [["write", 0xFFFFFFE0, 32, key | 0x0001], ["write", 0xFFFFFFE4, 32, key | 0x00A8], ["write", 0xFFFFFFE8, 32, key | 0x0055], ["write", 0xFFFFFFEC, 32, key | 0x0AB8], ["write", 0xFFFFFFF8, 32, key | 0x0059], ["write", 0xFFFFFFF0, 32, key | 0x0008]] # fmt: skip modules = [["write", 0xFFFFFE12, 8, 0x00], ["write", 0xFFFFFE14, 8, 0x00], ["write", 0xFFFFFE15, 8, 0x40], ["write", 0xFFFFFE11, 8, 0x01], ["write", 0xFFFFFE80, 16, 0xA520], ["write", 0xFFFFFF80, 32, 0x06001000], ["write", 0xFFFFFF84, 32, 0x06003000], ["write", 0xFFFFFF88, 32, 0x4000], ["write", 0xFFFFFF8C, 32, 0x5A01], ["write", 0xFFFFFFB0, 32, 1], ["read", 0xFFFFFE11, 8], ["read", 0xFFFFFF8C, 32]] # fmt: skip for name, bus, extra, cache in ( ("bench-fresh-nocache", "plain", [], False), ("bench-fresh-cache", "plain", [], True), ("bench-32x-fresh-nocache", "32x", [], False), ("bench-32x-fresh-cache", "32x", [], True), ("bench-32x-fresh-modules", "32x", modules, True), ): regions = [ {"base": 0, "size": 4 << 20, "span": 0x02000000, "chunks": [[0, image.hex()]]}, {"base": 0x06000000, "size": 4 << 20, "span": 0x02000000}, ] ops = [["reset", True]] + (bus32x if bus == "32x" else [["write", 0xFFFFFFE8, 32, key]]) + extra if cache: ops.append(["write", 0xFFFFFE92, 8, 0x01]) for i in range(40): ops.append(["run_until", 0x100 + 2 * 13, 2000]) if i == 20: # Saved at a step boundary, before the host moves the PC (a state saved # after a host's PC change and before a step would not hold the pending # refetch: the reference's _load_pipeline_state takes pc as fetched). ops.append(["step", 7]) ops.append(["fresh_restore"]) ops.append(["set", "pc", 0x100]) options = {"area0_width": 16} if bus == "32x" else {} write(out, name, {"board": {"regions": regions}, "options": options, "ops": ops, "slice": 500}) count += 1 return count # -- rung 4: the write buffer, DN's loops and values, 32xspd --------------------------------------- def nonzero_chunks(data: bytes, base_offset: int = 0, gap: int = 64) -> list: """The runs of ``data`` that are not zero, as chunks (a sparse image).""" chunks = [] i, n = 0, len(data) while i < n: if data[i] == 0: i += 1 continue start = i zeros = 0 while i < n and zeros < gap: zeros = zeros + 1 if data[i] == 0 else 0 i += 1 end = i - zeros chunks.append([base_offset + start, bytes(data[start:end]).hex()]) return chunks def rung4_family(root: Path, tp, out: Path) -> int: sys.path.insert(0, str(root / "validation" / "rung4")) import dn import sh2asm count = 0 store, store2, load, nop = 0x2B82, 0x2A82, 0x6A92, 0x0009 # tests/test_rung4.py: the write buffer on PM's one-state board. for name, program, waits in ( ("store", [store], {tp.DATA + 0x40 * 11: 4}), ("store-store", [store, store2], {tp.DATA + 0x40 * 11: 4}), ("store-load", [store, load], {tp.DATA + 0x40 * 11: 4}), ): fig = tp.Figure("", "", [*program, nop, nop, nop, nop, nop], [], waits=waits) write(out, f"rung4-wb-{name}", figure_scenario(tp, fig, contention=True, steps=len(program) + 3)) count += 1 fig = tp.Figure("", "", [store, 0x6104, nop, nop, nop, nop, nop], [], waits={tp.DATA + 0x2C0: 6}) scenario = figure_scenario(tp, fig, contention=True, steps=0) scenario["ops"] = [["r", 0, 0xFFFFFE10]] + scenario["ops"] + [["step", 4]] write(out, "rung4-wb-onchip", scenario) fig = tp.Figure("", "", [store, nop, load, nop, nop, nop, nop, nop], [], waits={tp.DATA + 0x2C0: 5}) scenario = figure_scenario(tp, fig, contention=True, steps=0) scenario["ops"] += [["step", 1], ["save_restore"], ["cycle_states", [1, 1, 1, 1]], ["step", 4]] write(out, "rung4-wb-state", scenario) count += 2 # The CCR purge behind a buffered store (U9), from the data array. source = " mov.l r0,@r7\n mov.b r1,@r2\n mov.l @r6,r3\n" + " nop\n" * 16 + " mov.l @r6,r4\n" program = sh2asm.assemble(source, 0xC0000000) ops: list = [["write_ccr", 0x01], ["r", 6, 0x100], ["read", 0x100, 32], ["poke", 0x100, "22222222"], ["r", 7, 0x20000200], ["r", 0, 0x33333333], ["r", 2, 0xFFFFFE92], ["r", 1, 0x11]] # fmt: skip ops += [["cache_put", i * 2, 16, w] for i, w in enumerate(program.words)] ops += [["set", "pc", 0xC0000000], ["step", 20]] board = {"regions": [{"base": 0, "size": 0x1000, "span": 0x20000000, "chunks": [[0x100, "11111111"]]}], "write_wait": 6} write(out, "rung4-ccr-purge", {"board": board, "ops": ops, "slice": 0}) count += 1 # 32xspd's cached read loop (the ten words tests/test_rung4.py carries, attributed there). import test_rung4 area1 = bytearray(0x2000) at = test_rung4.SPD_AT area1[at & 0x1FFF : (at & 0x1FFF) + 20] = struct.pack(">10H", *test_rung4.SPD_LOOP) for address, value in test_rung4.SPD_POOL.items(): area1[address & 0x1FFF : (address & 0x1FFF) + 4] = value.to_bytes(4, "big") regions = [ {"base": 0x02000000, "size": 0x2000, "span": 0x02000000, "chunks": [[0, area1.hex()]]}, {"base": 0x06000000, "size": 0x20000, "span": 0x02000000}, {"base": 0x00000000, "size": 0x20000, "span": 0x02000000}, ] ops = [["write_ccr", 0x11], ["set", "pc", at], ["step", 420]] write(out, "rung4-32xspd", {"board": {"regions": regions}, "ops": ops, "slice": 0}) count += 1 # DN's P2 loops on the CPS3-like board (validation/rung4/dn.py), both samples each. def cps3_scenario(b, sample_ops: list) -> dict: regions = [ {"base": 0x02000000, "size": len(b.ram), "span": 0x02000000, "chunks": nonzero_chunks(b.ram)}, {"base": 0x06000000, "size": len(b.flash), "span": 0x02000000, "chunks": nonzero_chunks(b.flash)}, ] board = {"regions": regions, "area_waits": list(dn.BOARD_WAITS)} setup = [["module_write", a, 32, 0xA55A0000 | v] for a, v in ((0xFFFFFFE0, dn.BCR1), (0xFFFFFFE4, dn.BCR2), (0xFFFFFFE8, dn.WCR))] setup.append(["set", "vbr", dn.VECTORS]) return {"board": board, "options": {"area0_width": 8}, "ops": setup + sample_ops, "slice": 2000} def call(routine: int, registers: dict, runner: int = 0) -> list: runner = runner or dn.RUNNER stop = runner + (4 if runner == dn.RUNNER else 8) ops = [["r", n, v] for n, v in registers.items()] ops += [["r", 12, routine], ["r", 15, dn.STACK], ["set", "delay_target", -1], ["set", "pc", runner]] ops.append(["run_until", stop, 400000]) return ops for n in sorted(dn.LOOPS): loop = dn.LOOPS[n] if not dn.runnable(loop): continue b = dn.board() b.load(dn.build(loop)) ops = [] for sample in range(2): ops.append(["write_ccr", loop["ccr"] | 0x10 if sample == 0 else loop["ccr"]]) ops += call(loop["routine"], {1: loop["n"], 0: 0, 2: 3, 3: 5}) write(out, f"rung4-dn-{n:03d}", cps3_scenario(b, ops)) count += 1 b = dn.board() tests = dn.DATA["values"] alias = dn.value_routine("data_alias", dn.VALUE_BODY.format(a=dn.A, u=dn.U, second="")) purge = dn.value_routine("data_purge", dn.VALUE_BODY.format(a=dn.A, u=dn.U, second=dn.SECOND_PURGE)) code = sh2asm.assemble(dn.CODE_BODY.format(a=dn.A, u=dn.U), tests["code_alias"]["routine"]) for program in (alias, purge, dn.VALUE_RUNNER, code): b.load(program) ops = [["write_ccr", 0x11], ["r", 10, dn.RESULTS]] for program in (alias, purge): for _ in range(4): ops += call(program.origin, {}, runner=dn.VALUE_RUNNER.origin) ops += call(code.origin, {}, runner=dn.VALUE_RUNNER.origin)[:-1] + [["run_until", dn.VALUE_RUNNER.origin + 8, 20000]] write(out, "rung4-dn-values", cps3_scenario(b, ops)) return count + 1 # -- edges: the paths random programs seldom reach ------------------------------------------------- EDGE_CODE = 0x06000100 EDGE_VBR = 0x06004000 EDGE_HANDLER = 0x06005000 def edge_scenario(ws: list[int], regs: dict[int, int], extra: list, steps: int = 40, options: dict | None = None, handler: list[int] | None = None) -> dict: # fmt: skip """A program at H'06000100 on two RAM areas, every vector at a handler that returns.""" reset = struct.pack(">IIII", EDGE_CODE, 0x06008000, EDGE_CODE, 0x06008000) vectors = struct.pack(">I", EDGE_HANDLER) * 256 handler = handler or [0x0009, 0x002B, 0x0009] # NOP; RTE; NOP regions = [ {"base": 0, "size": 0x10000, "span": 0x02000000, "chunks": [[0, reset.hex()]]}, {"base": 0x06000000, "size": 0x10000, "span": 0x02000000, "chunks": [[EDGE_CODE - 0x06000000, words(ws)], [EDGE_VBR - 0x06000000, vectors.hex()], [EDGE_HANDLER - 0x06000000, words(handler)]]}, ] # fmt: skip ops: list = [["reset", True], ["set", "vbr", EDGE_VBR], ["set", "pipeline_log", 1]] ops += [["r", n, v] for n, v in regs.items()] ops += extra + [["step", steps]] return {"board": {"regions": regions, "area_waits": [1, 0, 0, 1]}, "options": options or {}, "ops": ops, "slice": 0} def edges_family(out: Path) -> int: nop, rte = 0x0009, 0x002B cases = { # PC into on-chip space, odd, the arrays, cache-through (HM table 4.6, 8.2) "jmp-onchip": ([0x412B, nop, nop], {1: 0xFFFFFE10}, []), "jmp-onchip-top": ([0x412B, nop], {1: 0xFFFFFFF0}, []), "jmp-odd": ([0x412B, nop], {1: 0x06000201}, []), "jmp-data-array": ([0x412B, nop], {1: 0xC0000000}, [["cache_put", 0, 32, 0x0009000B], ["cache_put", 4, 32, 0x00090009]]), "jmp-through": ([0x412B, nop], {1: 0x26000110}, []), "jmp-purge-space": ([0x412B, nop], {1: 0x46000110}, []), # data accesses of the wrong size or alignment, and the odd spaces "long-onchip-byte-half": ([0x6212, nop, nop], {1: 0xFFFFFE10}, []), "byte-onchip-long-half": ([0x6210, nop, nop], {1: 0xFFFFFF00}, []), "word-odd": ([0x6211, nop, nop], {1: 0x06000301}, []), "long-unaligned": ([0x6212, 0x2122, nop], {1: 0x06000302}, []), "store-odd-in-slot": ([0xA002, 0x2122, nop, nop, nop], {1: 0x06000303}, []), "reads-odd-spaces": ([0x6212, 0x6312, 0x6412, 0x6512, 0x6611, 0x6712, 0x6812, nop], {1: 0x40000100}, [["r", 1, 0x40000100]]), "spaces": ([0x6512, 0x6612, 0x6711, 0x2522, 0x6812, 0x2321, 0x6932, nop, nop], {1: 0x60000040, 2: 0xA0000000, 3: 0xC0000010}, [["write", 0xFFFFFE92, 8, 0x01]]), # MOV.L @R1,R5 (cached); MOV.L R3,@R2 (an associative purge of that line); MOV.L @R1,R4 (a miss) "purge-write": ([0x6512, 0x2232, 0x6412, nop], {1: 0x06000300, 2: 0x46000300, 3: 0x1234}, [["write", 0xFFFFFE92, 8, 0x01]]), "tas-spaces": ([0x411B, 0x421B, 0x431B, 0x441B, nop], {1: 0xFFFFFE92, 2: 0xC0000000, 3: 0x60000000, 4: 0x06000400}, []), "tas-cached": ([0x6142, 0x441B, 0x6142, nop], {4: 0x06000400}, [["write", 0xFFFFFE92, 8, 0x01]]), "two-way-ram": ([0x2122, 0x6312, nop], {1: 0xC0000010, 2: 0x5A5A}, [["write", 0xFFFFFE92, 8, 0x09]]), "id-od": ([0x6312, 0x6312, nop], {1: 0x06000400}, [["write", 0xFFFFFE92, 8, 0x07]]), # slots: illegal instructions, undefined code, interrupts held off "illegal-slot": ([0xA002, 0xA002, nop, nop, nop], {}, []), "undefined-in-slot": ([0xA002, 0xFFFF, nop, nop, nop], {}, []), "undefined": ([0xFFFF, nop, nop], {}, []), "bts-not-taken-then-branch": ([0x8D02, 0xA002, nop, nop, nop], {}, [["set", "sr", 0xF0]]), "irq-held-by-slot-and-ldc": ([0xA002, nop, nop, 0x411E, nop, nop, nop], {1: 0}, [["set", "sr", 0], ["set", "irl", 9]]), "irq-after-sts": ([0x011A, nop, nop], {}, [["set", "sr", 0x50], ["set", "irl", 9]]), "irq-vecmd": ([nop, nop, nop], {}, [["write", 0xFFFFFEE1, 8, 1], ["set", "sr", 0], ["set", "irl", 7]]), "irq-onchip-tie": ([nop, nop, nop, nop], {}, [["write", 0xFFFFFE60, 8, 0x07], ["write", 0xFFFFFE10, 8, 0x02], ["write", 0xFFFFFE16, 8, 0], ["set", "sr", 0], ["set", "irl", 7]]), "nmi-falling": ([nop, nop, nop, nop], {}, [["set", "nmi", 0]]), "nmi-rising": ([nop, nop, nop, nop], {}, [["write", 0xFFFFFEE0, 8, 1], ["set", "nmi", 0], ["step", 2], ["set", "nmi", 1]]), "sleep-wakes": ([0x001B, nop, nop], {}, [["set", "sr", 0x00]] + [["step", 5], ["set", "irl", 3]]), "sleep-masked": ([0x001B, nop], {}, [["set", "sr", 0xF0]]), "trapa": ([0xC320, nop, nop], {}, []), "manual-reset": ([nop, nop, nop], {}, [["step", 3], ["reset", False]]), "divu-overflow": ([nop, nop], {}, [["write", 0xFFFFFF08, 32, 2], ["write", 0xFFFFFF00, 32, 0], ["write", 0xFFFFFF04, 32, 0x80000000], ["read", 0xFFFFFF14, 32], ["read", 0xFFFFFF10, 32], ["write", 0xFFFFFF00, 32, 0xFFFFFFFF], ["write", 0xFFFFFF10, 32, 0x80000000], ["write", 0xFFFFFF14, 32, 0], ["read", 0xFFFFFF14, 32]]), # A DMA write behind the CPU's buffered write: a source that is not external memory # (an on-chip register, the data array) so no DMA read waits first; rung 6 found it. "dma-onchip-after-store": ([0x2122, 0x2122, nop, 0x2122, nop, nop], {1: 0x00000400, 2: 0x11223344}, [["write", 0xFFFFFF80, 32, 0xFFFFFE00], ["write", 0xFFFFFF84, 32, 0x06000600], ["write", 0xFFFFFF88, 32, 6], ["write", 0xFFFFFF8C, 32, 0x4201], ["write", 0xFFFFFFB0, 32, 1]]), "dma-array-after-store": ([0x2122, nop, 0x2122, nop], {1: 0x00000400, 2: 0x55667788}, [["cache_put", 0, 32, 0xCAFEF00D], ["write", 0xFFFFFF90, 32, 0xC0000000], ["write", 0xFFFFFF94, 32, 0x00000500], ["write", 0xFFFFFF98, 32, 4], ["write", 0xFFFFFF9C, 32, 0x0A01], ["write", 0xFFFFFFB0, 32, 1]]), # Which way a refill takes after a purge (the LRU is cleared too, HM 8.4.6), read # back through the address array; rung 6 found it. "lru-after-purge": ([0x0009], {}, [["write", 0xFFFFFE92, 8, 0x01]] + [["read", 0x06000000 + 0x400 * k, 32] for k in (0, 1, 2, 0, 3, 1, 4)] + [["write", 0xFFFFFE92, 8, 0x11]] + [["read", 0x06000000 + 0x400 * k, 32] for k in (5, 6)] + sum(([["write", 0xFFFFFE92, 8, 0x01 | w << 6], ["read", 0x60000000, 32]] for w in range(4)), [])), "module-sizes": ([nop], {}, [["read", 0xFFFFFF40, 16], ["write", 0xFFFFFF40, 16, 0x1234], ["read", 0xFFFFFF40, 32], ["read", 0xFFFFFE80, 16], ["write", 0xFFFFFE80, 8, 0xA5], ["read", 0xFFFFFFE2, 16], ["write", 0xFFFFFFE0, 16, 0x0001], ["read", 0xFFFFFE91, 8], ["write", 0xFFFFFE91, 8, 0xFF], ["read", 0xFFFFFE91, 8], ["read", 0xFFFFFE71, 8], ["write", 0xFFFFFE71, 8, 0xFF], ["read", 0xFFFFFE71, 8], ["read", 0xFFFFFE06, 8], ["read", 0xFFFFFF1C, 32], ["read", 0xFFFF8000, 16], ["write", 0xFFFF8000, 16, 1]]), } # fmt: skip # DMA address errors (the reference's R2 fix: HM table 4.6, 9.2.7, 9.3.8; vector 10 goes # to the handler, which returns). SAR, DAR, TCR, CHCR of a channel, then DMAOR.DME. def dma(channel: int, sar: int, dar: int, tcr: int, chcr: int) -> list: base = 0xFFFFFF80 + 0x10 * channel return [["write", base, 32, sar], ["write", base + 4, 32, dar], ["write", base + 8, 32, tcr], ["write", base + 12, 32, chcr]] # fmt: skip dme = [["write", 0xFFFFFFB0, 32, 1]] status = [["read", 0xFFFFFFB0, 32], ["read", 0xFFFFFF8C, 32], ["read", 0xFFFFFF88, 32], ["read", 0xFFFFFF80, 32], ["read", 0xFFFFFF84, 32], ["read", 0xFFFFFF98, 32]] # fmt: skip dma_cases = { # R2's repro: a longword from the data array at H'FFE (it raised IndexError). "dma-ae-data-array": ([nop, nop], {}, [["cache_put", 0xFFC, 32, 0x12345678]] + dma(0, 0xC0000FFE, 0x06001000, 1, 0x0A01) + dme), # Burst from a misaligned source: one transfer, then both channels stop. "dma-ae-burst-stops-both": ([nop, nop, nop], {}, dma(0, 0x06001002, 0x06001200, 4, 0x5A11) + dma(1, 0x06001000, 0x06001100, 4, 0x5A01) + dme), "dma-ae-word-3-mod-4-onchip": ([nop, nop], {}, dma(0, 0xFFFFFF03, 0x06001000, 1, 0x0601) + dme), "dma-ae-byte-onchip-high": ([nop, nop], {}, dma(0, 0xFFFFFF00, 0x06001000, 2, 0x0201) + dme), "dma-ae-long-onchip-low": ([nop, nop], {}, dma(0, 0x06001000, 0xFFFFFE10, 2, 0x0A01) + dme), "dma-ae-dest-misaligned": ([nop, nop], {}, dma(0, 0x06001000, 0x06001002, 3, 0x0A01) + dme), "dma-ae-16-byte-unit": ([nop, nop], {}, dma(0, 0x06001002, 0x06001200, 8, 0x5E01) + dme), "dma-ae-word-odd-external": ([nop, nop], {}, dma(0, 0x06001001, 0x06001200, 2, 0x5601) + dme), # AE blocks until read as 1 and written 0; DE still set: the channel restarts. "dma-ae-clear-restart": ([nop, nop, nop, nop], {}, dma(0, 0x06001002, 0x06001200, 4, 0x5A01) + dme + [["step", 2], ["write", 0xFFFFFFB0, 32, 1]] + status + [["write", 0xFFFFFFB0, 32, 1], ["read", 0xFFFFFFB0, 32]]), # Not between a delayed branch and its slot (HM 4.6.1); it ends SLEEP (HM 14.3.2). "dma-ae-in-delay-slot": ([0xA002, nop, nop, nop, nop], {}, [["step", 1]] + dma(0, 0x06001002, 0x06001200, 2, 0x5A01) + dme), "dma-ae-wakes-sleep": ([0x001B, nop, nop], {}, [["set", "sr", 0xF0], ["step", 3]] + dma(0, 0x06001002, 0x06001200, 2, 0x5A01) + dme), # A CPU address error and a DMA one pending at once: the CPU's first (HM table 4.1). "dma-ae-with-cpu-ae": ([0x6212, nop, nop], {1: 0x06000302}, [["step", 1]] + dma(0, 0x06001002, 0x06001200, 2, 0x5A01) + dme), } # fmt: skip cases.update(dma_cases) # Fresh-chip restores at the states the random programs seldom reach (rung 6 found them # blind): each field of the reference's ChipState.internal that only a new chip can miss. fresh = [["fresh_restore"]] key = 0xA55A0000 sdram = [["write", 0xFFFFFFE0, 32, key | 0x0001], ["write", 0xFFFFFFE8, 32, key | 0x0055], ["write", 0xFFFFFFEC, 32, key | 0x0AB8], ["write", 0xFFFFFFF8, 32, key | 0x0003], ["write", 0xFFFFFFF0, 32, key | 0x0008]] # fmt: skip lru_reads = [["read", 0x06000000 + 0x400 * k, 32] for k in (0, 1, 2, 3, 0, 2)] fresh_cases = { # The pending DMA address error, saved between the slot and its exception. "fresh-dma-ae-pending": ([0xA002, nop, nop, nop, nop], {}, [["step", 1]] + dma(0, 0x06001002, 0x06001200, 2, 0x5A01) + dme + [["step", 1]] + fresh), # The LRU: four ways of entry 0 filled and two touched; which way the fifth tag # replaces shows in which of the old lines miss afterwards. "fresh-cache-lru": ([nop], {}, [["write", 0xFFFFFE92, 8, 0x01]] + lru_reads + fresh + [["read", 0x06000000 + 0x400 * k, 32] for k in (4, 1, 3, 0, 2)]), # The refresh under way: SDRAM with a refresh every 3 counts, saved after every step. "fresh-refresh-end": ([0x6212, 0x6212, 0x6212, 0x6212, 0x6212, 0x6212], {1: 0x26000400}, sdram + sum(([["step", 1], ["fresh_restore"]] for _ in range(24)), [])), # The flags a "read 1, then write 0" clears: CMF, SSR's TDRE, CHCR.TE, DMAOR.AE, # each read as 1 before the restore and written 0 after it. "fresh-cmf-read": ([nop, nop], {}, sdram + [["step", 30], ["read", 0xFFFFFFF0, 32]] + fresh + [["write", 0xFFFFFFF0, 32, key | 0x0008], ["read", 0xFFFFFFF0, 32]]), "fresh-ssr-read": ([nop], {}, [["read", 0xFFFFFE04, 8]] + fresh + [["write", 0xFFFFFE04, 8, 0x00], ["read", 0xFFFFFE04, 8]]), "fresh-te-read": ([nop, nop], {}, dma(0, 0x06001000, 0x06001200, 1, 0x5A01) + dme + [["step", 1], ["read", 0xFFFFFF8C, 32]] + fresh + [["write", 0xFFFFFF8C, 32, 0x5A00], ["read", 0xFFFFFF8C, 32]]), "fresh-ae-read": ([nop, nop], {}, dma(0, 0x06001002, 0x06001200, 1, 0x5A01) + dme + [["step", 2], ["read", 0xFFFFFFB0, 32]] + fresh + [["write", 0xFFFFFFB0, 32, 0], ["read", 0xFFFFFFB0, 32]]), # The NMI edge detector: a falling edge seen (NMIE = 1 waits for a rising one), then # a new chip whose pin idles high: the rising edge is there only if the state kept # the level the old chip saw. "fresh-nmi-seen": ([nop, nop, nop], {}, [["write", 0xFFFFFEE0, 8, 1], ["set", "nmi", 0], ["step", 1]] + fresh), } # fmt: skip cases.update(fresh_cases) for name, (ws, regs, extra) in cases.items(): write(out, f"edge-{name}", edge_scenario(ws + [nop] * 4, regs, extra)) # Every on-chip address written with all ones and all zeros at its legal sizes and read # back: the registers' masks (rung 6 found a VCR bit no other scenario wrote). sweep: list = [] for address in range(0xFFFFFE00, 0xFFFFFF00): for value in (0xFF, 0x00): sweep += [["write", address, 8, value], ["read", address, 8]] for address in range(0xFFFFFE00, 0xFFFFFF00, 2): sweep += [["write", address, 16, 0xA5FF], ["read", address, 16], ["write", address, 16, 0x5A00], ["read", address, 16]] for address in range(0xFFFFFF00, 0x1_0000_0000, 4): for value in (0xFFFFFFFF, 0xA55AFFFF, 0x00000000, 0xA55A0000): if address in (0xFFFFFF8C, 0xFFFFFF9C, 0xFFFFFFB0): value &= ~1 # never DE/DME: an unaligned DMA from the data array (R2) sweep += [["write", address, 32, value], ["read", address, 32]] if not 0xFFFFFF80 <= address <= 0xFFFFFFB0: # (CHCR's and DMAOR's low halves hold DE, DME) sweep += [["write", address + 2, 16, 0xFFFF], ["read", address + 2, 16]] sweep.append(["read", address, 16]) write(out, "edge-register-sweep", edge_scenario([nop] * 4, {}, sweep, steps=4)) # The DMAC's registers with DE and DME allowed (kept clear above until the reference's # R2 fix), a step after each write so a channel the values enable transfers (and # mostly faults: all-ones addresses are misaligned). sweep = [] for address in range(0xFFFFFF80, 0xFFFFFFB4, 4): for value in (0xFFFFFFFF, 0x00000000, 0xA55AFFFF, 0x0000FFFF, 0x00000000): sweep += [["write", address, 32, value], ["read", address, 32], ["step", 1]] sweep += [["write", address + 2, 16, 0xFFFF], ["read", address + 2, 16], ["step", 1], ["read", address, 16]] write(out, "edge-register-sweep-dma", edge_scenario([0xAFFE, nop], {}, sweep, steps=4)) # BRA $ for mode in ("slave", "master"): write(out, f"edge-bcr1-{mode}", edge_scenario([nop] * 4, {}, [["read", 0xFFFFFFE0, 32]], options={"mode": mode})) return len(cases) + 4 + boundaries_family(out) BOUNDARY = (0, 1, 2, 0x7FFF, 0x8000, 0xFFFF, 0x10000, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFE, 0xFFFFFFFF, # pairs that agree in one byte only (CMP/STR) and a plain pattern 0x12345678, 0x12ABCDEF, 0xAB34CDEF, 0xABCD56EF, 0xABCDEF78) # fmt: skip def boundaries_family(out: Path) -> int: """Every register-only ALU, shift and multiply form over boundary operands and T, Q, M. Random operands almost never meet an exact boundary (a carry at 2^32 - 1, a signed difference of -2^31): rung 6 found two such faults uncaught. Each form sits once in the program; each case sets R1 (Rn), R2 (Rm) and SR, points PC at the form and steps it. """ sys_path_forms = __import__("sh2_python._decode", fromlist=["FORMS"]).FORMS forms = [ f for f in sys_path_forms if f.pipeline in ("arith", "logic", "shift", "mul_w", "mul_l", "transfer") and all(tok in ("Rm", "Rn", "") for tok in f.operands.split(",")) ] # fmt: skip def encode(form, n: int, m: int) -> int: op = form.match if "n" in form.code: op |= n << (15 - form.code.rindex("n")) if "m" in form.code: op |= m << (15 - form.code.rindex("m")) return op count = 0 for same in (False, True): program, at = [], {} for form in forms: at[form.handler] = EDGE_CODE + 2 * len(program) program += [encode(form, 1, 1 if same else 2), 0x0009] ops: list = [] pairs = [(a, b) for a in BOUNDARY for b in BOUNDARY] if not same else [(a, a) for a in BOUNDARY] for form in forms: for a, b in pairs: for sr in (0x000, 0x001, 0x100, 0x200, 0x301): if sr in (0x100, 0x200, 0x301) and form.mnemonic != "DIV1": continue ops += [["r", 1, a], ["r", 2, b], ["set", "sr", sr], ["set", "mach", 0], ["set", "macl", 0], ["set", "pc", at[form.handler]], ["step", 1]] # fmt: skip scenario = edge_scenario(program, {}, ops, steps=0) scenario["slice"] = 1000 scenario["state_at_slice"] = False write(out, f"edge-boundaries{'-same' if same else ''}", scenario) count += 1 # MAC.W and MAC.L at their saturation edges (S = 1) and without (S = 0). mac_w, mac_l = 0x412F, 0x012F # MAC.W @R2+,@R1+ / MAC.L @R2+,@R1+ program = [mac_w, 0x0009, mac_l, 0x0009] ops = [] data = 0x06006000 words16 = (0x0000, 0x0001, 0x7FFF, 0x8000, 0xFFFF) macs = ((0, 0), (0, 0x7FFFFFFF), (0, 0x80000000), (0xFFFFFFFF, 0x80000000), (0x00007FFF, 0xFFFFFFFF), (0xFFFF8000, 0x00000000), (0x7FFFFFFF, 0xFFFFFFFF), (0x00008000, 0x00000000)) # fmt: skip for s in (0x000, 0x002): for mach, macl in macs: for a in words16: for b in words16: ops += [["poke", data, f"{a:04x}{b:04x}"], ["r", 1, data], ["r", 2, data + 2], ["set", "sr", s], ["set", "mach", mach], ["set", "macl", macl], ["set", "pc", EDGE_CODE], ["step", 1]] # fmt: skip for a in BOUNDARY: for b in (0, 1, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF): ops += [["poke", data, f"{a:08x}{b:08x}"], ["r", 1, data], ["r", 2, data + 4], ["set", "sr", s], ["set", "mach", mach], ["set", "macl", macl], ["set", "pc", EDGE_CODE + 4], ["step", 1]] # fmt: skip scenario = edge_scenario(program, {}, ops, steps=0) scenario["slice"] = 500 scenario["state_at_slice"] = False write(out, "edge-mac-saturation", scenario) return count + 1 # -- seeded fuzz --------------------------------------------------------------------------------- AREA_BASES = (0x00000000, 0x02000000, 0x04000000, 0x06000000) REGION = 0x10000 CODE = 0x06000100 VECTORS = 0x06004000 HANDLERS = 0x06005000 def fuzz_scenario(forms, seed: int, restore: str = "save_restore") -> dict: """``restore`` is the round trip the save-state events make: ``save_restore`` into the same chip (the fuzz family), or ``fresh_restore`` into a new chip on the same board (the fresh family; the board's pins start at their defaults in the new chip, the same on both sides). The random stream is the same either way.""" rng = random.Random(seed) # Weight the forms: every one appears, the common ones more. def opcode() -> int: form = rng.choice(forms) return form.match | (rng.getrandbits(16) & ~form.mask & 0xFFFF) def pointer() -> int: base = rng.choice(AREA_BASES) | rng.choice((0, 0x20000000, 0, 0)) return (base + rng.randrange(0, REGION - 64)) & ~rng.choice((0, 1, 3, 3, 3)) code = [opcode() for _ in range(rng.randrange(200, 600))] handlers = [] for _ in range(8): handlers += [opcode() for _ in range(rng.randrange(2, 12))] + [0x002B, 0x0009] # RTE; NOP vectors = b"".join( struct.pack(">I", HANDLERS + 2 * rng.randrange(0, len(handlers) - 2) & ~1) for _ in range(256) ) reset = struct.pack(">II", CODE, 0x06008000) regions = [] for i, base in enumerate(AREA_BASES): region = {"base": base, "size": REGION, "span": 0x02000000, "xorshift": rng.getrandbits(32)} if i == 0: region["chunks"] = [[0, reset.hex()], [8, reset.hex()]] if i == 3: region["chunks"] = [ [CODE - base, words(code)], [VECTORS - base, vectors.hex()], [HANDLERS - base, words(handlers)], ] regions.append(region) board = { "regions": regions, "area_waits": [rng.choice((0, 0, 1, 2, 3)) for _ in range(4)], "address_waits": {str(pointer() & 0x1FFFFFFF & ~3): rng.randrange(1, 4) for _ in range(4)}, "pattern": rng.random() < 0.2, } options = { "mode": rng.choice(("master", "master", "slave")), "area0_width": rng.choice((8, 16, 32, 32)), "undefined": rng.choice((0, 0, 0xFFFFFFFF, rng.getrandbits(32))), "observe": rng.random() < 0.3, } ops: list = [["reset", True]] key = 0xA55A0000 def bsc() -> list: out = [] if rng.random() < 0.7: out.append(["write", 0xFFFFFFE4, 32, key | rng.getrandbits(16)]) # BCR2 if rng.random() < 0.7: out.append(["write", 0xFFFFFFE8, 32, key | rng.getrandbits(16)]) # WCR if rng.random() < 0.6: # Synchronous DRAM (the 32X's settings and others) with refresh. out.append(["write", 0xFFFFFFEC, 32, key | rng.choice((0x0AB8, 0x0AB8, rng.getrandbits(16) | 0x0008))]) out.append(["write", 0xFFFFFFE0, 32, key | rng.choice((0x0001, 0x0004, 0x0005, rng.getrandbits(16)))]) out.append(["write", 0xFFFFFFF8, 32, key | rng.choice((rng.randrange(1, 0x40), rng.randrange(1, 0x100)))]) # RTCOR out.append(["write", 0xFFFFFFF0, 32, key | rng.choice((0x08, 0x08, 0x48, 0x10, 0x50, 0x18))]) elif rng.random() < 0.5: out.append(["write", 0xFFFFFFE0, 32, key | rng.getrandbits(16)]) return out def modules() -> list: out = [] if rng.random() < 0.6: out.append(["write", 0xFFFFFE92, 8, rng.choice((0x01, 0x11, 0x09, 0x03, 0x05, 0x41, 0x81, rng.getrandbits(8)))]) if rng.random() < 0.6: # FRT out.append(["write", 0xFFFFFE16, 8, rng.randrange(0, 3)]) # TCR out.append(["write", 0xFFFFFE17, 8, rng.getrandbits(8)]) # TOCR for _ in range(rng.choice((1, 2))): # OCRA, then OCRB when TOCR.OCRS is set out.append(["write", 0xFFFFFE14, 8, rng.choice((0, 0, rng.getrandbits(8)))]) # high out.append(["write", 0xFFFFFE15, 8, rng.getrandbits(8)]) out.append(["write", 0xFFFFFE17, 8, rng.getrandbits(8)]) # TOCR: OCRS, OLVLA/B out.append(["write", 0xFFFFFE11, 8, rng.choice((0, 1, 1))]) # CCLRA out.append(["write", 0xFFFFFE10, 8, rng.getrandbits(8)]) # TIER if rng.random() < 0.5: # WDT out.append(["write", 0xFFFFFE80, 16, 0x5A00 | rng.getrandbits(8)]) out.append(["write", 0xFFFFFE80, 16, 0xA500 | rng.choice((0x20, 0x21, 0x27, 0x60, rng.getrandbits(8)))]) if rng.random() < 0.7: # INTC levels and vectors for address in (0xFFFFFE60, 0xFFFFFEE2, 0xFFFFFEE3): out.append(["write", address, 8, rng.getrandbits(8)]) for address in range(0xFFFFFE62, 0xFFFFFE69): if rng.random() < 0.5: out.append(["write", address, 8, rng.randrange(64, 128)]) out.append(["write", 0xFFFFFEE4, 8, rng.randrange(64, 128)]) out.append(["write", 0xFFFFFEE5, 8, rng.randrange(64, 128)]) if rng.random() < 0.2: out.append(["write", 0xFFFFFEE0, 8, rng.getrandbits(1)]) # NMIE if rng.random() < 0.1: out.append(["write", 0xFFFFFEE1, 8, 1]) # VECMD if rng.random() < 0.5: # DMAC for ch in range(2): if rng.random() < 0.6: ts = rng.randrange(0, 4) align = (1, 2, 4, 16)[ts] sar = pointer() & ~(align - 1) & ~3 dar = pointer() & ~(align - 1) & ~3 base = 0xFFFFFF80 + 0x10 * ch out.append(["write", base, 32, sar]) out.append(["write", base + 4, 32, dar]) # A 16-byte unit counts TCR down by 4 (HM 9.2.3: "set the count to 4 # times the number of transfers"); any other count wraps past 0 and # runs some 4M transfers in one step, in both cores. count = 4 * rng.randrange(1, 4) if ts == 3 else rng.randrange(1, 12) out.append(["write", base + 8, 32, count]) chcr = (rng.randrange(0, 3) << 14) | (rng.randrange(0, 3) << 12) | (ts << 10) chcr |= rng.choice((0x0200, 0x0200, 0)) | rng.choice((0x10, 0)) | rng.choice((4, 0)) | 1 out.append(["write", base + 12, 32, chcr]) out.append(["write", 0xFFFFFFA0 + 8 * ch, 32, rng.randrange(64, 128)]) out.append(["write", 0xFFFFFFB0, 32, 1]) if rng.random() < 0.5: # DIVU out.append(["write", 0xFFFFFF0C, 32, rng.randrange(64, 128)]) out.append(["write", 0xFFFFFF08, 32, rng.randrange(0, 4)]) out.append(["write", 0xFFFFFF00, 32, rng.choice((0, 1, 0xFFFFFFFF, rng.getrandbits(32)))]) out.append(["write", 0xFFFFFF04, 32, rng.getrandbits(32)]) if rng.random() < 0.6: # SCI: TE (and RE), a byte to TDR, TDRE cleared: it goes out out.append(["write", 0xFFFFFE02, 8, rng.getrandbits(8) | 0x30]) out.append(["write", 0xFFFFFE03, 8, rng.getrandbits(8)]) out.append(["read", 0xFFFFFE04, 8]) out.append(["write", 0xFFFFFE04, 8, rng.choice((0x00, 0x7F, rng.getrandbits(8)))]) return out ops += bsc() + modules() ops.append(["write", 0xFFFFFFE8 & 0xFFFFFFFF, 16, 0]) # a read-only 16-bit BSC write: ignored for n in range(16): ops.append(["r", n, pointer() if rng.random() < 0.7 else rng.getrandbits(32)]) ops.append(["r", 15, 0x06008000 - 4 * rng.randrange(0, 64)]) ops.append(["set", "gbr", pointer()]) ops.append(["set", "vbr", VECTORS if rng.random() < 0.9 else pointer()]) ops.append(["set", "sr", rng.getrandbits(10) & 0x3F3]) steps = 0 while steps < 3000: k = rng.randrange(1, 60) ops.append(["step", k]) steps += k event = rng.random() if event < 0.15: ops.append(["set", "irl", rng.randrange(0, 16)]) elif event < 0.2: ops.append(["set", "nmi", rng.getrandbits(1)]) elif event < 0.27: ops.append(["set", rng.choice(("dreq0", "dreq1")), rng.getrandbits(1)]) elif event < 0.32: ops.append([restore]) elif event < 0.36: address = rng.choice((0xFFFFFE11, 0xFFFFFE12, 0xFFFFFE13, 0xFFFFFE81, 0xFFFFFE80, 0xFFFFFE04, 0xFFFFFE92, 0xFFFFFEE0, 0xFFFFFE60)) # fmt: skip ops.append(["read", address, 8]) if rng.random() < 0.5: ops.append(["write", address, 8, rng.getrandbits(8) & 0x7F]) elif event < 0.4: address = rng.choice((0xFFFFFF14, 0xFFFFFF10, 0xFFFFFF8C, 0xFFFFFF9C, 0xFFFFFFB0, 0xFFFFFFF0, 0xFFFFFFF4, 0xFFFFFFE0)) # fmt: skip ops.append(["read", address, 32]) if rng.random() < 0.4 and address in (0xFFFFFF8C, 0xFFFFFF9C, 0xFFFFFFB0): ops.append(["write", address, 32, 0]) if rng.random() < 0.4 and address == 0xFFFFFFF0: ops.append(["write", address, 32, key | 0x48]) elif event < 0.43: ops.append(["sci_receive", rng.getrandbits(8)]) elif event < 0.45: ops.append(["bus_released"]) elif event < 0.47: ops += modules() elif event < 0.48: ops += bsc() elif event < 0.49: ops.append(["set", "pc", CODE + 2 * rng.randrange(0, len(code))]) elif event < 0.495: ops.append(["reset", rng.random() < 0.5]) return {"board": board, "options": options, "ops": ops, "slice": 200} def fuzz_family(out: Path, forms, count: int, seed: int) -> int: for i in range(count): write(out, f"fuzz-{seed:04d}-{i:04d}", fuzz_scenario(forms, seed * 100003 + i)) return count def fresh_family(out: Path, forms, count: int, seed: int) -> int: """The fuzz family's programs with every save-state event a fresh-chip restore (the reference's complete ``ChipState``, its R1 fix): the cache's lines, the SDRAM banks, the refresh, the read-then-write flags and the timers' catch-up clocks go through the state, so a transcription that drops or garbles any of them diverges from the reference after the restore (whether the reference's own fresh chip continues as the uninterrupted one would is its tests/test_state.py's question).""" for i in range(count): write(out, f"fresh-{seed:04d}-{i:04d}", fuzz_scenario(forms, seed * 100003 + i, "fresh_restore")) return count def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("reference", type=Path) parser.add_argument("out", type=Path) parser.add_argument("--fuzz", type=int, default=0) parser.add_argument("--seed", type=int, default=1) parser.add_argument("--only", choices=("pipeline", "bench", "rung4", "edges", "fuzz", "fresh"), action="append") args = parser.parse_args() args.out.mkdir(parents=True, exist_ok=True) root = args.reference sys.path.insert(0, str(root / "src")) sys.path.insert(0, str(root / "tests")) families = args.only or ["pipeline", "bench", "rung4", "edges", "fuzz", "fresh"] total = 0 if "pipeline" in families: import test_pipeline total += pipeline_family(test_pipeline, args.out) if "bench" in families: total += bench_family(root, args.out) if "rung4" in families: import test_pipeline total += rung4_family(root, test_pipeline, args.out) if "edges" in families: total += edges_family(args.out) if "fuzz" in families and args.fuzz: from sh2_python._decode import FORMS total += fuzz_family(args.out, list(FORMS), args.fuzz, args.seed) if "fresh" in families and args.fuzz: from sh2_python._decode import FORMS total += fresh_family(args.out, list(FORMS), args.fuzz, args.seed) print(f"{total} scenarios in {args.out}") return 0 if __name__ == "__main__": sys.exit(main())