# SPDX-License-Identifier: MIT """PSR transfers: MRS and MSR (DS 4.6). Both take one S cycle (timing.md table 6-4). MSR's field mask is bits 19:16: ``c`` (bit 16) writes PSR[7:0], ``x`` (17) PSR[15:8], ``s`` (18) PSR[23:16], ``f`` (19) PSR[31:24] (DS 4.6 describes the flags-only and whole-register forms; the four-field mask is the corpus's behaviour, OBSERVED corpus v1). In User mode only the flags field of the CPSR can change (DS 4.6.1). A write to the CPSR's control field that changes the mode swaps the banks at once; a control-field write can also change T (DS 4.6 says software must not: the corpus keeps the written bit, OBSERVED corpus v1). With no SPSR (User, System, a mode value that names no mode) an SPSR write changes nothing and an SPSR read returns the CPSR (see _core.py). """ from __future__ import annotations from arm7tdmi_python._alu import ror32 from arm7tdmi_python._core import MASK32, CoreMixin from arm7tdmi_python._modes import MODE_BITS, USR FIELD_MASKS = (0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000) class PSRMixin(CoreMixin): def _arm_mrs(self, op: int) -> None: """MRS -- Rd = CPSR, or SPSR with bit 22 (DS 4.6).""" value = self._get_spsr() if op & (1 << 22) else self.cpsr self._set_reg((op >> 12) & 0xF, value) self.next_fetch_seq = True self.r[15] = (self.r[15] + 4) & MASK32 def _arm_msr(self, op: int) -> None: """MSR -- CPSR or SPSR fields <- Rm or a rotated immediate, by field mask (DS 4.6).""" immediate = op & (1 << 25) value = ror32(op & 0xFF, ((op >> 8) & 0xF) * 2) if immediate else self._reg(op & 0xF) mask = 0 for field in range(4): if op & (1 << (16 + field)): mask |= FIELD_MASKS[field] if op & (1 << 22): if self._spsr_bank is not None: bank = self._spsr_bank self.spsr[bank] = (self.spsr[bank] & ~mask) | (value & mask) else: if self.cpsr & MODE_BITS == USR: mask &= FIELD_MASKS[3] new = (self.cpsr & ~mask) | (value & mask) if mask & 0xFF: new |= 0x10 # M4 always reads 1 (alyosha-tas psr ReadMe, tested on GBP) if mask & MODE_BITS: self._switch_mode(new & MODE_BITS) self.cpsr = new & MASK32 self.next_fetch_seq = True self.r[15] = (self.r[15] + 4) & MASK32