// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT const std = @import("std"); const log = std.log.scoped(.cpu); const addressing_modes = @import("cpu8/addressing_modes.zig"); const flags = @import("cpu8/flags.zig"); const memory = @import("memory8.zig"); const opcodes = @import("cpu8/opcodes.zig"); const program_counter = @import("cpu8/program_counter.zig"); const registers = @import("cpu8/registers.zig"); const stack = @import("cpu8/stack.zig"); const Processor = @import("root.zig").Processor; pub const Errors = error{ Break, IllegalOpcode, IllegalOperation, IllegalAddressingMode, IllegalValue, }; pub const Options = struct { processor: Processor = .@"6502", }; // pub const Location = union(enum) { // A: void, // X: void, // Y: void, // address: u16, // }; /// A 6502, parameterised over the clock it counts cycles against. Everything /// the processor owns hangs off the returned struct, and each part finds its /// way back to the whole through @fieldParentPtr, so the CPU can be built in /// place without any pointer wiring. /// A 6502 with nothing built around it: a clock that only counts, and a flat /// sixty-four kilobytes. This is what the tests and the SingleStepTests /// corpus run against, and naming it here keeps them from each having to /// spell out the same pair. pub const Bare = CPU(@import("clock.zig").FakeClock, memory.Flat(.{})); /// The same, made in CMOS. pub const BareCMOS = CMOS(@import("clock.zig").FakeClock, memory.Flat(.{})); /// The same again, as Ricoh made it for the NES. pub const BareNES = RP2A03(@import("clock.zig").FakeClock, memory.Flat(.{})); /// A 6502, parameterised over the clock it counts cycles against and the /// memory it sees. The memory is a function from the processor type to the /// model, rather than the model itself, because a model needs to name the /// processor it belongs to and the processor is not a type yet at that point. pub fn CPU(comptime Clock: type, comptime MemoryModel: fn (type) type) type { return Chip(.{ .processor = .@"6502" }, Clock, MemoryModel); } /// A 65C02: the same processor made in CMOS a decade later. /// /// It is not only the 6502 with more instructions. The encodings the NMOS part /// left undefined, which did things nobody designed and which programs came to /// rely on, are instructions here or else do nothing at all; decimal /// arithmetic sets the flags it should and takes a cycle longer for it; and /// the famous bug in an indirect jump across a page is gone, at the cost of a /// cycle. Where the two disagree, `processor` is what decides. pub fn CMOS(comptime Clock: type, comptime MemoryModel: fn (type) type) type { return Chip(.{ .processor = .@"65C02" }, Clock, MemoryModel); } /// The 6502 core inside Ricoh's RP2A03, the processor in a NES. /// /// It is the NMOS part, undocumented opcodes and indirect jump bug and all, /// with one thing taken away: the decimal correction is not on the die, so ADC /// and SBC add and subtract in binary whatever the D flag says. The flag is /// still a flag — SED sets it, PHP pushes it, PLP restores it — it simply does /// not reach the adder, and it costs no cycle either way. pub fn RP2A03(comptime Clock: type, comptime MemoryModel: fn (type) type) type { return Chip(.{ .processor = .RP2A03 }, Clock, MemoryModel); } /// A processor of the kind the options name. pub fn Chip( comptime options: Options, comptime Clock: type, comptime MemoryModel: fn (type) type, ) type { return struct { const Self = @This(); /// Which processor this is, which the instruction table and the /// instructions that differ between the two both consult. pub const processor = options.processor; /// An unsigned byte, unchanged. The counterpart to signed, so that /// tests can write either without caring. pub fn unsigned(value: u8) u8 { return value; } test "unsigned 1" { const result = unsigned(128); try std.testing.expectEqual(@as(u8, 128), result); } /// A signed byte as the processor stores it, in two's complement. pub fn signed(value: i8) u8 { return @bitCast(value); } test "signed 1" { const result = signed(-1); try std.testing.expectEqual(@as(u8, 255), result); } test "signed 2" { const result = signed(5); try std.testing.expectEqual(@as(u8, 5), result); } /// A number from 0 to 99 packed into two BCD nibbles, for setting up /// decimal mode tests. pub fn toDecimal(value: u8) !u8 { if (value < 0) return error.IllegalValue; if (value > 99) return error.IllegalValue; const tmp: packed struct(u8) { low: u4, high: u4, } = .{ .low = @intCast(value % 10), .high = @intCast(value / 10), }; const result: u8 = @bitCast(tmp); return result; } test "toDecimal 1" { try std.testing.expectError(error.IllegalValue, toDecimal(100)); } test "toDecimal 2" { const result = toDecimal(0); try std.testing.expectEqual(@as(u8, 0b00000000), result); } test "toDecimal 3" { const result = toDecimal(11); try std.testing.expectEqual(@as(u8, 0b00010001), result); } test "toDecimal 4" { const result = toDecimal(99); try std.testing.expectEqual(@as(u8, 0b10011001), result); } /// Two BCD nibbles unpacked back into a number. pub fn fromDecimal(value: u8) u8 { const tmp: packed struct(u8) { low: u4, high: u4, } = @bitCast(value); const result: u8 = @as(u8, @intCast(tmp.high)) * 10 + @as(u8, @intCast(tmp.low)); return result; } test "fromDecimal 1" { const result = fromDecimal(0x99); try std.testing.expectEqual(@as(u8, 99), result); } /// Where an instruction's operand is, which is the other half of what /// an opcode says. The processor has fifty-six instructions and two /// hundred and fifty-six encodings, and most of the difference is this: /// the same instruction with a different way of naming what it works /// on. /// /// Each one costs what it costs. A page has 256 bytes and the low half /// of an address is one, so an indexed address that carries out of its /// low byte takes a cycle to put the high half right, which is why /// several of these are a cycle longer some of the time and not /// others. `AddressingModes.decode` is where each is worked out, and /// it spends those cycles on the bus rather than counting them. pub const AddressingModes = enum { /// The whole address, in the two bytes after the opcode, low half /// first. Three bytes and no arithmetic: the slowest way to say /// where something is and the only one that can reach anywhere. Absolute, /// The same, plus X. A page crossing costs a cycle, and the read /// the chip takes at the address it built before fixing the high /// half is what that cycle is spent on. @"Absolute, X", /// And plus Y, which is otherwise the same. Between them these are /// how an array longer than a page is walked. @"Absolute, Y", /// No operand at all: the instruction is the whole of it. The /// accumulator forms of the shifts are here too, since what they /// work on is not addressed either. Implied, /// The operand is the byte after the opcode: not where the value /// is but the value itself. Immediate, /// The address of the address. Only the jump uses it, and on the /// NMOS part it carries the most famous bug of the family: a /// pointer ending in $ff takes its high byte from the start of the /// same page rather than the next one. Indirect, /// A pointer in the zero page, chosen by adding X to the byte /// after the opcode. The addition wraps inside the zero page, so a /// table of pointers there can be indexed but not overrun. @"(Indirect, X)", /// A pointer in the zero page, then Y added to what it points at. /// The other way round from the above, and the more useful of the /// two: the pointer says which array and Y says how far into it. @"(Indirect), Y", /// A distance rather than an address: one signed byte, counted /// from the instruction after this one, which is why a branch /// reaches 127 forward and 128 back and no further. Taking it /// costs a cycle, and landing in another page costs a second. Relative, /// The first 256 bytes of memory, in one byte. A byte saved on /// every instruction and a cycle with it, which is why a 6502 /// program keeps everything it can down there. @"Zero Page", /// The same, plus X, wrapping inside the page: $ff plus one is $00 /// and not $0100. @"Zero Page, X", /// And plus Y, which only the two instructions that load and store /// X can use, since the others would have nothing left to index /// with. @"Zero Page, Y", /// The CMOS part's own: a pointer in the zero page with no index /// at all, which the NMOS part could only manage by indexing with /// nought in a register and giving up the register to do it. @"(Indirect)", /// And an indexed indirect jump: X picks an entry from a table of /// addresses and the chip jumps through it, which is how a jump /// table is written on the CMOS part and what the NMOS part needed /// self-modifying code for. @"(Absolute, X)", /// The two below are not addressing modes so much as the shapes of /// the encodings the CMOS part does not decode. They do nothing, /// but they take the cycles and fetch the bytes they take, and /// what those are differs from encoding to encoding, so the table /// has to be able to say which. /// /// One byte, one cycle, nothing read. @"No Operand", /// Three bytes, three cycles: two operands fetched and never /// looked at. @"Two Operands", /// A byte in the zero page and a distance to branch, which is /// what the instructions Rockwell added take: three bytes, and /// neither half of it means anything without the other. @"Zero Page, Relative", }; /// Where the processor looks for the address to carry on from when /// something interrupts the ordinary run of instructions. Three /// separate vectors, and using the wrong one lands in the wrong /// handler rather than failing in any visible way. pub const vector = struct { /// Non-maskable interrupt. pub const nmi: u16 = 0xfffa; /// Reset. pub const reset: u16 = 0xfffc; /// Interrupt request, and BRK. pub const irq: u16 = 0xfffe; }; pub const Opcodes = opcodes.Opcodes(Self); pub const Memory = MemoryModel(Self); /// The interrupt request line. Level triggered: it stays asserted /// until whatever pulled it lets go, so a device that is still asking /// will be answered again as soon as the handler enables interrupts. irq: bool = false, /// Whether the processor has been told to wait, which only Western /// Design's part can be. It stops fetching and lets the clock run until /// something pulls an interrupt line, and what happens then depends on /// whether interrupts are enabled: either the handler, or simply the next /// instruction. waiting: bool = false, /// And whether it has been stopped, which nothing but a reset undoes. stopped: bool = false, /// The non-maskable interrupt line. Edge triggered: answering it is /// what clears it, and the interrupt disable flag does not apply. nmi: bool = false, clock: Clock, flags: flags.Flags(Self), registers: registers.Registers(Self), program_counter: program_counter.ProgramCounter(Self), addressing_modes: addressing_modes.AddressingModes(Self), stack: stack.Stack(Self), memory: Memory, /// Brings up every part of the processor in place. Does not fetch the /// reset vector; call reset for that. pub fn init(self: *Self, memory_size: ?usize, clock_speed: ?u128) !void { // The processor is built from undefined, so field defaults do not // apply and the lines have to be let go of explicitly. self.irq = false; self.nmi = false; // A CPU is built from undefined, so the WAI and STP states have to // be let go of here too, the same as the interrupt lines: a caller // that runs an instruction after only init(), as the corpus runner // does, would otherwise start on whatever the stack held, and a // stray "stopped" makes every instruction a one-cycle no-op. self.stopped = false; self.waiting = false; self.clock.init(clock_speed); self.addressing_modes.init(); self.memory.init(memory_size); self.program_counter.init(); self.registers.init(); self.stack.init(); self.flags.init(); } /// Nothing to release. Present so callers can defer it and stay correct /// if that changes. pub fn deinit(self: *Self) void { _ = self; } /// Does what the reset line does: reloads the program counter from the /// vector and clears the registers, flags and stack pointer. pub fn reset(self: *Self) void { // The reset line reaches the whole machine, not only the // processor: the switches that decide where memory comes from go // back to where they start, and the cards clear their latches, // which is what stops a drive that was left turning. // // First, and not last. Whether $fffc is ROM or the language card // is one of the things the line decides, so the switches have to // be back where they start before the vector is read through them. self.memory.reset(); // A processor that was told to stop starts again here, which is // the only thing that undoes it. self.stopped = false; self.waiting = false; self.program_counter.reset(); self.registers.reset(); self.flags.reset(); self.stack.reset(); } /// Fetches one opcode and runs it, spending its cycles on the clock as /// it goes. /// /// Break and Jam are not failures but the two ways an instruction can /// end without the processor going on to the next one. IllegalOpcode /// cannot currently happen, since all 256 opcodes decode. /// Answers an interrupt: two discarded reads while the processor /// works out what it is doing, the return address and the flags onto /// the stack, interrupts disabled, and off through the vector. Seven /// cycles, the same as the BRK it is closely related to. fn serviceInterrupt(self: *Self, comptime line: enum { irq, nmi }) void { // The sequence begins like any instruction, with SYNC up and the // next opcode fetched and thrown away, so anything watching the // line for an instruction boundary sees one here too. if (comptime @hasDecl(Memory, "sync")) self.memory.sync(); self.program_counter.phantomRead(); self.program_counter.phantomRead(); self.stack.push(u16, self.program_counter.value); self.stack.push(u8, self.flags.saveInterrupt()); self.flags.set(.I); // The NMOS part left the decimal flag alone, so a handler that // wanted to add had to clear it itself and put it back, and one // that forgot did its arithmetic in the wrong base. The CMOS part // clears it on the way in. if (comptime processor.cmos()) self.flags.clear(.D); self.program_counter.jump(self.memory.read(u16, switch (line) { .irq => vector.irq, .nmi => vector.nmi, })); } /// Runs one instruction, or answers an interrupt if one is waiting. /// /// A processor looks at its interrupt lines between instructions, not /// during one, so this is the only place they are considered. An NMI /// is answered whatever the interrupt disable flag says, which is what /// makes it non-maskable, and answering it is what clears it. pub fn executeInstruction(self: *Self) error{ IllegalOpcode, Break, Jam }!void { // A stopped processor does nothing at all until it is reset: the // clock still runs, since a machine around it still has a clock, // but nothing is fetched. if (self.stopped) { self.clock.sleep(1); return; } // A waiting one is the same until something interrupts it. If // interrupts are enabled it goes to the handler below; if they are // not it simply carries on, which is the useful half of this // instruction. if (self.waiting) { if (!self.irq and !self.nmi) { self.clock.sleep(1); return; } self.waiting = false; } if (self.nmi) { self.nmi = false; self.serviceInterrupt(.nmi); return; } if (self.irq and self.flags.isClear(.I)) { self.serviceInterrupt(.irq); return; } return self.executeInstructionUncond(); } fn executeInstructionUncond(self: *Self) error{ IllegalOpcode, Break, Jam }!void { // The SYNC line: high for the cycle an opcode is fetched in, and // the one thing on the bus that tells an instruction's start from // the rest of it. An Apple III's memory logic watches it, so a // memory model that declares `sync` is told before every opcode // fetch; the Apple IIs have no use for it and declare nothing. if (comptime @hasDecl(Memory, "sync")) self.memory.sync(); const opcode = self.program_counter.read(u8); const data = Opcodes.get(opcode) orelse return error.IllegalOpcode; try data.func(self); } }; } test "cpu" { var cpu: Bare = undefined; std.mem.doNotOptimizeAway(try cpu.init(null, null)); defer cpu.deinit(); std.testing.refAllDecls(@This()); } test "an interrupt is answered between instructions" { var cpu: Bare = undefined; try cpu.init(null, null); defer cpu.deinit(); try cpu.memory.loadProgram(0x0200, &[_]u8{ 0xea, 0xea }); try cpu.memory.loadProgram(0xfffe, &[_]u8{ 0x00, 0x30 }); // IRQ vector cpu.program_counter.value = 0x0200; cpu.flags.clear(.I); // Nothing is asking, so the instruction runs. try cpu.executeInstruction(); try std.testing.expectEqual(@as(u16, 0x0201), cpu.program_counter.value); // Now something is, and the next step answers it instead. cpu.irq = true; const before = cpu.clock.cycles; try cpu.executeInstruction(); try std.testing.expectEqual(@as(u16, 0x3000), cpu.program_counter.value); try std.testing.expectEqual(before + 7, cpu.clock.cycles); try std.testing.expect(cpu.flags.isSet(.I)); // The return address is the instruction that did not run, and the pushed // flags have the break bit clear so a handler can tell this from a BRK. const pushed = cpu.memory.peek(0x01fd); try std.testing.expectEqual(@as(u8, 0), pushed & 0x10); try std.testing.expectEqual(@as(u8, 0x01), cpu.memory.peek(0x01fe)); try std.testing.expectEqual(@as(u8, 0x02), cpu.memory.peek(0x01ff)); } test "the interrupt disable flag masks IRQ but not NMI" { var cpu: Bare = undefined; try cpu.init(null, null); defer cpu.deinit(); try cpu.memory.loadProgram(0x0200, &[_]u8{ 0xea, 0xea, 0xea }); try cpu.memory.loadProgram(0xfffa, &[_]u8{ 0x00, 0x40 }); // NMI vector try cpu.memory.loadProgram(0xfffe, &[_]u8{ 0x00, 0x30 }); // IRQ vector cpu.program_counter.value = 0x0200; cpu.flags.set(.I); // Masked, so the instruction runs and the request is still waiting. cpu.irq = true; try cpu.executeInstruction(); try std.testing.expectEqual(@as(u16, 0x0201), cpu.program_counter.value); try std.testing.expect(cpu.irq); // An NMI is not masked by it. cpu.nmi = true; try cpu.executeInstruction(); try std.testing.expectEqual(@as(u16, 0x4000), cpu.program_counter.value); // Answering an NMI clears it; the IRQ line is still held. try std.testing.expect(!cpu.nmi); try std.testing.expect(cpu.irq); } test "an IRQ is answered again while the line is held" { var cpu: Bare = undefined; try cpu.init(null, null); defer cpu.deinit(); try cpu.memory.loadProgram(0xfffe, &[_]u8{ 0x00, 0x30 }); cpu.program_counter.value = 0x0200; cpu.flags.clear(.I); cpu.irq = true; try cpu.executeInstruction(); try std.testing.expectEqual(@as(u16, 0x3000), cpu.program_counter.value); // The handler enabling interrupts with the device still asking gets // interrupted again, which is what level triggered means. cpu.flags.clear(.I); try cpu.executeInstruction(); try std.testing.expectEqual(@as(u16, 0x3000), cpu.program_counter.value); } test "the processor can be told to wait, and what wakes it" { // Neither this nor stopping can be checked against the corpus: an // instruction that waits cannot be recorded a case at a time, and the // files for both are empty there. So they are checked here instead. var cpu: Chip(.{ .processor = .W65C02 }, @import("clock.zig").FakeClock, memory.Flat(.{})) = undefined; try cpu.init(null, null); defer cpu.deinit(); try cpu.memory.loadProgram(0x0200, &[_]u8{ 0xcb, 0xa9, 0x42 }); // WAI : LDA #$42 try cpu.memory.loadProgram(0xfffe, &[_]u8{ 0x00, 0x03 }); // the IRQ vector cpu.program_counter.value = 0x0200; cpu.flags.set(.I); // interrupts off, so it carries on rather than jumping try cpu.executeInstruction(); try std.testing.expect(cpu.waiting); // Waiting costs cycles and nothing else: the counter does not move. const before = cpu.clock.cycles; for (0..100) |_| try cpu.executeInstruction(); try std.testing.expect(cpu.clock.cycles > before); try std.testing.expectEqual(@as(u16, 0x0201), cpu.program_counter.value); try std.testing.expect(cpu.waiting); // Something asks for attention. Interrupts are off, so what happens is // the instruction after the wait rather than the handler. cpu.irq = true; try cpu.executeInstruction(); try std.testing.expect(!cpu.waiting); try std.testing.expectEqual(@as(u8, 0x42), cpu.registers.get(.A)); // And with interrupts on it goes to the handler instead. var handled: Chip(.{ .processor = .W65C02 }, @import("clock.zig").FakeClock, memory.Flat(.{})) = undefined; try handled.init(null, null); defer handled.deinit(); try handled.memory.loadProgram(0x0200, &[_]u8{0xcb}); try handled.memory.loadProgram(0xfffe, &[_]u8{ 0x00, 0x03 }); handled.program_counter.value = 0x0200; handled.flags.clear(.I); try handled.executeInstruction(); handled.irq = true; try handled.executeInstruction(); try std.testing.expectEqual(@as(u16, 0x0300), handled.program_counter.value); } test "the processor can be stopped, and only reset starts it again" { var cpu: Chip(.{ .processor = .W65C02 }, @import("clock.zig").FakeClock, memory.Flat(.{})) = undefined; try cpu.init(null, null); defer cpu.deinit(); try cpu.memory.loadProgram(0x0200, &[_]u8{ 0xdb, 0xa9, 0x42 }); // STP : LDA #$42 try cpu.memory.loadProgram(0xfffc, &[_]u8{ 0x00, 0x04 }); // the reset vector cpu.program_counter.value = 0x0200; try cpu.executeInstruction(); try std.testing.expect(cpu.stopped); // Nothing wakes it: not an interrupt, not anything. cpu.irq = true; cpu.nmi = true; cpu.flags.clear(.I); for (0..100) |_| try cpu.executeInstruction(); try std.testing.expect(cpu.stopped); try std.testing.expectEqual(@as(u8, 0x00), cpu.registers.get(.A)); try std.testing.expectEqual(@as(u16, 0x0201), cpu.program_counter.value); cpu.reset(); try std.testing.expect(!cpu.stopped); try std.testing.expectEqual(@as(u16, 0x0400), cpu.program_counter.value); } test "the bit instructions are only on the parts that have them" { // The plain CMOS part does nothing at these encodings, and Rockwell's and // Western Design's move a bit of a byte in the zero page. inline for (.{ .@"65C02", .R65C02, .W65C02 }) |which| { var cpu: Chip(.{ .processor = which }, @import("clock.zig").FakeClock, memory.Flat(.{})) = undefined; try cpu.init(null, null); defer cpu.deinit(); // SMB3 $10, then RMB1 $10. try cpu.memory.loadProgram(0x0200, &[_]u8{ 0xb7, 0x10, 0x17, 0x10 }); try cpu.memory.loadProgram(0x0010, &[_]u8{0b0000_0010}); cpu.program_counter.value = 0x0200; try cpu.executeInstruction(); try cpu.executeInstruction(); const expected: u8 = switch (which) { .@"65C02" => 0b0000_0010, // nothing happened at all else => 0b0000_1000, // bit three set, bit one cleared }; try std.testing.expectEqual(expected, cpu.memory.peek(0x0010)); } } test "the NES part keeps the decimal flag and ignores it" { // SED, then CLC, then ADC #$01 onto $19. The flag is set the whole way // through, so the NMOS part adds in decimal and reaches $20 while Ricoh's // adds in binary and reaches $1a. inline for (.{ .@"6502", .RP2A03 }) |which| { var cpu: Chip(.{ .processor = which }, @import("clock.zig").FakeClock, memory.Flat(.{})) = undefined; try cpu.init(null, null); defer cpu.deinit(); try cpu.memory.loadProgram(0x0200, &[_]u8{ 0xf8, 0x18, 0xa9, 0x19, 0x69, 0x01 }); cpu.program_counter.value = 0x0200; for (0..3) |_| try cpu.executeInstruction(); const before = cpu.clock.read(); try cpu.executeInstruction(); const adc_cycles = cpu.clock.read() - before; switch (which) { .@"6502" => { try std.testing.expectEqual(@as(u8, 0x20), cpu.registers.get(.A)); try std.testing.expectEqual(@as(u64, 2), adc_cycles); }, else => { try std.testing.expectEqual(@as(u8, 0x1a), cpu.registers.get(.A)); // Not the CMOS part, so the correction it does not do costs it // nothing: the same two cycles either way. try std.testing.expectEqual(@as(u64, 2), adc_cycles); }, } // The flag itself is untouched by any of this. SED set it, nothing // cleared it, and it reads back set on both parts. try std.testing.expect(cpu.flags.isSet(.D)); } } test "a reset disables interrupts, so a card still asking is not answered at once" { // Reset is one of the hardware interrupts — the W65C816S datasheet lists // RESETB at $00fffc,d beside IRQB and NMIB — and "when an interrupt is // executed, D=0 and I=1 in Status Register P" (Western Design Center, // 2018, p. 30). // // It matters because reset does not reach into a card and take back what // it was asking for. A Mockingboard with a timer running holds the line // down across the reset, and if the flag came back clear the first // instruction the reset vector points at would be interrupted before it // finished. var cpu: Chip(.{ .processor = .@"6502" }, @import("clock.zig").FakeClock, memory.Flat(.{})) = undefined; try cpu.init(null, null); try cpu.memory.loadProgram(0xfffc, &[_]u8{ 0x00, 0x20 }); try cpu.memory.loadProgram(0x2000, &[_]u8{ 0xea, 0xea }); cpu.irq = true; cpu.reset(); try std.testing.expect(cpu.flags.isSet(.I)); try std.testing.expectEqual(@as(u16, 0x2000), cpu.program_counter.value); // And the first instruction is the one the vector pointed at, not a // handler. _ = cpu.executeInstruction() catch {}; try std.testing.expectEqual(@as(u16, 0x2001), cpu.program_counter.value); // The line is still being pulled, so clearing the flag answers it. cpu.flags.clear(.I); _ = cpu.executeInstruction() catch {}; try std.testing.expect(cpu.program_counter.value != 0x2002); }