# SPDX-License-Identifier: MIT """A snapshot of everything the ARM7TDMI holds, and the SingleStepTests layout. ``registers`` is what the current mode sees (R0-R15). ``banks`` holds every bank in full, including the current mode's (kept in step with ``registers``), so a snapshot can be restored in any mode: ``banks[0]`` is R8-R14 of User/System, ``banks[1]`` R8-R14_fiq, and banks 2-5 (svc, abt, irq, und) use slots 5 and 6 for their R13 and R14. ``spsr`` is indexed the same way (slot 0 unused). ``pipeline`` is the two prefetched opcodes, oldest first; ``next_fetch_seq`` is whether the next opcode fetch is an S cycle (the SEQ pin, merged IS included). """ from __future__ import annotations from dataclasses import dataclass, field from arm7tdmi_python._modes import BANK_COUNT, BANK_FIQ, BANK_INVALID, BANK_USER, bank_of from arm7tdmi_python.access import CODE, SEQ def _empty_banks() -> list[list[int]]: return [[0] * 7 for _ in range(BANK_COUNT - 1)] @dataclass class CPUState: registers: list[int] = field(default_factory=lambda: [0] * 16) banks: list[list[int]] = field(default_factory=_empty_banks) cpsr: int = 0xD3 # Supervisor, ARM, I and F set: the reset values (TRM 2.10) spsr: list[int] = field(default_factory=lambda: [0] * (BANK_COUNT - 1)) pipeline: list[int] = field(default_factory=lambda: [0, 0]) next_fetch_seq: bool = False @classmethod def from_sst(cls, words: tuple[int, ...] | list[int]) -> CPUState: """A state from the 40 words of a SingleStepTests ARM7TDMI state record. The corpus's layout is undocumented and was measured (docs/validation.md "The corpus's state layout"): ``R`` holds R0-R15 with R8-R14 always the User bank, the mode banks always hold their own registers, then CPSR, the five SPSRs (fiq, svc, abt, irq, und), the two pipeline opcodes and NBA's next-fetch access bits. """ banks = _empty_banks() banks[BANK_USER] = list(words[8:15]) banks[BANK_FIQ] = list(words[16:23]) for index, bank in enumerate(range(2, 6)): banks[bank][5] = words[23 + 2 * index] banks[bank][6] = words[24 + 2 * index] cpsr = words[31] registers = list(words[0:16]) current = bank_of(cpsr) if current == BANK_FIQ: registers[8:15] = banks[BANK_FIQ] elif current not in (BANK_USER, BANK_INVALID): registers[13:15] = banks[current][5:7] return cls( registers=registers, banks=banks, cpsr=cpsr, spsr=[0, *words[32:37]], pipeline=list(words[37:39]), next_fetch_seq=bool(words[39] & SEQ), ) def to_sst(self) -> list[int]: """The 40 words of a SingleStepTests state record (the inverse of :meth:`from_sst`). The last word is NBA's access bits for the next fetch, ``CODE`` plus ``SEQ`` as the core reports it; the rung-1 comparison maps it through ``gba_access`` first. """ words = [*self.registers[0:8], *self.banks[BANK_USER], self.registers[15]] words += self.banks[BANK_FIQ] for bank in range(2, 6): words += self.banks[bank][5:7] words += [self.cpsr, *self.spsr[1:6], *self.pipeline] words.append(CODE | (SEQ if self.next_fetch_seq else 0)) return words