// 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. //! //! Transcribed from `arm7tdmi_python/_core.py` (the reference's `CoreMixin`; the mixins are //! `impl` blocks on [`ARM7TDMI`] here). //! //! 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 [`ARM7TDMI::switch_mode`]). use crate::access::{CODE, LOCK, SEQ}; use crate::modes::{ bank_of, condition_passes, BANK_COUNT, BANK_FIQ, BANK_INVALID, BANK_USER, FLAG_N, FLAG_Z, MASK_F, MASK_I, MODE_BITS, THUMB, USR, }; use crate::state::CPUState; use crate::tables::{ARM_HANDLERS, THUMB_HANDLERS}; pub const MASK32: u32 = 0xFFFF_FFFF; /// The host's bus: one call per CPU cycle, in chip order, internal cycles included (the /// reference's `read`, `write` and `idle` callables). /// /// - `read(address, width, access) -> value`: one N or S cycle that reads `width` (8, 16 or /// 32) bits; `access` is a set of [`SEQ`], [`CODE`] and [`LOCK`]. /// - `write(address, width, value, access)`: one N or S cycle that writes. /// - `idle(address, coprocessor_cycle)`: one internal cycle; `address` is what the core /// drives. A CP14 coprocessor cycle also comes here, with `coprocessor_cycle` true. (The /// reference's callback reads `cpu.coprocessor_cycle` during the call; a Rust callback /// cannot see the CPU that is calling it, so the flag is passed: the one change Rust /// forces on the contract. The field is kept too.) pub trait Bus { fn read(&mut self, address: u32, width: u32, access: u32) -> u32; fn write(&mut self, address: u32, width: u32, value: u32, access: u32); /// The default `idle`: a host that ignores internal cycles (the reference's `_no_idle`). fn idle(&mut self, address: u32, coprocessor_cycle: bool) { let _ = (address, coprocessor_cycle); } } /// CONDITIONS[cond][NZCV] is condition_passes for every flag nibble, built once. pub(crate) static CONDITIONS: [[bool; 16]; 16] = { let mut table = [[false; 16]; 16]; let mut cond = 0; while cond < 16 { let mut flags = 0; while flags < 16 { table[cond][flags] = condition_passes(cond as u32, (flags as u32) << 28); flags += 1; } cond += 1; } table }; /// The bit mask of a `width`-bit value (`(1 << width) - 1` in the reference). #[inline] pub(crate) fn width_mask(width: u32) -> u32 { if width >= 32 { MASK32 } else { (1u32 << width) - 1 } } /// An ARM7TDMI core whose bus is a [`Bus`] supplied by a host. /// /// The address is the one the core computes, low bits included; aligning it is the memory's /// job. `irq` and `fiq` are the interrupt lines (true = asserted), sampled at the start of /// each `step()`. A new CPU is in the reset state; call [`ARM7TDMI::reset`] to make the two /// refill fetches at address 0, or load a state with [`ARM7TDMI::restore_state`]. #[allow(clippy::upper_case_acronyms)] pub struct ARM7TDMI { /// The host's bus (the reference's `_bus_read`, `_bus_write`, `_bus_idle`). pub bus: B, /// What the current mode sees; r[15] is the PC (plus 2L, see above). pub r: [u32; 16], pub(crate) bank: [[u32; 7]; BANK_COUNT], pub cpsr: u32, pub spsr: [u32; BANK_COUNT], /// None: this mode has no SPSR. pub spsr_bank: Option, pub mode_invalid: bool, pub pipeline: [u32; 2], pub next_fetch_seq: bool, pub irq_masked: bool, pub fiq_masked: bool, pub user_access: bool, /// The last instruction was an LDM^ without R15 (U7). pub glitch_next: bool, /// The reference swaps `_reg` for `_reg_or_user` and `_tick` for `_tick_in_glitch` on /// the instance during the instruction after an LDM^ (U7); Rust cannot replace a method /// on one value, so this flag selects the same behaviour in `reg` and `tick`. pub(crate) glitch: bool, pub coprocessor_cycle: bool, pub irq: bool, pub fiq: bool, pub(crate) cycles: u32, } impl ARM7TDMI { // ------------------------------------------------------------------ registers pub(crate) fn init_registers(bus: B) -> Self { ARM7TDMI { bus, r: [0; 16], bank: [[0; 7]; BANK_COUNT], cpsr: 0xD3, spsr: [0; BANK_COUNT], spsr_bank: None, mode_invalid: false, pipeline: [0, 0], next_fetch_seq: false, irq_masked: true, fiq_masked: true, user_access: false, glitch_next: false, glitch: false, coprocessor_cycle: false, irq: false, fiq: false, cycles: 0, } } /// The TBIT pin: the core is in Thumb state. pub fn thumb(&self) -> bool { self.cpsr & THUMB != 0 } pub fn mode(&self) -> u32 { self.cpsr & MODE_BITS } /// nTRANS: high for a privileged access; low in User mode and for LDRT/STRT (TRM 3.4). pub fn privileged(&self) -> bool { self.cpsr & MODE_BITS != USR && !self.user_access } /// Rn as the current mode sees it (R15: the instruction's address plus 2L, or 3L after /// a second address cycle). #[inline] pub(crate) fn reg(&self, n: usize) -> u32 { if self.glitch { return self.reg_or_user(n); } self.r[n] } /// Rn <- value as the current mode sees it. Writing R15 does not refill; callers that /// branch call `set_pc` or `refill`. #[inline] pub(crate) fn set_reg(&mut self, n: usize, value: u32) { self.r[n] = value; } /// 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). pub(crate) fn switch_mode(&mut self, new_mode: u32) { let old = bank_of(self.cpsr); let new = bank_of(new_mode); if old == BANK_FIQ { self.bank[BANK_FIQ].copy_from_slice(&self.r[8..15]); } else { self.bank[BANK_USER][0..5].copy_from_slice(&self.r[8..13]); let slot = if old == BANK_INVALID { BANK_USER } else { old }; self.bank[slot][5..7].copy_from_slice(&self.r[13..15]); } if new == BANK_FIQ { self.r[8..15].copy_from_slice(&self.bank[BANK_FIQ]); } else { self.r[8..13].copy_from_slice(&self.bank[BANK_USER][0..5]); let slot = if new == BANK_INVALID { BANK_USER } else { new }; self.r[13..15].copy_from_slice(&self.bank[slot][5..7]); } self.cpsr = (self.cpsr & !MODE_BITS) | (new_mode & MODE_BITS); self.spsr_bank = if new == BANK_USER || new == BANK_INVALID { None } else { Some(new) }; self.mode_invalid = new == BANK_INVALID; } /// 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). pub(crate) fn get_spsr(&self) -> u32 { match self.spsr_bank { None => self.cpsr, Some(bank) => self.spsr[bank], } } /// CPSR <- SPSR: data processing with S and Rd = R15, and LDM^ with R15 (DS 4.5.4, /// 4.11.4). pub(crate) fn restore_cpsr_from_spsr(&mut self) { let spsr = self.get_spsr(); self.switch_mode(spsr & MODE_BITS); self.cpsr = spsr; } // ------------------------------------------------------------------ the bus /// `_tick`, and during the instruction after an LDM^ `_tick_in_glitch`: the glitch lasts /// for the register reads of the instruction's first cycle, and ends with its second (U7). #[inline] pub(crate) fn tick(&mut self) { self.cycles += 1; if self.glitch && self.cycles >= 2 { self.end_glitch(); } } #[inline] pub(crate) fn end_glitch(&mut self) { self.glitch = false; } /// One opcode fetch (nOPC low). #[inline] pub(crate) fn fetch(&mut self, address: u32, width: u32, seq: bool) -> u32 { let value = self .bus .read(address, width, CODE | if seq { SEQ } else { 0 }); self.tick(); value & if width == 16 { 0xFFFF } else { MASK32 } } /// One data read of `width` bits at `address` as driven (never aligned: U1-U3). #[inline] pub(crate) fn read(&mut self, address: u32, width: u32, seq: bool, lock: bool) -> u32 { let value = self.bus.read( address, width, (if seq { SEQ } else { 0 }) | if lock { LOCK } else { 0 }, ); self.tick(); value & width_mask(width) } /// One data write; `value` is truncated to `width` bits, MAS[1:0] (TRM 3.4). #[inline] pub(crate) fn write(&mut self, address: u32, width: u32, value: u32, seq: bool, lock: bool) { self.bus.write( address, width, value & width_mask(width), (if seq { SEQ } else { 0 }) | if lock { LOCK } else { 0 }, ); self.tick(); } /// One internal (I) cycle; `address` is what the core drives meanwhile (timing.md). #[inline] pub(crate) fn idle(&mut self, address: u32) { self.bus.idle(address, self.coprocessor_cycle); self.tick(); } /// One coprocessor (C) cycle, reported through `idle()` with `coprocessor_cycle` /// true for the duration of the call (U17). pub(crate) fn coprocessor_cycle(&mut self, address: u32) { self.coprocessor_cycle = true; self.idle(address); self.coprocessor_cycle = false; } // ------------------------------------------------------------------ the pipeline /// 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). pub(crate) fn refill(&mut self) { let pc = self.r[15]; if self.cpsr & THUMB != 0 { let fetch = pc & !1; self.pipeline[0] = self.fetch(fetch, 16, false); self.pipeline[1] = self.fetch(fetch.wrapping_add(2), 16, true); self.r[15] = pc.wrapping_add(4); } else { let fetch = pc & !3; self.pipeline[0] = self.fetch(fetch, 32, false); self.pipeline[1] = self.fetch(fetch.wrapping_add(4), 32, true); self.r[15] = pc.wrapping_add(8); } self.next_fetch_seq = true; } /// R15 <- value and refill (any instruction that writes the PC). pub(crate) fn set_pc(&mut self, value: u32) { self.r[15] = value; self.refill(); } // ------------------------------------------------------------------ exceptions /// 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). pub(crate) fn enter_exception(&mut self, vector: u32, mode: u32, link: u32, mask_fiq: bool) { let saved = self.cpsr; self.spsr[bank_of(mode)] = saved; self.switch_mode(mode); self.cpsr = (self.cpsr | MASK_I | if mask_fiq { MASK_F } else { 0 }) & !THUMB; self.set_reg(14, link); self.set_pc(vector); } // ------------------------------------------------------------------ flags #[inline] pub(crate) fn set_nz(&mut self, value: u32) { self.cpsr = (self.cpsr & !(FLAG_N | FLAG_Z)) | (value & FLAG_N) | if value == 0 { FLAG_Z } else { 0 }; } // ------------------------------------------------------------------ state /// A snapshot of every register, bank, SPSR, the pipeline and the next fetch's type. pub fn capture_state(&self) -> CPUState { let mut banks = [[0u32; 7]; BANK_COUNT - 1]; banks.copy_from_slice(&self.bank[..BANK_INVALID]); let current = bank_of(self.cpsr); let r = &self.r; if current == BANK_FIQ { banks[BANK_FIQ].copy_from_slice(&r[8..15]); } else if current != BANK_INVALID { banks[current][5..7].copy_from_slice(&r[13..15]); banks[BANK_USER][0..5].copy_from_slice(&r[8..13]); } let mut spsr = [0u32; BANK_COUNT - 1]; spsr.copy_from_slice(&self.spsr[..BANK_INVALID]); CPUState { registers: *r, banks, cpsr: self.cpsr, spsr, pipeline: self.pipeline, next_fetch_seq: self.next_fetch_seq, } } /// Load a snapshot. `registers` win over the current mode's bank copy. pub fn restore_state(&mut self, state: &CPUState) { for (bank, values) in state.banks.iter().enumerate() { self.bank[bank] = *values; } self.bank[BANK_INVALID] = [0; 7]; self.spsr[..state.spsr.len()].copy_from_slice(&state.spsr); self.spsr[BANK_INVALID] = 0; self.cpsr = state.cpsr; let current = bank_of(state.cpsr); // As the reference: only BANK_USER has no SPSR here (a mode value that names no mode // keeps BANK_INVALID's slot, unlike switch_mode). self.spsr_bank = if current == BANK_USER { None } else { Some(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 = state.cpsr & MASK_I != 0; self.fiq_masked = state.cpsr & MASK_F != 0; self.user_access = false; self.glitch_next = false; // the last instruction was an LDM^ without R15 (U7) } // ------------------------------------------------------------------ step /// 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). pub fn step(&mut self) -> u32 { self.cycles = 0; let glitch = self.glitch_next; if glitch { // The instruction after an LDM^ reads banked registers OR'd with the User bank's // (U7, block.rs): its register reads go through reg_or_user. self.glitch_next = false; self.glitch = true; self.step_inner(); self.end_glitch(); } else { self.step_inner(); } self.cycles } fn step_inner(&mut self) { // 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). let cpsr = self.cpsr; if self.fiq && !(self.fiq_masked && cpsr & MASK_F != 0) { self.take_interrupt(0x1C, 0x11, 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 = self.cpsr & MASK_I != 0; self.fiq_masked = self.cpsr & MASK_F != 0; } else if self.irq && !(self.irq_masked && cpsr & MASK_I != 0) { self.take_interrupt(0x18, 0x12, false); self.irq_masked = self.cpsr & MASK_I != 0; self.fiq_masked = self.cpsr & MASK_F != 0; } else { self.irq_masked = self.cpsr & MASK_I != 0; self.fiq_masked = self.cpsr & MASK_F != 0; if self.cpsr & THUMB != 0 { self.execute_thumb(); } else { self.execute_arm(); } } } /// What the next [`ARM7TDMI::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. pub fn pending_interrupt(&self) -> Option { if self.fiq && !(self.fiq_masked && self.cpsr & MASK_F != 0) { return Some(0x11); } if self.irq && !(self.irq_masked && self.cpsr & MASK_I != 0) { return Some(0x12); } 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"). fn take_interrupt(&mut self, vector: u32, mode: u32, mask_fiq: bool) { let thumb = self.cpsr & THUMB; let link = if thumb != 0 { self.fetch(self.r[15] & !1, 16, self.next_fetch_seq); self.r[15] // pc + 4 } else { self.fetch(self.r[15] & !3, 32, self.next_fetch_seq); self.r[15].wrapping_sub(4) // pc + 4 }; self.enter_exception(vector, mode, link, mask_fiq); } /// 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). fn execute_arm(&mut self) { let 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) as usize][(self.cpsr >> 28) as usize] { let handler = ARM_HANDLERS[((op >> 16) & 0xFF0 | (op >> 4) & 0xF) as usize]; self.dispatch_arm(handler, op); } else { self.next_fetch_seq = true; self.r[15] = self.r[15].wrapping_add(4); } } fn execute_thumb(&mut self) { let 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); let handler = THUMB_HANDLERS[(op >> 6) as usize]; self.dispatch_thumb(handler, op); } } // The condition table equals condition_passes for every entry (checked once, in a test). #[cfg(test)] mod tests { use super::*; #[test] fn conditions_table_matches_condition_passes() { for cond in 0..16u32 { for flags in 0..16u32 { assert_eq!( CONDITIONS[cond as usize][flags as usize], condition_passes(cond, flags << 28) ); } } } }