// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT const std = @import("std"); const builtin = @import("builtin"); const options = @import("options"); const zig65 = @import("zig65"); // const single_step_tests = t: { // var t: [256][]const u8 = undefined; // for (0..256) |i| { // var buf: [32]u8 = undefined; // const name = std.fmt.bufPrint(&buf, "single_step_test_6502_{x:0>2}", .{i}) catch unreachable; // t[i] = @embedFile(name); // } // break :t t; // }; const RAM = @import("single_step_tests/RAM.zig"); const State = struct { pc: u16, s: u8, a: u8, x: u8, y: u8, p: u8, ram: []RAM, }; const Cycle = @import("single_step_tests/Cycle.zig"); const Test = struct { name: []const u8, initial: State, final: State, cycles: []Cycle, }; const usage = \\usage: single_step_tests DIRECTORY \\ \\Runs every opcode against the SingleStepTests corpus in DIRECTORY, which \\is the directory holding 00.json through ff.json. In the 65x02 repository \\that is 6502/v1. `zig build single-step-tests` 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, which is worth knowing /// before one has been read: it means an opcode can be counted as skipped /// without parsing four megabytes to find out how many were in it. const cases_per_opcode = 10_000; var debug_allocator: std.heap.DebugAllocator(.{}) = .init; /// Whether a cycle the corpus records is one no emulator can reproduce. /// /// There is exactly one such cycle, and it is worth being precise about rather /// than waving away. Adding or subtracting against a constant in decimal mode /// costs the CMOS parts an extra cycle, which they spend putting the answer /// right, and something is on the address bus while they do. Every other mode /// has an operand address to re-read and does; a constant has none, and what /// the recordings show instead is the same address in every single case of an /// opcode — $0056 for ADC and $0000 for SBC on one set, $0059 and $0000 on /// another. An address that does not vary with the operands, the registers or /// the program counter, and differs between recordings of the same /// instruction, is the bench that made the recording rather than the chip. /// Reproducing it would be reproducing their bench. fn known_difference(opcode: u8, cycle: usize, case: Test) bool { if (options.processor == .@"6502" or options.processor == .RP2A03) return false; if (opcode != 0x69 and opcode != 0xe9) return false; // Only in decimal, and only the last cycle, which is the correction. if (case.initial.p & 0x08 == 0) return false; return cycle == case.cycles.len - 1; } /// Runs every opcode against the SingleStepTests corpus in the directory named /// on the command line. /// /// Each case gives a starting state, the state the hardware ended in, and every /// access it made on the way. All three are checked: the architectural state, /// the number of cycles, and the address, value and direction of each access. /// The last is the sharpest of them, because a discarded read leaves no trace /// in the registers but is exactly what a memory mapped device reacts to. /// /// Build with -Dssf= to run only some opcodes. /// Flat memory is the only model this corpus can run against: it uses the /// whole address space as ordinary memory, including the page a real machine /// fills with I/O. And it is the one caller that wants the bus log, since /// checking the trace against the hardware's is the point. const CPU = zig65.Chip( .{ .processor = switch (options.processor) { .@"6502" => .@"6502", .RP2A03 => .RP2A03, .@"65C02" => .@"65C02", .R65C02 => .R65C02, .W65C02 => .W65C02, // Not this runner's to run: the 65816 is a separate core with a // separate corpus and a separate runner, and build.zig sends that // processor to main65816.zig instead. Saying so here rather than // leaving an `else` means the next processor added has to be given a // home on purpose. .@"65C816" => @compileError("the 65816 is run by main65816.zig, not this runner"), }, }, zig65.clock.FakeClock, zig65.memory.Flat(.{ .bus_log = true }), ); /// What running one opcode's ten thousand cases came to. /// /// Everything a worker learns comes back in one of these rather than being /// printed where it happened, so that two hundred and fifty-six of them can /// run at once and still be reported in opcode order. const Outcome = struct { total: usize = 0, succeeded: usize = 0, failed: usize = 0, skipped: usize = 0, decimal: usize = 0, cycle_mismatches: usize = 0, /// The first disagreement, as wanted and got. cycle_example: [2]u64 = .{ 0, 0 }, bus_mismatches: usize = 0, /// Cycles that differ from the recording for a reason that is understood /// and written down: see `known_difference`. known: usize = 0, /// The first bus disagreement, described. Owned by the caller. bus_report: ?[]u8 = null, /// The first architectural failure, described at length. Owned by the /// caller. report: ?[]u8 = null, /// Something that is not a test failure and should stop everything. 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 every case for one opcode. Takes its own allocator because several of /// these run at once and each parses four megabytes of its own. 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.get(opcode).?; const filename = std.fmt.allocPrint(alloc, "{x:0>2}.json", .{opcode}) 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; }; // An empty file is not a broken one. Western Design's part has two // instructions that stop the processor — one until an interrupt, one until // reset — and neither can be recorded a case at a time, so the corpus // holds a file with nothing in it for each. There is nothing here to check // them against, and saying so is better than either failing or pretending. if (test_data.len == 0) { outcome.total = 0; return outcome; } 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, data, case, opcode, &outcome); if (outcome.fatal != null) return outcome; } return outcome; } fn oom(outcome: *Outcome) Outcome { outcome.fatal = "out of memory"; return outcome.*; } /// Describes a failing case at length: what was wanted, what happened, and the /// memory either side of it. Written into a buffer rather than to the terminal, /// so that it can be shown next to the opcode it belongs to. 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 }); // std.debug.print("\n{s}\n\n", .{code}); 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.pointer) { try stderr.print("stack pointer: FAIL (0x{x:0>2} != 0x{x:0>2})\n", .{ cpu.stack.pointer, case.final.s }); } if (case.final.a != cpu.registers.get(.A)) { try stderr.print("register A: FAIL (0x{x:0>2} != 0x{x:0>2})\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>2} != 0x{x:0>2})\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>2} != 0x{x:0>2})\n", .{ cpu.registers.get(.Y), case.final.y }); } 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("{s}: memory 0x{x:0>4}: FAIL (0x{x:0>2} != 0x{x:0>2})\n", .{ case.name, ram.address, cpu.memory.peek(ram.address), ram.value, }); } } try stderr.print("\n", .{}); try stderr.print(" Initial Final Actual\n", .{}); try stderr.print("PC: ${x:0>4} PC: ${x:0>4} PC: ${x:0>4}\n", .{ case.initial.pc, case.final.pc, cpu.program_counter.value }); try stderr.print("SP: ${x:0>2} SP: ${x:0>2} SP: ${x:0>2}\n", .{ case.initial.s, case.final.s, cpu.stack.pointer }); try stderr.print(" A: ${x:0>2} A: ${x:0>2} A: ${x:0>2}\n", .{ case.initial.a, case.final.a, cpu.registers.get(.A) }); try stderr.print(" X: ${x:0>2} X: ${x:0>2} X: ${x:0>2}\n", .{ case.initial.x, case.final.x, cpu.registers.get(.X) }); try stderr.print(" Y: ${x:0>2} Y: ${x:0>2} Y: ${x:0>2}\n", .{ case.initial.y, case.final.y, cpu.registers.get(.Y) }); 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"); // var initial_buf: [8]u8 = undefined; // const initial = cpu.flag.format(&initial_buf, @bitCast(case.initial.p)); // var final_buf: [8]u8 = undefined; // const final = cpu.flag.format(&final_buf, @bitCast(case.final.p)); // var actual_buf: [8]u8 = undefined; // const actual = cpu.flag.format(&actual_buf, cpu.flag.value); // try stderr.print(" P: {s} P: {s} P: {s}\n", .{ initial, final, actual }); // try stderr.print("\n", .{}); for (0..@max(case.initial.ram.len, case.final.ram.len)) |j| { if (j < case.initial.ram.len) try stderr.print(" ${x:0>4}: ${x:0>2}", .{ case.initial.ram[j].address, case.initial.ram[j].value }) else try stderr.print(" ", .{}); if (j < case.final.ram.len) try stderr.print(" ${x:0>4}: ${x:0>2}", .{ case.final.ram[j].address, case.final.ram[j].value }) else try stderr.print(" ", .{}); if (j < case.final.ram.len) try stderr.print(" ${x:0>4}: ${x:0>2}\n", .{ case.final.ram[j].address, cpu.memory.peek(case.final.ram[j].address) }) else try stderr.print("\n", .{}); } try stderr.print("\n", .{}); } /// Runs one case and folds what happened into the outcome. Nothing is printed: /// the reports are built in memory so that the opcode they belong to can be /// identified when they are shown, whatever order the workers finished in. fn runCase( gpa: std.mem.Allocator, data: *const CPU.Opcodes.Data, case: Test, opcode: u8, outcome: *Outcome, ) void { var failed: bool = false; var cpu: CPU = undefined; try cpu.init(null, null); defer cpu.deinit(); cpu.program_counter.value = case.initial.pc; cpu.stack.pointer = case.initial.s; cpu.registers.set(.A, case.initial.a); cpu.registers.set(.X, case.initial.x); cpu.registers.set(.Y, case.initial.y); cpu.flags.load(case.initial.p); if (cpu.flags.isSet(.D)) { // std.debug.print("{s}: skipping test with decimal mode\n", .{case.name}); outcome.decimal += 1; // continue; } for (case.initial.ram) |ram| { cpu.memory.poke(ram.address, ram.value); } // var buf: [64]u8 = undefined; // const code = try zig65.opcodes.format(&buf, &cpu.memory, cpu.program_counter.value); cpu.executeInstruction() catch |err| switch (err) { error.Break => {}, error.Jam => {}, else => { outcome.fatal = "an instruction returned an unexpected error"; return; }, }; if (case.final.pc != cpu.program_counter.value) failed = true; if (case.final.s != cpu.stack.pointer) 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 (!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. A discarded read // leaves no trace in the registers but is exactly what a soft // switch reacts to, so the addresses matter as much as the count. bus: for (case.cycles, 0..) |want, j| { const got: ?CPU.Memory.Access = if (j < cpu.memory.bus.len) cpu.memory.bus.entries[j] else null; if (got) |access| { if (access.address == want.address and access.value == want.value and (access.direction == .write) == (want.direction == .write)) continue; } if (known_difference(opcode, j, case)) { outcome.known += 1; 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 {s} ${x:0>4}=${x:0>2}, ", .{ opcode, data.mnemonic, j, @tagName(want.direction), want.address, want.value, }) catch break :describe; if (got) |access| out.print("got {s} ${x:0>4}=${x:0>2}\n", .{ @tagName(access.direction), access.address, access.value, }) 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) { if (outcome.cycle_mismatches == 0) outcome.cycle_example = .{ case.cycles.len, 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); // Best effort: a report that cannot be written is not a reason // to lose the count of what failed. writeReport(&buffer.writer, data, case, &cpu) catch {}; outcome.report = buffer.toOwnedSlice() catch null; return; } else { outcome.succeeded += 1; } } pub fn main(init: std.process.Init) !void { const io = init.io; var args: std.process.Args.Iterator = .init(init.minimal.args); _ = args.skip(); // the name the program was invoked by const data_directory = args.next() orelse { std.debug.print("single_step_tests: no test data directory given\n\n{s}", .{usage}); std.process.exit(2); }; if (args.next()) |extra| { std.debug.print("single_step_tests: 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 6502", .estimated_total_items = 256, }); defer root.end(); // Which opcodes to actually run. Decided before anything is read, so that // asking for one opcode costs one opcode. var wanted: [256]bool = @splat(true); var outcomes: [256]Outcome = @splat(.{}); for (0..256) |i| { const opcode: u8 = @intCast(i); if (CPU.Opcodes.get(opcode) == null) { wanted[i] = false; } else 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_opcode, .skipped = cases_per_opcode }; } // The two hundred and fifty-six files have nothing to do with each other, // so they are read, parsed and run at the same time. In batches rather // than all at once, because each worker holds a parsed four megabyte file // and all of them at once would be gigabytes. const at_once = 16; 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 data = CPU.Opcodes.get(opcode).?; var name_buf: [32]u8 = undefined; const name = try std.fmt.bufPrint(&name_buf, "Opcode 0x{x:0>2} {s}", .{ opcode, data.mnemonic }); const node = root.start(name, cases_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); } } // Everything below here is reporting, in opcode order whatever order the // work finished in. var total_cases: usize = 0; var failed_cases: usize = 0; var skipped_cases: usize = 0; var successful_cases: usize = 0; var decimal_cases: usize = 0; var cycle_mismatches: usize = 0; var bus_mismatches: usize = 0; var known_cycles: usize = 0; for (&outcomes, 0..) |*outcome, i| { defer outcome.deinit(gpa); if (outcome.fatal) |why| { std.debug.print("single_step_tests: 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; decimal_cases += outcome.decimal; cycle_mismatches += outcome.cycle_mismatches; bus_mismatches += outcome.bus_mismatches; known_cycles += outcome.known; if (outcome.report) |report| std.debug.print("{s}", .{report}); if (outcome.bus_report) |report| std.debug.print("{s}", .{report}); } std.debug.print("\n{d} tests: {d} succeeded, {d} failed, {d} skipped, {d} decimal\n", .{ total_cases, successful_cases, failed_cases, skipped_cases, decimal_cases }); if (bus_mismatches == 0 and known_cycles == 0) { std.debug.print("bus traces: every cycle matches\n", .{}); } else if (bus_mismatches == 0) { std.debug.print( "bus traces: every cycle matches but {d}, which are the decimal correction\n" ++ " of ADC and SBC against a constant and are the recording\n" ++ " rather than the chip: see known_difference\n", .{known_cycles}, ); } 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 }); } // Anything that disagreed with the hardware has to fail the build. Until // now this printed what it found and exited nought, so a corpus run could // report two and a half thousand failures and still count as a pass. 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.get(@intCast(i)).?; std.debug.print(" 0x{x:0>2} {s: <3} {s: <16} {d: >5}/10000 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], }); } } }