// SPDX-License-Identifier: MIT //! Registers, the fetch helpers, the addressing modes cycle by cycle, and the //! stack (`_core.py`). //! //! A 65C02 puts an address on the bus and reads or writes in every cycle, and //! this core makes each of those accesses, dummy reads included, in the chip's //! order (the reference's docs/timing.md). Sources are cited by the keys of the //! reference's docs/start-here.md: CAP is the logic-analyser captures of real //! chips (tier 1), DS the W65C02S data sheet (tier 2), CL and LK Clark's and //! Laughton's research (tier 3), SST the emulator-generated SingleStepTests //! corpus (tier 5). U and C numbers are entries of the reference's //! docs/undocumented-behavior.md. //! //! Which cycles exist and which of them write is CAP's for every sequence //! here. The *address* of a dummy read is known at tier 1 only where the //! captured data identifies it (the captures hold no address bus, U4); each //! helper says which evidence its dummy address rests on. //! //! The instruction stream is read through [`Cmos65c02::fetch_byte`] and //! [`Cmos65c02::fetch_discard`], which hold `fetch` true for the length of the //! callback: a host tells an instruction-byte read from a data access by that //! signal (the reference's docs/handoff-brief.md, "The bus contract"). //! //! Differences forced by Rust: //! //! - A Python callback reads `cpu.sync`, `cpu.fetch`, `cpu.opcode` (and //! anything else) off the CPU object while the CPU is calling it. A Rust //! callback cannot borrow the CPU then, so every callback receives //! [`Signals`], a copy of what a host reads there (`sync`, `fetch`, //! `opcode`, and `pc`, which the capture replay's paging model reads), with //! `&mut Frame` for its interrupt requests and `note_stall`, as in //! 6502-rust. //! - The Python frame swaps its bus callables for confirming wrappers when a //! request changes; here every access calls [`Frame::access`] first, which //! is the same check (6502-rust's frame). The reference's trap ("never write //! `self._read(self._fetch())`") cannot happen here: the confirmation is at //! the access, not at a method lookup. //! - `_fetch` is `fetch_byte` here, because `fetch` is the signal's field. //! - `_modify` takes the operation as a function pointer, the Python one a //! bound method. use crate::cpu::Row; use crate::dispatch::Entry; use sixfiveohtwo::frame::Frame; // Evidence tags (emulator-lineage docs/methodology.md) sit beside each rule: // MEASURED = CAP; DOC = a data sheet or CL/LK/GF/BC/GW; TEST ROM = LT; // OBSERVED = SST or MAME; HYPOTHESIS = a default nothing measures. // Status register bits, P (DS 3.11, the Processor Status Register figure; Table 6-4's header). // DOC: DS 3.11. Bit 5 and B as pushed: MEASURED too (CAP's written stack bytes). pub const N: u8 = 0x80; // negative: bit 7 of the result pub const V: u8 = 0x40; // overflow pub const U: u8 = 0x20; // unused: no flip-flop; reads as 1 when P is pushed pub const B: u8 = 0x10; // break: no flip-flop; 1 in the byte BRK and PHP push, 0 for IRQ and NMI pub const D: u8 = 0x08; // decimal mode pub const I: u8 = sixfiveohtwo::frame::I; // IRQ disable (bit 2 on every part: the frame's) pub const Z: u8 = 0x02; // zero pub const C: u8 = 0x01; // carry /// N and Z for every 8-bit result, so a handler sets both with one lookup. pub(crate) const NZ: [u8; 256] = { let mut table = [0u8; 256]; let mut value = 0; while value < 256 { table[value] = (value as u8 & N) | if value == 0 { Z } else { 0 }; value += 1; } table }; pub const STACK: u16 = 0x0100; // the stack is page one; S is the low byte (DOC: DS 3.x) /// What a host may read of the CPU inside a bus callback. /// /// The reference's host reads these attributes off the CPU object during the /// callback; here they arrive with it (see the module header). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Signals { /// True during an opcode fetch: the chip's SYNC pin (DS 3.13), and the /// first cycle of an interrupt entry and of reset (CAP). pub sync: bool, /// True during every read of the instruction stream at PC: the opcode, /// the operand bytes, and the byte a one-byte instruction reads and drops. pub fetch: bool, /// The opcode of the instruction in progress. The fetch callback itself /// still sees the previous instruction's; an interrupt entry and reset /// leave it unchanged. pub opcode: u8, /// PC as it stands during the callback (the fetch helpers move it on /// before the read, as the reference's do). pub pc: u16, } /// The host's side of the bus: one call per cycle, in the chip's order. /// /// `read(address)` is every read cycle, dummy reads included; `write(address, /// value)` every write cycle. A callback may take as long as the host likes /// and may change interrupt requests through `frame`; if it holds the CPU /// (RDY, a bus grant) it calls [`Frame::note_stall`] as the hold begins and /// after each held cycle, in a read or a write callback (the reference's R1). pub trait Bus { fn read(&mut self, address: u16, frame: &mut Frame, signals: Signals) -> u8; fn write(&mut self, address: u16, value: u8, frame: &mut Frame, signals: Signals); } /// The 65C02 instruction core (`CMOS65C02`); a part is a [`Row`]. /// /// Every cycle is exactly one bus callback, in the chip's order, dummy reads /// included: a 65C02 reads or writes in every cycle, so there is no third /// callable. `step()` runs one instruction, one interrupt entry, one reset, /// or one cycle of `WAI`/`STP` waiting, and returns how many callbacks it /// made. The core keeps no time. /// /// Registers are plain fields: `a`, `x`, `y`, `s` (8 bits), `pc` (16 bits) /// and `p`, which keeps bit 5 set and B clear. A new CPU has zeroed /// registers and I set; [`Frame::request_reset`] runs the chip's start /// sequence. The interrupt inputs, their poll and `step()`'s skeleton are /// 6502-rust's [`Frame`] and [`sixfiveohtwo::frame::Part`]. pub struct Cmos65c02 { pub a: u8, pub x: u8, pub y: u8, pub s: u8, pub pc: u16, pub p: u8, /// True during an opcode fetch: the chip's SYNC pin (DS 3.13). pub sync: bool, /// True during every read of the instruction stream at PC: the opcode, /// the operand bytes, and the byte a one-byte instruction reads and drops. pub fetch: bool, /// The opcode of the instruction in progress. The fetch callback itself /// still sees the previous instruction's; an interrupt entry and reset /// leave it unchanged. pub opcode: u8, /// WAI has run and no interrupt has arrived yet (W65C02S row). pub waiting: bool, /// STP has run; only reset ends it (W65C02S row). pub stopped: bool, pub bus: T, pub frame: Frame, /// The part: which cells the opcode table replaces, and the U defaults. pub(crate) row: Row, /// The 256 (handler, mode, base cycles) entries of the row, built once /// when the CPU is made (the reference builds them once per class). pub(crate) table: [Entry; 256], // Cycles a step adds to its opcode's base count: a page crossed by an // indexed read, a branch taken, the decimal cycle. pub(crate) extra: u32, } impl Cmos65c02 { pub(crate) fn init_registers(row: Row, bus: T) -> Self { Cmos65c02 { // A, X, Y and S are not initialised by reset (DS 3.11); zero makes // hosts and traces reproducible. DOC (DS 3.11) that they are not // initialised; the zeros are a host convention, not a hardware claim. a: 0, x: 0, y: 0, s: 0, pc: 0, // Bit 5 is kept set and B clear: neither is a flip-flop, and this is // the value P reads as everywhere except on the stack. I set: DOC (DS // 3.11, reset sets I); a new CPU is expected to be reset before use. p: U | I, // True during an opcode fetch: the chip's SYNC pin (DS 3.13). // DOC (DS 3.13); MEASURED (CAP records SYNC every cycle). sync: false, fetch: false, opcode: 0, waiting: false, stopped: false, bus, frame: Frame::default(), row, table: crate::dispatch::build_table(&row), extra: 0, } } // -- the bus (the frame's `_read` and `_write`) --------------------------- #[inline] pub(crate) fn signals(&self) -> Signals { Signals { sync: self.sync, fetch: self.fetch, opcode: self.opcode, pc: self.pc, } } #[inline] pub(crate) fn read(&mut self, address: u16) -> u8 { self.frame.access(); let signals = self.signals(); self.bus.read(address, &mut self.frame, signals) } #[inline] pub(crate) fn write(&mut self, address: u16, value: u8) { self.frame.access(); let signals = self.signals(); self.bus.write(address, value, &mut self.frame, signals); } // -- the instruction stream --------------------------------------------- /// One instruction byte at PC; PC moves on. #[inline] pub(crate) fn fetch_byte(&mut self) -> u8 { let pc = self.pc; self.pc = pc.wrapping_add(1); self.fetch = true; let value = self.read(pc); self.fetch = false; value } /// A read at PC whose byte is dropped; PC stays. /// /// The second cycle of a one-byte instruction (CAP: 2 cycles, both reads; /// the address is the next opcode's: rung 4 finds the captured byte equal /// to the opcode fetched next). #[inline] pub(crate) fn fetch_discard(&mut self) { // MEASURED: CAP, both parts (cycles, direction, and the address through the byte read). self.fetch = true; self.read(self.pc); self.fetch = false; } pub(crate) fn fetch_word(&mut self) -> u16 { let low = self.fetch_byte() as u16; // little-endian: low byte first (DOC: DS; MEASURED: CAP) ((self.fetch_byte() as u16) << 8) | low } // -- flags ---------------------------------------------------------------- #[inline] pub(crate) fn set_nz(&mut self, value: u8) -> u8 { self.p = (self.p & !(N | Z)) | NZ[value as usize]; value } // -- the stack ------------------------------------------------------------ // Write then decrement, increment then read: DOC (DS); MEASURED (CAP's pushed bytes). pub(crate) fn push(&mut self, value: u8) { let s = self.s; self.write(STACK | s as u16, value); self.s = s.wrapping_sub(1); } pub(crate) fn pull(&mut self) -> u8 { let s = self.s.wrapping_add(1); self.s = s; self.read(STACK | s as u16) } // -- addressing modes: the cycles up to the operand, returning its address -- // docs/timing.md, "Addressing modes". Cycle counts and the read/write order // are CAP's; the dummy addresses are noted line by line. // MEASURED (CAP) for every count and direction below; DOC (DS Table 5-7) // agrees on the counts. /// `zp`: the operand byte is the address. pub(crate) fn ea_zp(&mut self) -> u16 { self.fetch_byte() as u16 } /// `zp,X`: the operand byte is read a second time, then the sum within page zero. pub(crate) fn ea_zpx(&mut self) -> u16 { // MEASURED: the dummy address (CAP); OBSERVED otherwise in SST (C18). let zp = self.fetch_byte(); self.read(zp as u16); zp.wrapping_add(self.x) as u16 } /// `zp,Y` (LDX and STX only). pub(crate) fn ea_zpy(&mut self) -> u16 { let zp = self.fetch_byte(); self.read(self.pc.wrapping_sub(1)); // MEASURED (CAP): as zp,X (C18) zp.wrapping_add(self.y) as u16 } /// `abs`. pub(crate) fn ea_abs(&mut self) -> u16 { self.fetch_word() } // Indexing across a page costs a cycle, in which the chip reads again the // address of the cycle before instead of the NMOS part's wrong address: // "extra read of last instruction byte" (DS Table 7-1). For `abs,X` and // `abs,Y` that is the operand's high byte at PC+2; for `(zp),Y` it is the // pointer's high byte in page zero (CAP, both parts: the captured byte is // the one read the cycle before; SST re-reads PC+1 there, C15). // // A store, and INC and DEC `abs,X`, take the cycle whether or not a page // is crossed (CAP: `9D` 5, `91` 6, `DE FE` 7 in every execution; C11). // Without a crossing the cycle reads the operand's own address, as the // NMOS part does (CAP, both parts; SST re-reads the instruction byte, C14). // MEASURED (CAP) for the rules in this comment and the helpers below it: // the cycles, and each dummy address through the byte it returned; DOC (DS // Table 7-1) for the page-cross rule. SST's addresses differ (C14, C15: OBSERVED). /// `abs,X`, read: 4 cycles, 5 across a page (CAP: `BD` 4/5). pub(crate) fn ea_abx(&mut self) -> u16 { let base = self.fetch_word(); let address = base.wrapping_add(self.x as u16); if (address ^ base) & 0xFF00 != 0 { self.read(self.pc.wrapping_sub(1)); self.extra += 1; } address } /// `abs,Y`, read: 4 cycles, 5 across a page (CAP: `B9` 4/5). pub(crate) fn ea_aby(&mut self) -> u16 { let base = self.fetch_word(); let address = base.wrapping_add(self.y as u16); if (address ^ base) & 0xFF00 != 0 { self.read(self.pc.wrapping_sub(1)); self.extra += 1; } address } /// `abs,X`, store or INC/DEC: always the extra cycle. pub(crate) fn ea_abx_fixed(&mut self) -> u16 { let base = self.fetch_word(); let address = base.wrapping_add(self.x as u16); self.read(if (address ^ base) & 0xFF00 != 0 { self.pc.wrapping_sub(1) } else { address }); address } /// `abs,Y`, store: always the extra cycle. pub(crate) fn ea_aby_fixed(&mut self) -> u16 { let base = self.fetch_word(); let address = base.wrapping_add(self.y as u16); self.read(if (address ^ base) & 0xFF00 != 0 { self.pc.wrapping_sub(1) } else { address }); address } /// `(zp,X)`: a dummy read of the unindexed address, then the pointer. pub(crate) fn ea_idx(&mut self) -> u16 { let zp = self.fetch_byte(); // MEASURED: the dummy address (CAP); SST's differs (C18, OBSERVED). self.read(self.pc.wrapping_sub(1)); // CAP: the operand byte again (SST reads `zp`, C18) let pointer = zp.wrapping_add(self.x); let low = self.read(pointer as u16) as u16; // The page-zero wrap: the NMOS rule, kept; OBSERVED (SST covers every pointer). ((self.read(pointer.wrapping_add(1) as u16) as u16) << 8) | low // the pointer wraps in page zero } /// `(zp),Y`, read: 5 cycles, 6 across a page (CAP: `B1` 5/6). pub(crate) fn ea_idy(&mut self) -> u16 { let zp = self.fetch_byte(); let low = self.read(zp as u16) as u16; let high_address = zp.wrapping_add(1) as u16; let base = ((self.read(high_address) as u16) << 8) | low; let address = base.wrapping_add(self.y as u16); if (address ^ base) & 0xFF00 != 0 { // MEASURED: CAP, the pointer's high byte again; SST's differs (C15, OBSERVED). self.read(high_address); self.extra += 1; } address } /// `(zp),Y`, store: always the extra cycle (CAP: `91` 6). pub(crate) fn ea_idy_fixed(&mut self) -> u16 { let zp = self.fetch_byte(); let low = self.read(zp as u16) as u16; let high_address = zp.wrapping_add(1) as u16; let base = ((self.read(high_address) as u16) << 8) | low; self.read(high_address); base.wrapping_add(self.y as u16) } /// `(zp)`, the 65C02's new mode: 5 cycles (CAP: `B2` 5). pub(crate) fn ea_ind(&mut self) -> u16 { // MEASURED (CAP); DOC (DS Table 5-7). let zp = self.fetch_byte(); let low = self.read(zp as u16) as u16; ((self.read(zp.wrapping_add(1) as u16) as u16) << 8) | low } // -- the same modes for an instruction that only reads its operand ---------- // Each returns the operand's value; the immediate operand is an // instruction byte, the others are data. // // The address is computed in a statement of its own, here and in every // handler, as in the reference (where it matters for the frame's // confirming wrappers; here it is kept for the line-by-line match). pub(crate) fn rd_imm(&mut self) -> u8 { self.fetch_byte() } pub(crate) fn rd_zp(&mut self) -> u8 { let address = self.fetch_byte() as u16; self.read(address) } pub(crate) fn rd_zpx(&mut self) -> u8 { let address = self.ea_zpx(); self.read(address) } pub(crate) fn rd_zpy(&mut self) -> u8 { let address = self.ea_zpy(); self.read(address) } pub(crate) fn rd_abs(&mut self) -> u8 { let address = self.fetch_word(); self.read(address) } pub(crate) fn rd_abx(&mut self) -> u8 { let address = self.ea_abx(); self.read(address) } pub(crate) fn rd_aby(&mut self) -> u8 { let address = self.ea_aby(); self.read(address) } pub(crate) fn rd_idx(&mut self) -> u8 { let address = self.ea_idx(); self.read(address) } pub(crate) fn rd_idy(&mut self) -> u8 { let address = self.ea_idy(); self.read(address) } pub(crate) fn rd_ind(&mut self) -> u8 { let address = self.ea_ind(); self.read(address) } // -- read-modify-write ------------------------------------------------------ /// Read, read again, write: "two read and one write cycle" (DS Table 7-1; CAP: one write). /// /// The NMOS part reads once and writes twice. Rung 4 finds both reads /// returning the operand's byte on two real parts. pub(crate) fn modify(&mut self, address: u16, operation: fn(&mut Self, u8) -> u8) { // MEASURED (CAP: two reads of the operand, one write); DOC (DS Table 7-1). let value = self.read(address); self.read(address); let result = operation(self, value); self.write(address, result); } }