// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! The SingleStepTests 65816 corpus, run against the 16-bit core. //! //! Its own runner rather than the 8-bit one made generic, which is the same //! bargain the cores themselves strike. Almost everything about a case is a //! different shape here: the registers are sixteen bits and there are three //! more of them, the emulation line is part of the state, an address is //! twenty-four bits, a cycle carries eight signal lines instead of a //! direction, and each opcode has two files rather than one because every //! encoding is recorded twice — ten thousand cases in native mode and ten //! thousand emulating. //! //! Five million cases in all, against two and a half million for the 65x02 //! sets, and checked the same three ways: the architectural state, the number //! of cycles, and every access on the bus. The bus check is sharper here than //! it was, because the recordings say more per cycle. A cycle in which the //! processor transferred nothing is written with a null value, and an emulator //! that logged it as a read of some byte would be caught even though no //! register would ever show it. //! //! The instruction table is finished — all 256 encodings pass — and this //! runner still counts an unimplemented opcode apart from an implemented and //! wrong one, so that if one were ever taken back out the number worth looking //! at would not be buried in the number still to do. Today that count is zero. const std = @import("std"); const builtin = @import("builtin"); const options = @import("options"); const zig65 = @import("zig65"); const RAM = @import("single_step_tests/RAM24.zig"); const Cycle = @import("single_step_tests/Cycle65816.zig"); /// Everything the recordings say about the processor at a moment. Three /// registers the 6502 never had — the two bank registers and the direct page — /// and the emulation line, which is not a bit of the status register but is /// every bit as much part of the state. const State = struct { pc: u16, s: u16, p: u8, a: u16, x: u16, y: u16, dbr: u8, d: u16, pbr: u8, e: u1, ram: []RAM, }; const Test = struct { name: []const u8, initial: State, final: State, cycles: []Cycle, }; const usage = \\usage: single_step_tests_65816 DIRECTORY \\ \\Runs every opcode against the SingleStepTests 65816 corpus in DIRECTORY, \\which is the directory holding 00.e.json and 00.n.json through ff.e.json \\and ff.n.json. In the 65816 repository that is v1. `zig build run \\-Dprocessor=65C816` passes the path of the fetched copy; give one here to \\run against a checkout instead. \\ ; /// Every file in the corpus holds this many cases, and there are two files per /// opcode. Worth knowing before one has been read: it means an opcode can be /// counted as skipped without parsing it to find out how many were in it. const cases_per_file = 10_000; const files_per_opcode = 2; var debug_allocator: std.heap.DebugAllocator(.{}) = .init; /// Flat memory is the only model this corpus can run against: it uses the /// whole sixteen megabytes as ordinary memory. The bus log is on, since /// checking the trace against the hardware's is the point. const CPU = zig65.cpu16.Chip( .{ .dispatch = switch (options.dispatch) { .branch => .branch, .tables => .tables, } }, zig65.clock.FakeClock, zig65.memory16.Flat(.{ .bus_log = true }), ); /// What running one opcode's twenty thousand cases came to. const Outcome = struct { total: usize = 0, succeeded: usize = 0, failed: usize = 0, /// Cases for an opcode that has no implementation yet. Kept apart from /// failures on purpose: an instruction that has not been written is not an /// instruction that is wrong, and burying the second count inside the /// first would make the number that matters unreadable until the table is /// finished. unimplemented: usize = 0, skipped: usize = 0, /// How many of the cases were recorded in native mode, which is the half /// the 8-bit core could never have run at all. native: usize = 0, cycle_mismatches: usize = 0, cycle_example: [2]u64 = .{ 0, 0 }, bus_mismatches: usize = 0, bus_report: ?[]u8 = null, report: ?[]u8 = null, fatal: ?[]const u8 = null, fn deinit(self: *Outcome, gpa: std.mem.Allocator) void { if (self.report) |r| gpa.free(r); if (self.bus_report) |r| gpa.free(r); } }; /// Runs both files for one opcode. /// /// The CPU is built once and reused across every case, because its memory is /// sixteen megabytes: allocating that twenty thousand times over would cost /// more than the whole of the rest of the work. What makes reuse safe is that /// a case only ever touches the addresses it names and the ones the /// instruction reaches, and both are known afterwards, so putting those back /// to zero puts the whole machine back. fn runOpcode( io: std.Io, gpa: std.mem.Allocator, data_directory: []const u8, opcode: u8, node: std.Progress.Node, ) Outcome { var outcome: Outcome = .{}; var arena_state: std.heap.ArenaAllocator = .init(gpa); defer arena_state.deinit(); const alloc = arena_state.allocator(); const data = CPU.Opcodes.describe(opcode) orelse { outcome.total = cases_per_file * files_per_opcode; outcome.unimplemented = outcome.total; return outcome; }; var cpu: CPU = undefined; cpu.init(gpa, null) catch return oom(&outcome); defer cpu.deinit(); // The two halves of the recording: emulation mode and native mode. for ([_][]const u8{ "e", "n" }) |mode| { const filename = std.fmt.allocPrint(alloc, "{x:0>2}.{s}.json", .{ opcode, mode }) catch return oom(&outcome); const pathname = std.Io.Dir.path.join(alloc, &.{ data_directory, filename }) catch return oom(&outcome); const test_data = std.Io.Dir.cwd().readFileAlloc(io, pathname, alloc, .unlimited) catch { outcome.fatal = "cannot read the corpus file"; return outcome; }; if (test_data.len == 0) continue; const parsed = std.json.parseFromSlice([]Test, alloc, test_data, .{}) catch { outcome.fatal = "cannot parse the corpus file"; return outcome; }; defer parsed.deinit(); outcome.total += parsed.value.len; for (parsed.value) |case| { defer node.completeOne(); runCase(gpa, &cpu, data, case, opcode, &outcome); if (outcome.fatal != null) return outcome; } } return outcome; } fn oom(outcome: *Outcome) Outcome { outcome.fatal = "out of memory"; return outcome.*; } /// Whether this is one of the two block moves, which the corpus records /// differently from everything else. /// /// A block move backs the program counter over its own three bytes when there /// is more to move, so it is not one instruction but the same instruction /// executed again and again — a move of a whole bank is sixty-five thousand /// executions. The recordings cannot hold that, so they run the machine for a /// hundred cycles, or until the move finishes, whichever comes first. A case /// that finishes ends on an instruction boundary and needs no allowance; one /// that does not stops two cycles into the next fetch, with the counter two /// bytes on and nothing else changed. fn blockMove(opcode: u8) bool { return opcode == 0x44 or opcode == 0x54; } /// Puts every address a case touched back to zero, so the next one starts from /// the same empty machine. Cheap because a case names a handful of addresses /// and an instruction reaches a handful more, and all of them are written down. fn scrub(cpu: *CPU, case: Test) void { for (case.initial.ram) |ram| cpu.memory.poke(ram.address, 0); for (case.final.ram) |ram| cpu.memory.poke(ram.address, 0); for (cpu.memory.bus.entries[0..cpu.memory.bus.len]) |access| cpu.memory.poke(access.address, 0); } /// Runs one case and folds what happened into the outcome. fn runCase( gpa: std.mem.Allocator, cpu: *CPU, data: *const CPU.Opcodes.Data, case: Test, opcode: u8, outcome: *Outcome, ) void { var failed: bool = false; cpu.clock.reset(); cpu.memory.bus.clear(); // The processor is reused across the twenty thousand cases of an opcode, // because its memory is sixteen megabytes and allocating that per case // would cost more than the work. Everything a case can leave behind has to // be put back, and the lines are the easy ones to forget: WAI and STP set // a flag that outlives the instruction, and one case leaving the processor // waiting made every case after it in the file fail at the first cycle. cpu.waiting = false; cpu.stopped = false; cpu.irq = false; cpu.nmi = false; cpu.locked = false; // The emulation line first: it decides what the width flags and the stack // pointer are allowed to be, so setting it after them would undo them. cpu.flags.setEmulation(case.initial.e == 1); cpu.flags.load(case.initial.p); cpu.program_counter.jump(case.initial.pc); cpu.registers.program_bank = case.initial.pbr; cpu.registers.data_bank = case.initial.dbr; cpu.registers.direct = case.initial.d; cpu.registers.set(.A, case.initial.a); cpu.registers.set(.X, case.initial.x); cpu.registers.set(.Y, case.initial.y); cpu.stack.set(case.initial.s); if (case.initial.e == 0) outcome.native += 1; for (case.initial.ram) |ram| cpu.memory.poke(ram.address, ram.value); defer scrub(cpu, case); if (blockMove(opcode)) { // Keep going while the move has more to do and another whole // execution fits inside what was recorded. while (true) { cpu.executeInstruction() catch { outcome.fatal = "an instruction returned an unexpected error"; return; }; if (cpu.registers.get(.A) == 0xffff) break; if (cpu.clock.cycles + 7 > case.cycles.len) break; } } else { cpu.executeInstruction() catch |err| switch (err) { error.Break => {}, error.Jam => {}, else => { outcome.fatal = "an instruction returned an unexpected error"; return; }, }; } // How much of the recording is the fetch it was cut off in the middle of. // Only a block move can be cut off; for everything else a difference here // is a wrong cycle count and must be reported as one rather than excused. const truncated: usize = if (blockMove(opcode) and cpu.clock.cycles < case.cycles.len) case.cycles.len - cpu.clock.cycles else 0; // Each of those cycles read an instruction byte, so the counter is that // many bytes further on than where we stopped. const expected_pc = case.final.pc -% @as(u16, @intCast(truncated)); if (expected_pc != cpu.program_counter.value) failed = true; if (case.final.s != cpu.stack.get()) failed = true; if (case.final.a != cpu.registers.get(.A)) failed = true; if (case.final.x != cpu.registers.get(.X)) failed = true; if (case.final.y != cpu.registers.get(.Y)) failed = true; if (case.final.pbr != cpu.registers.program_bank) failed = true; if (case.final.dbr != cpu.registers.data_bank) failed = true; if (case.final.d != cpu.registers.direct) failed = true; if ((case.final.e == 1) != cpu.flags.emulation) failed = true; if (!cpu.flags.compare(case.final.p)) failed = true; for (case.final.ram) |ram| { if (cpu.memory.peek(ram.address) != ram.value) failed = true; } // Every access the instruction made, in order, and every line the // processor drove while it made it. bus: for (case.cycles[0 .. case.cycles.len - truncated], 0..) |want, j| { const got: ?CPU.Memory.Access = if (j < cpu.memory.bus.len) cpu.memory.bus.entries[j] else null; if (got) |access| { const signals = access.signals(); // A cycle that transferred nothing has no value to compare, and // one in which the processor had let go of the bus has no address // either. const same_value = if (want.value) |v| access.value == v else true; const same_address = if (want.address) |a| access.address == a else true; if (same_address and same_value and std.mem.eql(u8, &signals, &wantSignals(want))) continue; } if (outcome.bus_report == null) describe: { var buffer: std.Io.Writer.Allocating = .init(gpa); const out = &buffer.writer; out.print(" 0x{x:0>2} {s} cycle {d}: want ", .{ opcode, data.mnemonic, j, }) catch break :describe; if (want.address) |a| out.print("${x:0>6} ", .{a}) catch break :describe else out.print("$------ ", .{}) catch break :describe; if (want.value) |v| out.print("={x:0>2} ", .{v}) catch break :describe else out.print("=-- ", .{}) catch break :describe; out.print("{s}, ", .{wantSignals(want)}) catch break :describe; if (got) |access| out.print("got ${x:0>6} ={x:0>2} {s}\n", .{ access.address, access.value, access.signals(), }) catch break :describe else out.print("got no access\n", .{}) catch break :describe; outcome.bus_report = buffer.toOwnedSlice() catch break :describe; } outcome.bus_mismatches += 1; break :bus; } if (cpu.clock.cycles != case.cycles.len - truncated) { if (outcome.cycle_mismatches == 0) outcome.cycle_example = .{ case.cycles.len - truncated, cpu.clock.cycles }; outcome.cycle_mismatches += 1; } if (failed) { outcome.failed += 1; if (outcome.report != null) return; var buffer: std.Io.Writer.Allocating = .init(gpa); writeReport(&buffer.writer, data, case, cpu) catch {}; outcome.report = buffer.toOwnedSlice() catch null; return; } outcome.succeeded += 1; } /// The eight signal characters a recorded cycle amounts to, so that what was /// wanted and what happened can be compared and printed the same way. fn wantSignals(want: Cycle) [8]u8 { // No address at all means the processor was not driving the bus, and then // it is not driving the read line either. if (want.address == null) return .{ '-', '-', '-', '-', '-', '-', '-', '-' }; return .{ if (want.vda) 'd' else '-', if (want.vpa) 'p' else '-', if (want.vpb) 'v' else '-', if (want.direction == .read) 'r' else 'w', if (want.e) 'e' else '-', if (want.m) 'm' else '-', if (want.x) 'x' else '-', if (want.mlb) 'l' else '-', }; } /// Describes a failing case at length: what was wanted, what happened, and the /// memory either side of it. fn writeReport( stderr: *std.Io.Writer, data: *const CPU.Opcodes.Data, case: Test, cpu: *CPU, ) !void { try stderr.print("════════════ {s} {s} ════════════\n", .{ data.mnemonic, case.name }); if (case.final.pc != cpu.program_counter.value) try stderr.print("program counter: FAIL (0x{x:0>4} != 0x{x:0>4})\n", .{ cpu.program_counter.value, case.final.pc }); if (case.final.s != cpu.stack.get()) try stderr.print("stack pointer: FAIL (0x{x:0>4} != 0x{x:0>4})\n", .{ cpu.stack.get(), case.final.s }); if (case.final.a != cpu.registers.get(.A)) try stderr.print("register A: FAIL (0x{x:0>4} != 0x{x:0>4})\n", .{ cpu.registers.get(.A), case.final.a }); if (case.final.x != cpu.registers.get(.X)) try stderr.print("register X: FAIL (0x{x:0>4} != 0x{x:0>4})\n", .{ cpu.registers.get(.X), case.final.x }); if (case.final.y != cpu.registers.get(.Y)) try stderr.print("register Y: FAIL (0x{x:0>4} != 0x{x:0>4})\n", .{ cpu.registers.get(.Y), case.final.y }); if (case.final.d != cpu.registers.direct) try stderr.print("direct page: FAIL (0x{x:0>4} != 0x{x:0>4})\n", .{ cpu.registers.direct, case.final.d }); if (case.final.dbr != cpu.registers.data_bank) try stderr.print("data bank: FAIL (0x{x:0>2} != 0x{x:0>2})\n", .{ cpu.registers.data_bank, case.final.dbr }); if (case.final.pbr != cpu.registers.program_bank) try stderr.print("program bank: FAIL (0x{x:0>2} != 0x{x:0>2})\n", .{ cpu.registers.program_bank, case.final.pbr }); if ((case.final.e == 1) != cpu.flags.emulation) try stderr.print("emulation: FAIL ({} != {})\n", .{ cpu.flags.emulation, case.final.e == 1 }); if (!cpu.flags.compare(case.final.p)) { try stderr.writeAll("flags: FAIL ("); try cpu.flags.format(stderr, cpu.flags.dump()); try stderr.writeAll(" != "); try cpu.flags.format(stderr, case.final.p); try stderr.writeAll(")\n"); } for (case.final.ram) |ram| { if (cpu.memory.peek(ram.address) != ram.value) try stderr.print("memory 0x{x:0>6}: FAIL (0x{x:0>2} != 0x{x:0>2})\n", .{ ram.address, cpu.memory.peek(ram.address), ram.value, }); } try stderr.print("\n Initial Final Actual\n", .{}); try stderr.print("PC: {x:0>2}:{x:0>4} PC: {x:0>2}:{x:0>4} PC: {x:0>2}:{x:0>4}\n", .{ case.initial.pbr, case.initial.pc, case.final.pbr, case.final.pc, cpu.registers.program_bank, cpu.program_counter.value, }); try stderr.print(" S: ${x:0>4} S: ${x:0>4} S: ${x:0>4}\n", .{ case.initial.s, case.final.s, cpu.stack.get() }); try stderr.print(" A: ${x:0>4} A: ${x:0>4} A: ${x:0>4}\n", .{ case.initial.a, case.final.a, cpu.registers.get(.A) }); try stderr.print(" X: ${x:0>4} X: ${x:0>4} X: ${x:0>4}\n", .{ case.initial.x, case.final.x, cpu.registers.get(.X) }); try stderr.print(" Y: ${x:0>4} Y: ${x:0>4} Y: ${x:0>4}\n", .{ case.initial.y, case.final.y, cpu.registers.get(.Y) }); try stderr.print(" D: ${x:0>4} D: ${x:0>4} D: ${x:0>4}\n", .{ case.initial.d, case.final.d, cpu.registers.direct }); try stderr.print("DB: ${x:0>2} DB: ${x:0>2} DB: ${x:0>2}\n", .{ case.initial.dbr, case.final.dbr, cpu.registers.data_bank }); try stderr.print(" E: {d} E: {d} E: {d}\n", .{ case.initial.e, case.final.e, @intFromBool(cpu.flags.emulation) }); try stderr.writeAll(" P: "); try cpu.flags.format(stderr, case.initial.p); try stderr.writeAll(" P: "); try cpu.flags.format(stderr, case.final.p); try stderr.writeAll(" P: "); try cpu.flags.format(stderr, cpu.flags.dump()); try stderr.writeAll("\n\n"); } pub fn main(init: std.process.Init) !void { const io = init.io; var args: std.process.Args.Iterator = .init(init.minimal.args); _ = args.skip(); const data_directory = args.next() orelse { std.debug.print("single_step_tests_65816: no test data directory given\n\n{s}", .{usage}); std.process.exit(2); }; if (args.next()) |extra| { std.debug.print("single_step_tests_65816: unexpected argument '{s}'\n\n{s}", .{ extra, usage }); std.process.exit(2); } const gpa, const is_debug = allocator: { break :allocator switch (builtin.mode) { .Debug, .ReleaseSafe => .{ debug_allocator.allocator(), true }, .ReleaseFast, .ReleaseSmall => .{ std.heap.smp_allocator, false }, }; }; defer if (is_debug) { _ = debug_allocator.deinit(); }; const root = std.Progress.start(io, .{ .root_name = "Testing 65816", .estimated_total_items = 256, }); defer root.end(); var wanted: [256]bool = @splat(true); var outcomes: [256]Outcome = @splat(.{}); for (0..256) |i| { const opcode: u8 = @intCast(i); if (options.ssf) |ssfs| { var buf: [2]u8 = undefined; const name = try std.fmt.bufPrint(&buf, "{x:0>2}", .{opcode}); wanted[i] = false; for (ssfs) |ssf| { if (std.mem.eql(u8, name, ssf)) wanted[i] = true; } } if (!wanted[i]) outcomes[i] = .{ .total = cases_per_file * files_per_opcode, .skipped = cases_per_file * files_per_opcode, }; } // Fewer at once than the 8-bit runner uses: each worker holds sixteen // megabytes of memory as well as its parsed files. const at_once = 8; var next_opcode: usize = 0; while (next_opcode < 256) { var futures: [at_once]std.Io.Future(Outcome) = undefined; var started: [at_once]u8 = undefined; var count: usize = 0; while (count < at_once and next_opcode < 256) : (next_opcode += 1) { if (!wanted[next_opcode]) continue; const opcode: u8 = @intCast(next_opcode); const mnemonic = if (CPU.Opcodes.describe(opcode)) |d| d.mnemonic else "---"; var name_buf: [32]u8 = undefined; const name = try std.fmt.bufPrint(&name_buf, "Opcode 0x{x:0>2} {s}", .{ opcode, mnemonic }); const node = root.start(name, cases_per_file * files_per_opcode); started[count] = opcode; futures[count] = io.async(runOpcode, .{ io, gpa, data_directory, opcode, node }); count += 1; } for (futures[0..count], started[0..count]) |*future, opcode| { outcomes[opcode] = future.await(io); } } var total_cases: usize = 0; var failed_cases: usize = 0; var skipped_cases: usize = 0; var successful_cases: usize = 0; var unimplemented_cases: usize = 0; var native_cases: usize = 0; var cycle_mismatches: usize = 0; var bus_mismatches: usize = 0; for (&outcomes, 0..) |*outcome, i| { defer outcome.deinit(gpa); if (outcome.fatal) |why| { std.debug.print("single_step_tests_65816: opcode 0x{x:0>2}: {s}\n", .{ i, why }); std.process.exit(1); } total_cases += outcome.total; failed_cases += outcome.failed; skipped_cases += outcome.skipped; successful_cases += outcome.succeeded; unimplemented_cases += outcome.unimplemented; native_cases += outcome.native; cycle_mismatches += outcome.cycle_mismatches; bus_mismatches += outcome.bus_mismatches; if (outcome.report) |report| std.debug.print("{s}", .{report}); if (outcome.bus_report) |report| std.debug.print("{s}", .{report}); } const implemented = CPU.Opcodes.implemented(); std.debug.print( "\n{d} tests: {d} succeeded, {d} failed, {d} skipped, {d} not implemented\n", .{ total_cases, successful_cases, failed_cases, skipped_cases, unimplemented_cases }, ); std.debug.print( "instructions: {d} of 256 encodings implemented, {d} cases run, {d} of them native\n", .{ implemented, successful_cases + failed_cases, native_cases }, ); if (bus_mismatches == 0) { std.debug.print("bus traces: every cycle matches\n", .{}); } else { var opcodes: usize = 0; for (&outcomes) |outcome| { if (outcome.bus_mismatches != 0) opcodes += 1; } std.debug.print("bus traces: {d} mismatches across {d} opcodes\n", .{ bus_mismatches, opcodes }); } // An instruction that has not been written yet is not a failure; one that // disagrees with the hardware is. defer if (failed_cases != 0 or cycle_mismatches != 0 or bus_mismatches != 0) std.process.exit(1); if (cycle_mismatches == 0) { std.debug.print("cycle counts: all {d} cases match\n", .{successful_cases}); } else { var opcodes: usize = 0; for (&outcomes) |outcome| { if (outcome.cycle_mismatches != 0) opcodes += 1; } std.debug.print("cycle counts: {d} mismatches across {d} opcodes\n", .{ cycle_mismatches, opcodes }); for (&outcomes, 0..) |outcome, i| { if (outcome.cycle_mismatches == 0) continue; const data = CPU.Opcodes.describe(@intCast(i)).?; std.debug.print(" 0x{x:0>2} {s: <3} {s: <22} {d: >5}/20000 bad (e.g. want {d} cycles, got {d})\n", .{ i, data.mnemonic, @tagName(data.addressing_mode), outcome.cycle_mismatches, outcome.cycle_example[0], outcome.cycle_example[1], }); } } }