# SPDX-License-Identifier: MIT """The core's state and the machinery every instruction shares: registers and their banks, the bus cycles, the pipeline, exception entry. Registers (TRM 2.6, DS 3.6-3.7). ``r`` is what the current mode sees, R0-R15. ``_bank[b]`` holds R8-R14 of bank ``b`` while another mode is current: the FIQ bank owns all seven, the other privileged banks only R13 and R14 (slots 5 and 6), and R8-R12 of every mode but FIQ are the User bank's slots 0-4. A mode switch writes the outgoing mode's registers back to their bank and loads the incoming mode's. R15 during an instruction is the instruction's address plus 2L (L = 4 in ARM state, 2 in Thumb): it is the address of the fetch that instruction cycle 1 makes. An instruction that takes a second address cycle first advances R15 by L, so an operand read after that sees plus 3L (timing.md; DS 4.9.4, U8, U9). Mode values that name no mode (DS 3.7: "the processor will enter an unpredictable state") select ``BANK_INVALID``: no SPSR, and R8-R14 as the User bank's (see :meth:`_switch_mode`). """ from __future__ import annotations from arm7tdmi_python._modes import ( BANK_COUNT, BANK_FIQ, BANK_INVALID, BANK_USER, FLAG_N, FLAG_Z, MASK_F, MASK_I, MODE_BITS, THUMB, USR, bank_of, condition_passes, ) from arm7tdmi_python.access import CODE, LOCK, SEQ from arm7tdmi_python.state import CPUState MASK32 = 0xFFFFFFFF # CONDITIONS[cond][NZCV] is condition_passes for every flag nibble, built once. CONDITIONS = tuple( tuple(condition_passes(cond, flags << 28) for flags in range(16)) for cond in range(16) ) class CoreMixin: # Set by the public class: the host's callbacks. _bus_read: object _bus_write: object _bus_idle: object # ------------------------------------------------------------------ registers def _init_registers(self) -> None: self.r = [0] * 16 # what the current mode sees; r[15] is the PC (plus 2L, see above) self._bank = [[0] * 7 for _ in range(BANK_COUNT)] self.cpsr = 0xD3 self.spsr = [0] * BANK_COUNT self._spsr_bank: int | None = None # None: this mode has no SPSR self._mode_invalid = False self.pipeline = [0, 0] self.next_fetch_seq = False self._irq_masked = True self._fiq_masked = True self._user_access = False self._glitch_next = False # the last instruction was an LDM^ without R15 (U7) self.coprocessor_cycle = False self.irq = False self.fiq = False self._cycles = 0 @property def thumb(self) -> bool: """The TBIT pin: the core is in Thumb state.""" return bool(self.cpsr & THUMB) @property def mode(self) -> int: return self.cpsr & MODE_BITS @property def privileged(self) -> bool: """nTRANS: high for a privileged access; low in User mode and for LDRT/STRT (TRM 3.4).""" return self.cpsr & MODE_BITS != USR and not self._user_access def _reg(self, n: int) -> int: """Rn as the current mode sees it (R15: the instruction's address plus 2L, or 3L after a second address cycle).""" return self.r[n] def _set_reg(self, n: int, value: int) -> None: """Rn <- value as the current mode sees it. Writing R15 does not refill; callers that branch call :meth:`_set_pc` or :meth:`_refill`.""" self.r[n] = value & MASK32 def _switch_mode(self, new_mode: int) -> None: """Set CPSR[4:0] to ``new_mode`` and swap the banked registers (TRM 2.6, figure 2-3). The outgoing mode's R8-R14 go back to their banks: the FIQ bank takes all seven, any other mode gives R8-R12 to the User bank and R13-R14 to its own. A mode value that names no mode stores and loads like User mode (``BANK_INVALID`` has no registers of its own) and has no SPSR: HYPOTHESIS, the data sheet calls it unpredictable; the SingleStepTests corpus's cases in such modes agree (OBSERVED, corpus v1). """ old = bank_of(self.cpsr) new = bank_of(new_mode) r = self.r if old == BANK_FIQ: self._bank[BANK_FIQ][:] = r[8:15] else: self._bank[BANK_USER][0:5] = r[8:13] self._bank[BANK_USER if old == BANK_INVALID else old][5:7] = r[13:15] if new == BANK_FIQ: r[8:15] = self._bank[BANK_FIQ] else: r[8:13] = self._bank[BANK_USER][0:5] r[13:15] = self._bank[BANK_USER if new == BANK_INVALID else new][5:7] self.cpsr = (self.cpsr & ~MODE_BITS) | (new_mode & MODE_BITS) self._spsr_bank = None if new in (BANK_USER, BANK_INVALID) else new self._mode_invalid = new == BANK_INVALID def _get_spsr(self) -> int: """The current mode's SPSR; in User and System mode, which have none, the CPSR (HYPOTHESIS: DS 4.6 leaves it unpredictable; the corpus agrees, OBSERVED corpus v1).""" if self._spsr_bank is None: return self.cpsr return self.spsr[self._spsr_bank] def _restore_cpsr_from_spsr(self) -> None: """CPSR <- SPSR: data processing with S and Rd = R15, and LDM^ with R15 (DS 4.5.4, 4.11.4).""" spsr = self._get_spsr() self._switch_mode(spsr & MODE_BITS) self.cpsr = spsr # ------------------------------------------------------------------ the bus def _tick(self) -> None: self._cycles += 1 def _tick_in_glitch(self) -> None: """``_tick`` during the instruction after an LDM^: the glitch lasts for the register reads of the instruction's first cycle, and ends with its second (U7).""" self._cycles += 1 if self._cycles >= 2: self._end_glitch() def _end_glitch(self) -> None: self.__dict__.pop("_reg", None) self.__dict__.pop("_tick", None) def _fetch(self, address: int, width: int, seq: bool) -> int: """One opcode fetch (nOPC low).""" value = self._bus_read(address, width, CODE | (SEQ if seq else 0)) self._tick() return value & (0xFFFF if width == 16 else MASK32) def _read(self, address: int, width: int, seq: bool = False, lock: bool = False) -> int: """One data read of ``width`` bits at ``address`` as driven (never aligned: U1-U3).""" value = self._bus_read(address & MASK32, width, (SEQ if seq else 0) | (LOCK if lock else 0)) self._tick() return value & ((1 << width) - 1) def _write( self, address: int, width: int, value: int, seq: bool = False, lock: bool = False ) -> None: """One data write; ``value`` is truncated to ``width`` bits, MAS[1:0] (TRM 3.4).""" self._bus_write( address & MASK32, width, value & ((1 << width) - 1), (SEQ if seq else 0) | (LOCK if lock else 0), ) self._tick() def _idle(self, address: int) -> None: """One internal (I) cycle; ``address`` is what the core drives meanwhile (timing.md).""" self._bus_idle(address & MASK32) self._tick() def _coprocessor_cycle(self, address: int) -> None: """One coprocessor (C) cycle, reported through ``idle()`` with ``coprocessor_cycle`` true for the duration of the call (U17).""" self.coprocessor_cycle = True try: self._idle(address) finally: self.coprocessor_cycle = False # ------------------------------------------------------------------ the pipeline def _refill(self) -> None: """Refill the pipeline from R15: an N fetch at R15 and an S fetch at R15 + L, in the current state; R15 ends at the first address plus 2L and the next fetch is S (TRM 3.3, timing.md tables 6-1 to 6-3). The fetches drive R15 with bits 1:0 (ARM) or bit 0 (Thumb) cleared (C3); R15 itself keeps the low bits it was written with until the next Thumb instruction clears bit 0 (U20: OBSERVED, every refill in the SingleStepTests corpus v1; the GBA's bus cannot see them, and no document describes them).""" pc = self.r[15] if self.cpsr & THUMB: fetch = pc & ~1 & MASK32 self.pipeline[0] = self._fetch(fetch, 16, False) self.pipeline[1] = self._fetch((fetch + 2) & MASK32, 16, True) self.r[15] = (pc + 4) & MASK32 else: fetch = pc & ~3 & MASK32 self.pipeline[0] = self._fetch(fetch, 32, False) self.pipeline[1] = self._fetch((fetch + 4) & MASK32, 32, True) self.r[15] = (pc + 8) & MASK32 self.next_fetch_seq = True def _set_pc(self, value: int) -> None: """R15 <- value and refill (any instruction that writes the PC).""" self.r[15] = value & MASK32 self._refill() # ------------------------------------------------------------------ exceptions def _enter_exception(self, vector: int, mode: int, link: int, mask_fiq: bool = False) -> None: """Exception entry: SPSR_mode <- CPSR, enter the mode in ARM state with I set (and F for FIQ and reset), R14_mode <- ``link``, PC <- vector, refill (TRM 2.8, table 6-15).""" saved = self.cpsr self.spsr[bank_of(mode)] = saved self._switch_mode(mode) self.cpsr = (self.cpsr | MASK_I | (MASK_F if mask_fiq else 0)) & ~THUMB self._set_reg(14, link & MASK32) self._set_pc(vector) # ------------------------------------------------------------------ flags def _set_nz(self, value: int) -> None: self.cpsr = ( (self.cpsr & ~(FLAG_N | FLAG_Z)) | (value & FLAG_N) | (FLAG_Z if value & MASK32 == 0 else 0) ) # ------------------------------------------------------------------ state def capture_state(self) -> CPUState: """A snapshot of every register, bank, SPSR, the pipeline and the next fetch's type.""" banks = [list(b) for b in self._bank[:BANK_INVALID]] current = bank_of(self.cpsr) r = self.r if current == BANK_FIQ: banks[BANK_FIQ] = r[8:15] elif current != BANK_INVALID: banks[current][5:7] = r[13:15] banks[BANK_USER][0:5] = r[8:13] return CPUState( registers=list(r), banks=banks, cpsr=self.cpsr, spsr=list(self.spsr[:BANK_INVALID]), pipeline=list(self.pipeline), next_fetch_seq=self.next_fetch_seq, ) def restore_state(self, state: CPUState) -> None: """Load a snapshot. ``registers`` win over the current mode's bank copy.""" for bank, values in enumerate(state.banks): self._bank[bank][:] = values self._bank[BANK_INVALID][:] = [0] * 7 self.spsr[: len(state.spsr)] = state.spsr self.spsr[BANK_INVALID] = 0 self.cpsr = state.cpsr current = bank_of(state.cpsr) self._spsr_bank = None if current == BANK_USER else current self._mode_invalid = current == BANK_INVALID self.r[:] = state.registers self.pipeline[:] = state.pipeline self.next_fetch_seq = state.next_fetch_seq self._irq_masked = bool(state.cpsr & MASK_I) self._fiq_masked = bool(state.cpsr & MASK_F) self._user_access = False self._glitch_next = False # the last instruction was an LDM^ without R15 (U7) # ------------------------------------------------------------------ step def step(self) -> int: """Run one instruction, or take a pending interrupt; return the bus cycles made. The lines ``irq`` and ``fiq`` are sampled here, at the end of the previous instruction (TRM 2.8.4-2.8.5). A line is masked only if its bit was set both when that instruction started and when it ended: setting I or F acts one instruction late, clearing it acts at once (U14). """ self._cycles = 0 glitch = self._glitch_next if glitch: # The instruction after an LDM^ reads banked registers OR'd with the User bank's # (U7, _block.py): its register reads go through _reg_or_user. self._glitch_next = False self._reg = self._reg_or_user self._tick = self._tick_in_glitch try: self._step() finally: self._end_glitch() else: self._step() return self._cycles def _step(self) -> None: # U14: masked only if masked when the last instruction started (setting the bit acts # one instruction late: TEST ROM alyosha-tas psr) and still masked now (clearing it acts # at once: TEST ROM alyosha-tas irq/IRQ_sub and IRQ_sub_slow with Nintendo's BIOS). cpsr = self.cpsr if self.fiq and not (self._fiq_masked and cpsr & MASK_F): self._take_interrupt(0x1C, 0x11, mask_fiq=True) # The entry set I (and F); the next sample is gated by those masks, not by the # interrupted instruction's (U14), or a still-high line is taken again at the vector. self._irq_masked = bool(self.cpsr & MASK_I) self._fiq_masked = bool(self.cpsr & MASK_F) elif self.irq and not (self._irq_masked and cpsr & MASK_I): self._take_interrupt(0x18, 0x12, mask_fiq=False) self._irq_masked = bool(self.cpsr & MASK_I) self._fiq_masked = bool(self.cpsr & MASK_F) else: self._irq_masked = bool(self.cpsr & MASK_I) self._fiq_masked = bool(self.cpsr & MASK_F) if self.cpsr & THUMB: self._execute_thumb() else: self._execute_arm() def pending_interrupt(self) -> int | None: """What the next :meth:`step` takes instead of an instruction: ``0x11`` (FIQ) or ``0x12`` (IRQ), the mode it enters, or None. Decided as ``step()`` decides it, with the masks of the instruction that just ended and the current ones (U14). For debuggers; changes nothing.""" if self.fiq and not (self._fiq_masked and self.cpsr & MASK_F): return 0x11 if self.irq and not (self._irq_masked and self.cpsr & MASK_I): return 0x12 return None def _take_interrupt(self, vector: int, mode: int, mask_fiq: bool) -> None: """IRQ or FIQ entry: cycle 1 still fetches (its opcode is discarded), then the entry sequence; R14 = address of the instruction not executed + 4 in both states (TRM table 2-3, timing.md "SWI and exception entry").""" thumb = self.cpsr & THUMB if thumb: self._fetch(self.r[15] & ~1, 16, self.next_fetch_seq) link = self.r[15] # pc + 4 else: self._fetch(self.r[15] & ~3, 32, self.next_fetch_seq) link = self.r[15] - 4 # pc + 4 self._enter_exception(vector, mode, link, mask_fiq) def _execute_arm(self) -> None: """Cycle 1 of an ARM instruction: shift the pipeline, fetch at R15, then run the instruction if its condition passes, or advance one S cycle if not (table 6-22).""" op = self.pipeline[0] self.pipeline[0] = self.pipeline[1] self.pipeline[1] = self._fetch(self.r[15] & ~3, 32, self.next_fetch_seq) if CONDITIONS[op >> 28][self.cpsr >> 28]: self._arm_table[(op >> 16) & 0xFF0 | (op >> 4) & 0xF](op) else: self.next_fetch_seq = True self.r[15] = (self.r[15] + 4) & MASK32 def _execute_thumb(self) -> None: # Bits 15:0 of what the decode stage holds. A Thumb fetch only ever brings 16 bits, # so this changes nothing until an MSR sets T and leaves the two ARM words it # prefetched in the pipeline (U16), which software must never do (DS 3.8, DS 4.6: # "the processor will enter an unpredictable state"; TRM 2.7.2: "Never use an MSR # instruction to force a change to the state of the T bit"). HYPOTHESIS (U16): # each such word is decoded as the halfword a Thumb fetch at its address would # have taken from the bus: the word was fetched at A[1:0] = 00, and a halfword # read there takes D[15:0] when BIGEND = 0 (TRM table 3-7; the GBA is # little-endian), so bits 15:0. A GBA test ROM that runs such an MSR and reports # which instructions execute would settle it. op = self.pipeline[0] & 0xFFFF self.r[15] &= ~1 self.pipeline[0] = self.pipeline[1] self.pipeline[1] = self._fetch(self.r[15], 16, self.next_fetch_seq) self._thumb_table[op >> 6](op)