"""Registers, the cycle primitives, operand access and the addressing modes. Every cycle of the 65C816 is one callback, IO cycles included, each with the 24-bit address the chip drives and its kind (VDA, VPA, VPB, MLB) readable as ``cpu.vda`` and the rest while the callback runs. The addressing modes below are written cycle by cycle from the datasheet's Table 5-7 (DS, WDC W65C816S, 2024-03-13, pp. 36-42, rows cited as "row 10a"), with the emulation-mode wrapping rules of docs/undocumented-behavior.md U1-U4 layered on top. """ from collections.abc import Callable # P (DS section 2.9, Figure 2-2). In emulation mode bits 5 and 4 are not M # and X: the core keeps both set there, so that M and X read as 1 (8-bit) # without a test of E in every handler. N = 0x80 V = 0x40 M = 0x20 # accumulator and memory width: 1 = 8-bit X = 0x10 # index width: 1 = 8-bit (emulation mode: the B bit of a pushed P) D = 0x08 I = 0x04 Z = 0x02 C = 0x01 # A cycle's kind: which of VDA, VPA, VPB and MLB the chip asserts (DS # section 2.19-2.22). VPB and MLB are active-low pins; here 1 means asserted. VDA = 0x01 VPA = 0x02 VPB = 0x04 MLB = 0x08 OPCODE = VDA | VPA # the opcode fetch: both, as the 6502's SYNC PROGRAM = VPA # an operand byte from the instruction stream DATA = VDA VECTOR = VDA | VPB IO = 0 # an internal cycle: neither, the address "invalid" (DS section 7.5) ReadByte = Callable[[int], int] WriteByte = Callable[[int, int], None] Idle = Callable[[int], None] def nz8(value: int) -> int: return (value & N) | (0 if value & 0xFF else Z) def nz16(value: int) -> int: return (value >> 8 & N) | (0 if value else Z) class CoreMixin: """Private register state, bus primitives, operand access and addressing modes.""" def _init_registers(self) -> None: # The registers hold whatever they held until reset; zero makes # traces reproducible. Reset itself sets only what DS section 2.25 # lists (see _accept_reset). self.a = 0 # C, all 16 bits; A is the low byte, B the high self.x = 0 self.y = 0 self.s = 0x01FF self.d = 0 self.dbr = 0 self.pbr = 0 self.pc = 0 self.p = M | X | I self.e = 1 self.waiting = False # WAI has run; an interrupt request ends it self.stopped = False # STP has run; only reset ends it self._kind = IO self._cycles = 0 # How the second byte of a 16-bit operand follows the first: set by # every addressing mode (row notes). In the bank: the offset wraps at # $FFFF and the bank stays (program bytes, direct page and stack in # bank 0). Not in the bank: the carry reaches the bank (DS section # 7.3, U4). self._in_bank = False self._operand_kind = DATA # -- the pins as a callback sees them ------------------------------- @property def vda(self) -> bool: """Valid data address: the cycle reads or writes data.""" return bool(self._kind & VDA) @property def vpa(self) -> bool: """Valid program address: the cycle reads the instruction stream.""" return bool(self._kind & VPA) @property def vpb(self) -> bool: """Vector pull: the cycle reads an interrupt vector.""" return bool(self._kind & VPB) @property def mlb(self) -> bool: """Memory lock: the cycle is part of a read-modify-write.""" return bool(self._kind & MLB) @property def m(self) -> bool: """The M flag as the M/X pin shows it: True for an 8-bit accumulator.""" return bool(self.p & M) @property def x_flag(self) -> bool: """The X flag as the M/X pin shows it: True for 8-bit index registers.""" return bool(self.p & X) # -- cycles ---------------------------------------------------------- def _cycle_read(self, address: int, kind: int) -> int: self._kind = kind self._cycles += 1 return self._read(address) def _cycle_write(self, address: int, value: int, kind: int = DATA) -> None: self._kind = kind self._cycles += 1 self._write(address, value) def _io(self, address: int, kind: int = IO) -> None: """An internal cycle: the address is driven, nothing is read or written.""" self._kind = kind self._cycles += 1 if self._deferred is not None: self._confirm() self._idle(address) def _program_address(self) -> int: return self.pbr << 16 | self.pc def _fetch(self) -> int: """One operand byte at PBR,PC; PC wraps within the bank (U4).""" pc = self.pc self.pc = (pc + 1) & 0xFFFF return self._cycle_read(self.pbr << 16 | pc, PROGRAM) def _fetch_word(self) -> int: low = self._fetch() return self._fetch() << 8 | low def _io_operand(self) -> None: """The IO cycle Table 5-7 drives at the last operand byte's address (PBR,PC-1).""" self._io(self.pbr << 16 | (self.pc - 1) & 0xFFFF) def _io_pc(self) -> None: """The IO cycle at PBR,PC: an implied instruction's second cycle (row 19a).""" self._io(self.pbr << 16 | self.pc) # -- operands of either width --------------------------------------- def _next(self, address: int) -> int: """The address of a 16-bit operand's high byte, as the mode left it.""" if self._in_bank: return (address & 0xFF0000) | ((address + 1) & 0xFFFF) return (address + 1) & 0xFFFFFF def _load(self, address: int, wide: bool) -> int: """Data low, then with 16-bit data the high byte at the next address (note 1).""" kind = self._operand_kind low = self._cycle_read(address, kind) if not wide: return low return self._cycle_read(self._next(address), kind) << 8 | low def _store(self, address: int, value: int, wide: bool) -> None: self._cycle_write(address, value & 0xFF) if wide: self._cycle_write(self._next(address), value >> 8) def _modify(self, address: int, wide: bool, operation: Callable[[int], int]) -> None: """A read-modify-write (row 1d): read, modify cycle, write, with MLB throughout. 16-bit data reads low then high and writes high then low. The modify cycle is an IO cycle in native mode; in emulation mode RWB is low and the old value is on the bus, with VDA low (note 17; contested, C3): the core reports it as a write and the board decides whether it reaches anything. """ high_address = self._next(address) value = self._cycle_read(address, DATA | MLB) if wide: value |= self._cycle_read(high_address, DATA | MLB) << 8 if self.e: self._cycle_write(address, value, MLB) else: self._io(high_address if wide else address, MLB) result = operation(value) if wide: self._cycle_write(high_address, result >> 8, DATA | MLB) self._cycle_write(address, result & 0xFF, DATA | MLB) # -- addressing modes (Table 5-7) ----------------------------------- # Each makes its addressing cycles and returns the 24-bit address of the # operand's low byte, having set _in_bank and _operand_kind for its high # byte. The `_w` variants are for stores and read-modify-writes, which # spend note 4's IO cycle whatever the index. def _ea_imm_m(self) -> int: """`#` with the accumulator's width (row 18).""" return self._immediate(not self.p & M) def _ea_imm_x(self) -> int: """`#` with the index registers' width (row 18).""" return self._immediate(not self.p & X) def _immediate(self, wide: bool) -> int: pc = self.pc self.pc = (pc + (2 if wide else 1)) & 0xFFFF self._in_bank = True self._operand_kind = PROGRAM return self.pbr << 16 | pc def _data_mode(self, in_bank: bool) -> None: self._in_bank = in_bank self._operand_kind = DATA def _ea_abs(self) -> int: """`a`: DBR,AA (row 1a).""" address = self._fetch_word() self._data_mode(False) return self.dbr << 16 | address def _indexed(self, base: int, index: int, write: bool) -> int: # Note 4: an IO cycle at DBR,AAH,(AAL+index) for a page crossed, a # store, or 16-bit index registers; the index carries into the bank. if write or not self.p & X or (base & 0xFF) + index > 0xFF: self._io(self.dbr << 16 | (base & 0xFF00) | ((base + index) & 0xFF)) self._data_mode(False) return ((self.dbr << 16) + base + index) & 0xFFFFFF def _ea_abx(self) -> int: """`a,x` (row 6a).""" return self._indexed(self._fetch_word(), self.x, False) def _ea_aby(self) -> int: """`a,y` (row 7).""" return self._indexed(self._fetch_word(), self.y, False) def _ea_abx_w(self) -> int: """`a,x` for a store or read-modify-write (rows 6a, 6b).""" return self._indexed(self._fetch_word(), self.x, True) def _ea_aby_w(self) -> int: """`a,y` for a store (row 7).""" return self._indexed(self._fetch_word(), self.y, True) def _ea_long(self) -> int: """`al`: AAB,AA (row 4a).""" address = self._fetch_word() bank = self._fetch() self._data_mode(False) return bank << 16 | address def _ea_long_x(self) -> int: """`al,x`: AAB,AA+X, the index carrying into the bank (row 5).""" address = self._fetch_word() bank = self._fetch() self._data_mode(False) return ((bank << 16) + address + self.x) & 0xFFFFFF def _direct_offset(self) -> int: """The direct-page operand, with note 2's IO cycle when D.l is not 0.""" offset = self._fetch() if self.d & 0xFF: self._io_operand() return offset def _direct(self, offset: int) -> int: """Bank 0, D + offset. U1: in emulation mode with D.l = 0 the 6502's modes stay in page D.h; otherwise the sum wraps at $FFFF.""" if self.e and not self.d & 0xFF: return (self.d & 0xFF00) | (offset & 0xFF) return (self.d + offset) & 0xFFFF def _ea_dp(self) -> int: """`d` (row 10a).""" address = self._direct(self._direct_offset()) self._data_mode(True) return address def _ea_dpx(self) -> int: """`d,x` (row 16a).""" offset = self._direct_offset() self._io_operand() address = self._direct(offset + self.x) self._data_mode(True) return address def _ea_dpy(self) -> int: """`d,y` (row 17).""" offset = self._direct_offset() self._io_operand() address = self._direct(offset + self.y) self._data_mode(True) return address def _pointer16(self, low_address: int, high_address: int) -> int: low = self._cycle_read(low_address, DATA) return self._cycle_read(high_address, DATA) << 8 | low def _direct_pointer(self, offset: int) -> int: """A two-byte pointer in the direct page; U1's page wrap applies to both bytes.""" low_address = self._direct(offset) return self._pointer16(low_address, self._direct(offset + 1)) def _ea_idx(self) -> int: """`(d,x)` (row 11). U3 (C4): in emulation mode with D.l not 0 the pointer's high byte comes from the low byte's page, as gilyon's cputest, bsnes, ares, Mesen2 and MAME have it; the corpus disagrees and those cases are excluded. """ offset = self._direct_offset() self._io_operand() if self.e and self.d & 0xFF: low_address = (self.d + offset + self.x) & 0xFFFF high_address = (low_address & 0xFF00) | ((low_address + 1) & 0xFF) pointer = self._pointer16(low_address, high_address) else: pointer = self._direct_pointer(offset + self.x) self._data_mode(False) return self.dbr << 16 | pointer def _ea_ind(self) -> int: """`(d)` (row 12).""" pointer = self._direct_pointer(self._direct_offset()) self._data_mode(False) return self.dbr << 16 | pointer def _indirect_y(self, write: bool) -> int: pointer = self._direct_pointer(self._direct_offset()) return self._indexed(pointer, self.y, write) def _ea_idy(self) -> int: """`(d),y` (row 13).""" return self._indirect_y(False) def _ea_idy_w(self) -> int: """`(d),y` for a store (row 13).""" return self._indirect_y(True) def _long_pointer(self) -> int: # [d] is a "new" mode: no page wrap in emulation mode (U1), bank 0. base = self.d + self._direct_offset() low = self._cycle_read(base & 0xFFFF, DATA) high = self._cycle_read((base + 1) & 0xFFFF, DATA) bank = self._cycle_read((base + 2) & 0xFFFF, DATA) return bank << 16 | high << 8 | low def _ea_ind_long(self) -> int: """`[d]` (row 15).""" address = self._long_pointer() self._data_mode(False) return address def _ea_ind_long_y(self) -> int: """`[d],y` (row 14).""" address = (self._long_pointer() + self.y) & 0xFFFFFF self._data_mode(False) return address def _ea_sr(self) -> int: """`d,s`: bank 0, S + offset (row 23).""" offset = self._fetch() self._io_operand() self._data_mode(True) return (self.s + offset) & 0xFFFF def _ea_sr_y(self) -> int: """`(d,s),y` (row 24).""" offset = self._fetch() self._io_operand() base = self.s + offset pointer = self._pointer16(base & 0xFFFF, (base + 1) & 0xFFFF) self._io((base + 1) & 0xFFFF) self._data_mode(False) return ((self.dbr << 16) + pointer + self.y) & 0xFFFFFF # -- the stack (bank 0; S points at the next free byte) ------------- def _push(self, value: int) -> None: """Push for the 6502's instructions: in emulation mode S wraps in page one (U2).""" s = self.s self._cycle_write(s, value) self.s = (s & 0xFF00) | ((s - 1) & 0xFF) if self.e else (s - 1) & 0xFFFF def _pull(self) -> int: s = self.s s = (s & 0xFF00) | ((s + 1) & 0xFF) if self.e else (s + 1) & 0xFFFF self.s = s return self._cycle_read(s, DATA) def _push_new(self, value: int) -> None: """Push for the new instructions: S steps in 16 bits even in emulation mode (U2).""" s = self.s self._cycle_write(s, value) self.s = (s - 1) & 0xFFFF def _pull_new(self) -> int: s = (self.s + 1) & 0xFFFF self.s = s return self._cycle_read(s, DATA) def _fix_stack(self) -> None: """After a new instruction in emulation mode, SH is forced back to $01 (U2).""" if self.e: self.s = 0x0100 | (self.s & 0xFF)