# SPDX-License-Identifier: MIT """Registers, the fetch helpers, the addressing modes cycle by cycle, and the stack. 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 (docs/timing.md). Sources are cited by the keys of 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 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 :meth:`CoreMixin._fetch` and :meth:`CoreMixin._fetch_discard`, which hold ``cpu.fetch`` True for the length of the callback: a host tells an instruction-byte read from a data access by that attribute (docs/handoff-brief.md, "The bus contract"). """ from collections.abc import Callable # 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). N = 0x80 # negative: bit 7 of the result V = 0x40 # overflow U = 0x20 # unused: no flip-flop; reads as 1 when P is pushed B = 0x10 # break: no flip-flop; 1 in the byte BRK and PHP push, 0 for IRQ and NMI D = 0x08 # decimal mode I = 0x04 # IRQ disable Z = 0x02 # zero C = 0x01 # carry #: N and Z for every 8-bit result, so a handler sets both with one lookup. NZ = tuple((value & N) | (0 if value else Z) for value in range(256)) STACK = 0x0100 # the stack is page one; S is the low byte (DOC: DS 3.x) ReadByte = Callable[[int], int] WriteByte = Callable[[int, int], None] class CoreMixin: """Register state and the helpers every handler uses. The bus (``self._read``, ``self._write``), the interrupt requests and their poll are the frame's (``sixfiveohtwo.frame.CPUFrame``). """ def _init_registers(self) -> None: # 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. self.a = 0 self.x = 0 self.y = 0 self.s = 0 self.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. self.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). self.sync = False #: 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. self.fetch = False #: 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. self.opcode = 0 #: WAI has run and no interrupt has arrived yet (W65C02S row). self.waiting = False #: STP has run; only reset ends it (W65C02S row). self.stopped = False # Cycles a step adds to its opcode's base count: a page crossed by an # indexed read, a branch taken, the decimal cycle. self._extra = 0 # -- the instruction stream --------------------------------------------- def _fetch(self) -> int: """One instruction byte at PC; PC moves on.""" pc = self.pc self.pc = (pc + 1) & 0xFFFF self.fetch = True value = self._read(pc) self.fetch = False return value def _fetch_discard(self) -> None: """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). """ # MEASURED: CAP, both parts (cycles, direction, and the address through the byte read). self.fetch = True self._read(self.pc) self.fetch = False def _fetch_word(self) -> int: low = self._fetch() # little-endian: low byte first (DOC: DS; MEASURED: CAP) return self._fetch() << 8 | low # -- flags ---------------------------------------------------------------- def _set_nz(self, value: int) -> int: self.p = (self.p & ~(N | Z)) | NZ[value] return value # -- the stack ------------------------------------------------------------ # Write then decrement, increment then read: DOC (DS); MEASURED (CAP's pushed bytes). def _push(self, value: int) -> None: s = self.s self._write(STACK | s, value) self.s = (s - 1) & 0xFF def _pull(self) -> int: s = (self.s + 1) & 0xFF self.s = s return self._read(STACK | s) # -- 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. def _ea_zp(self) -> int: """`zp`: the operand byte is the address.""" return self._fetch() def _ea_zpx(self) -> int: """`zp,X`: the operand byte is read a second time, then the sum within page zero.""" # MEASURED: the dummy address (CAP); OBSERVED otherwise in SST (C18). zp = self._fetch() self._read((self.pc - 1) & 0xFFFF) # CAP, both parts; SST reads `zp` instead (C18) return (zp + self.x) & 0xFF def _ea_zpy(self) -> int: """`zp,Y` (LDX and STX only).""" zp = self._fetch() self._read((self.pc - 1) & 0xFFFF) # MEASURED (CAP): as zp,X (C18) return (zp + self.y) & 0xFF def _ea_abs(self) -> int: """`abs`.""" return 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). def _ea_abx(self) -> int: """`abs,X`, read: 4 cycles, 5 across a page (CAP: `BD` 4/5).""" base = self._fetch_word() address = (base + self.x) & 0xFFFF if (address ^ base) & 0xFF00: self._read((self.pc - 1) & 0xFFFF) self._extra += 1 return address def _ea_aby(self) -> int: """`abs,Y`, read: 4 cycles, 5 across a page (CAP: `B9` 4/5).""" base = self._fetch_word() address = (base + self.y) & 0xFFFF if (address ^ base) & 0xFF00: self._read((self.pc - 1) & 0xFFFF) self._extra += 1 return address def _ea_abx_fixed(self) -> int: """`abs,X`, store or INC/DEC: always the extra cycle.""" base = self._fetch_word() address = (base + self.x) & 0xFFFF self._read((self.pc - 1) & 0xFFFF if (address ^ base) & 0xFF00 else address) return address def _ea_aby_fixed(self) -> int: """`abs,Y`, store: always the extra cycle.""" base = self._fetch_word() address = (base + self.y) & 0xFFFF self._read((self.pc - 1) & 0xFFFF if (address ^ base) & 0xFF00 else address) return address def _ea_idx(self) -> int: """`(zp,X)`: a dummy read of the unindexed address, then the pointer.""" zp = self._fetch() # MEASURED: the dummy address (CAP); SST's differs (C18, OBSERVED). self._read((self.pc - 1) & 0xFFFF) # CAP: the operand byte again (SST reads `zp`, C18) pointer = (zp + self.x) & 0xFF low = self._read(pointer) # The page-zero wrap: the NMOS rule, kept; OBSERVED (SST covers every pointer). return self._read((pointer + 1) & 0xFF) << 8 | low # the pointer wraps in page zero def _ea_idy(self) -> int: """`(zp),Y`, read: 5 cycles, 6 across a page (CAP: `B1` 5/6).""" zp = self._fetch() low = self._read(zp) high_address = (zp + 1) & 0xFF base = self._read(high_address) << 8 | low address = (base + self.y) & 0xFFFF if (address ^ base) & 0xFF00: # MEASURED: CAP, the pointer's high byte again; SST's differs (C15, OBSERVED). self._read(high_address) self._extra += 1 return address def _ea_idy_fixed(self) -> int: """`(zp),Y`, store: always the extra cycle (CAP: `91` 6).""" zp = self._fetch() low = self._read(zp) high_address = (zp + 1) & 0xFF base = self._read(high_address) << 8 | low self._read(high_address) return (base + self.y) & 0xFFFF def _ea_ind(self) -> int: """`(zp)`, the 65C02's new mode: 5 cycles (CAP: `B2` 5).""" # MEASURED (CAP); DOC (DS Table 5-7). zp = self._fetch() low = self._read(zp) return self._read((zp + 1) & 0xFF) << 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: ``self._read(self._ea_zp())`` would look ``self._read`` up before # the addressing cycles run, and the frame replaces that attribute when a # bus callback changes an interrupt request (its poll depends on it). def _rd_imm(self) -> int: return self._fetch() def _rd_zp(self) -> int: address = self._fetch() return self._read(address) def _rd_zpx(self) -> int: address = self._ea_zpx() return self._read(address) def _rd_zpy(self) -> int: address = self._ea_zpy() return self._read(address) def _rd_abs(self) -> int: address = self._fetch_word() return self._read(address) def _rd_abx(self) -> int: address = self._ea_abx() return self._read(address) def _rd_aby(self) -> int: address = self._ea_aby() return self._read(address) def _rd_idx(self) -> int: address = self._ea_idx() return self._read(address) def _rd_idy(self) -> int: address = self._ea_idy() return self._read(address) def _rd_ind(self) -> int: address = self._ea_ind() return self._read(address) # -- read-modify-write ------------------------------------------------------ def _modify(self, address: int, operation: Callable[[int], int]) -> None: """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. """ # MEASURED (CAP: two reads of the operand, one write); DOC (DS Table 7-1). value = self._read(address) self._read(address) self._write(address, operation(value))