"""The core's machinery: registers and banks, the bus, the pipeline, exceptions, ``step()``. Every instruction handler in the family modules builds on these. The rules they encode come from the TRM (ARM DDI 0029G) and the data sheet (DS, ARM DDI 0029E); where the documents are silent the behaviour is NanoBoyAdvance's, which the SingleStepTests corpus was generated from, and the docs item that says so is cited. **R15 during an instruction.** As in the TRM's pipeline (DS 3.4), when an instruction starts executing R15 holds its address plus 2L (L = 4 in ARM state, 2 in Thumb): that is the address of cycle 1's prefetch. Handlers advance R15 by L at the point the hardware's PC advances, which is what makes R15 read as plus 12 after the first cycle (U8, U9, U12). """ 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 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._conflict_cycles = 0 self._user_access = False 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 an ARM-state instruction reads it. For two cycles after a user-bank LDM^ in a privileged mode, a banked register reads as the OR of its own and the user copy (U7, the LDM^ bus glitch). """ value = self.r[n] if self._conflict_cycles and 8 <= n < 15: value |= self._bank[BANK_USER][n - 8] return value def _set_reg(self, n: int, value: int) -> None: """Rn <- value. In an invalid mode the banked registers ignore writes (U15); in the LDM^ glitch window the user copy is written too (U7).""" banked = 8 <= n < 15 if self._conflict_cycles and banked: self._bank[BANK_USER][n - 8] = value if not self._mode_invalid or not banked: self.r[n] = value def _switch_mode(self, new_mode: int) -> None: """Change CPSR[4:0] and swap the banked registers (TRM 2.6, figure 2-3). A mode value that names no mode reads R8-R14 as zero and ignores writes to them until a valid mode returns; this is NBA's model, not a measurement (U15). """ old = bank_of(self.cpsr) new = bank_of(new_mode) self.cpsr = (self.cpsr & ~MODE_BITS) | (new_mode & MODE_BITS) self._spsr_bank = None if new == BANK_USER else new if old == new: return r, bank = self.r, self._bank if old == BANK_FIQ: bank[BANK_FIQ][0:5] = r[8:13] r[8:13] = bank[BANK_USER][0:5] elif new == BANK_FIQ: bank[BANK_USER][0:5] = r[8:13] r[8:13] = bank[BANK_FIQ][0:5] bank[old][5] = r[13] bank[old][6] = r[14] if new != BANK_INVALID: r[13] = bank[new][5] r[14] = bank[new][6] self._mode_invalid = False else: r[8:15] = [0] * 7 self.spsr[BANK_INVALID] = 0 self._mode_invalid = True def _get_spsr(self) -> int: """The current mode's SPSR. Bit 4 always reads 1 on the ARM7TDMI (U15). In User and System mode there is no SPSR and the CPSR is read instead (U13, U16).""" value = (self.cpsr if self._spsr_bank is None else self.spsr[self._spsr_bank]) | 0x10 if self._conflict_cycles: value |= self.cpsr # NBA's theory for the LDM^ glitch window (U7) return value 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 if self._conflict_cycles: self._conflict_cycles -= 1 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: """Flush the pipeline after a write to R15: N at the target, S at target+L (DS 3.4). The fetch addresses have R15's low bits cleared (bits 1:0 in ARM state, bit 0 in Thumb: C3); R15 itself keeps them (U20). The refill also latches the new I and F masks (U14). """ if self.cpsr & THUMB: target = self.r[15] & ~1 self.pipeline[0] = self._fetch(target, 16, False) self.pipeline[1] = self._fetch((target + 2) & MASK32, 16, True) self.r[15] = (self.r[15] + 4) & MASK32 else: target = self.r[15] & ~3 self.pipeline[0] = self._fetch(target, 32, False) self.pipeline[1] = self._fetch((target + 4) & MASK32, 32, True) self.r[15] = (self.r[15] + 8) & MASK32 self.next_fetch_seq = True self._irq_masked = bool(self.cpsr & MASK_I) self._fiq_masked = bool(self.cpsr & MASK_F) 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._conflict_cycles = 0 self._user_access = False # ------------------------------------------------------------------ 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, gated by the masks in force when that instruction started (U14, TRM 2.8.4-2.8.5). """ self._cycles = 0 if self.fiq and not self._fiq_masked: self._take_interrupt(0x1C, 0x11, mask_fiq=True) elif self.irq and not self._irq_masked: self._take_interrupt(0x18, 0x12, mask_fiq=False) 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() return self._cycles 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 (U14). For debuggers; changes nothing.""" if self.fiq and not self._fiq_masked: return 0x11 if self.irq and not self._irq_masked: 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: op = self.pipeline[0] self.r[15] &= ~1 # NBA clears bit 0 of R15 at every instruction (U20) self.pipeline[0] = self.pipeline[1] self.pipeline[1] = self._fetch(self.r[15] & ~3, 32, self.next_fetch_seq) if condition_passes(op >> 28, self.cpsr): self._arm_table[((op >> 16) & 0xFF0) | ((op >> 4) & 0xF)](op) else: # An instruction whose condition fails costs its prefetch only (TRM table 6-22). self.next_fetch_seq = True self.r[15] = (self.r[15] + 4) & MASK32 def _execute_thumb(self) -> None: op = self.pipeline[0] 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)