// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! Klaus Dormann's functional tests, run against both eight-bit cores. //! //! The SingleStepTests corpus next door checks a processor one instruction at a //! time: set up a machine state, run a single opcode, compare every register, //! flag and bus cycle against a recording. It is exhaustive and it is shallow //! by construction — nothing in it runs two instructions in a row. //! //! These tests are the other shape. Each is a single sixty-four kilobyte image //! that starts at $0400 and computes: it works through every addressing mode of //! every documented opcode, checks each result against a value the assembler //! worked out, and if anything disagrees it jumps to a trap and sits there. Get //! to the end and the last instruction is `jmp *` at a known address, so a run //! has exactly two outcomes and the address the machine settles at says which. //! The author's readme puts it plainly: "the test will loop at the failure //! address" (Dormann, 2020). //! //! What that buys over the corpus is the interaction between instructions — //! flags carried from one to the next, the stack used across a chain of calls, //! decimal mode entered and left — and a great deal of it: thirty million //! instructions for the NMOS part, twenty-two million for the CMOS one. //! //! ## Which core gets which image //! //! `6502_functional_test.bin` is the NMOS 6502 and runs on the `6502` core. //! //! `65C02_extended_opcodes_test.bin` is assembled with both `wdc_op` and //! `rkwl_wdc_op` set, so it expects the bit instructions Rockwell added — BBR, //! BBS, RMB and SMB — as well as WAI and STP. A plain CMOS part has none of //! those and does nothing at those encodings, so it fails almost immediately; //! the image is for a `W65C02`, and that is what it is given here. //! //! ## References //! //! Dormann, K. (2020). *6502_65C02_functional_tests* [Computer software]. //! GitHub. https://github.com/Klaus2m5/6502_65C02_functional_tests //! — Test suites for the 6502 and 65C02, with a readme describing how a //! failure is signalled. const std = @import("std"); const zig65 = @import("zig65"); const feedback = @import("feedback.zig"); /// Where an image comes from. /// /// Two of the four are published assembled and two are not, so half the table /// names a file in the fetched repository and half takes what the build /// assembled and handed over on the command line, in the order the build put /// them there. const Source = union(enum) { bundled: []const u8, assembled: usize, fn name(self: Source) []const u8 { return switch (self) { .bundled => |file| file, .assembled => |i| assembled_names[i], }; } }; /// What the build assembles, in the order `build.zig` passes them. const assembled_names = [_][]const u8{ "6502_decimal_test", "6502_interrupt_test" }; /// Which memory the image needs under it. const Memory = enum { /// Sixty-four kilobytes and nothing else. flat, /// The same, with a register wired to the interrupt pins. See /// `feedback.zig`. interrupt_feedback, }; /// One image, and what it means for it to have passed. /// /// Every one of these ends by not going anywhere — `jmp *` on success, and a /// tight loop at the point of disagreement on failure — so a run stops when /// the program counter either reaches the address a pass ends at or stops /// moving anywhere else. const Test = struct { source: Source, processor: zig65.Processor, memory: Memory = .flat, /// Where the image is loaded. `as65` writes only the bytes the source /// emitted, from the lowest address it used, so this is not always zero. load: u16 = 0, /// Where it is entered. entry: u16 = 0x0400, /// The address a passing run ends at. success: u16, /// A location that has to read zero once `success` is reached, for the one /// test that reports its verdict in memory rather than by where it stops. verdict: ?u16 = null, /// Enough to finish, with room to spare. A failing image settles long /// before this; the cap is only so that a core broken into an unproductive /// loop stops rather than runs forever. limit: usize = 200_000_000, what: []const u8, }; const tests = [_]Test{ .{ .source = .{ .bundled = "6502_functional_test.bin" }, .processor = .@"6502", .success = 0x3469, .what = "every documented NMOS opcode and addressing mode", }, .{ .source = .{ .bundled = "65C02_extended_opcodes_test.bin" }, .processor = .W65C02, .success = 0x24f1, .what = "what the 65C02 added, with Rockwell's bit instructions", }, .{ // Bruce Clark's decimal mode test, which Dormann carries with the // configuration knobs added. It is the one that does not say how it // went by where it stops: it stops in the same place either way and // leaves the answer in `ERROR`, which the source puts at $0b. // // As published it is set to `cputype = 0`, the NMOS part, and to check // the accumulator and the carry but not N, V or Z — those three are // genuinely undefined on a 6502 after a decimal add. The corpus next // door is what checks them on the parts that do define them. .source = .{ .assembled = 0 }, .processor = .@"6502", .load = 0x0200, .entry = 0x0200, .success = 0x024b, .verdict = 0x000b, .what = "decimal mode, against results worked out in binary", }, .{ // The interrupt test needs hardware: there is no way for a program to // raise its own IRQ, and BRK is a different path through the processor // that would prove nothing about the pins. // // The `jmp start` three bytes past the success loop, under the same // banner, is not reachable: `success` is `jmp *` and nothing comes // back from it. $06f5 is where a passing run stops. .source = .{ .assembled = 1 }, .processor = .@"6502", .memory = .interrupt_feedback, .load = 0x000a, .success = 0x06f5, .what = "IRQ, NMI and BRK, through a register wired to the pins", }, }; /// Run one image to wherever it stops. /// /// A pass and a failure are the same shape — a loop that goes nowhere — so the /// way to find either is to notice the program counter arriving at the address /// a pass ends at, or not moving at all. That catches a core that has gone /// somewhere neither the author nor this project expected as well. /// /// Errors are swallowed rather than ended on. The images execute BRK on /// purpose to check that it works, and this core surfaces BRK to the caller; /// stopping there would report a pass as a hang. fn run( comptime processor: zig65.Processor, comptime memory: Memory, image: []const u8, t: Test, ) !struct { u16, usize, u64, ?u8 } { const Model = switch (memory) { .flat => zig65.memory.Flat(.{}), .interrupt_feedback => feedback.Feedback(.{}), }; const Chip = zig65.Chip(.{ .processor = processor }, zig65.clock.FakeClock, Model); var cpu: Chip = undefined; try cpu.init(null, null); try cpu.memory.loadProgram(t.load, image); cpu.reset(); cpu.program_counter.jump(t.entry); var instructions: usize = 0; while (instructions < t.limit) : (instructions += 1) { if (cpu.program_counter.value == t.success) break; const before = cpu.program_counter.value; cpu.executeInstruction() catch {}; if (cpu.program_counter.value == before) break; } return .{ cpu.program_counter.value, instructions, cpu.clock.cycles, if (t.verdict) |at| cpu.memory.peek(at) else null, }; } /// Read one image and run it, saying whether it passed. /// /// A function of its own because the loop over the table has to be an `inline /// for` — each test names the core and the memory it wants, and those are /// comptime parameters — and giving up on one image partway through is /// ordinary runtime control flow. fn one(comptime t: Test, io: std.Io, gpa: std.mem.Allocator, full: []const u8) !bool { std.debug.print("{s}\n {s}, on a {s}\n", .{ t.source.name(), t.what, @tagName(t.processor) }); const image = std.Io.Dir.cwd().readFileAlloc(io, full, gpa, .limited(0x10001)) catch |err| { std.debug.print(" cannot read '{s}': {s}\n\n", .{ full, @errorName(err) }); return false; }; defer gpa.free(image); if (image.len == 0 or @as(usize, t.load) + image.len > 0x10000) { std.debug.print(" will not fit in memory at ${X:0>4}: {d} bytes\n\n", .{ t.load, image.len }); return false; } const settled, const instructions, const cycles, const verdict = try run(t.processor, t.memory, image, t); if (settled != t.success) { std.debug.print( " FAIL: settled at ${X:0>4}, wanted ${X:0>4}, after {d} instructions\n" ++ " the listing beside the image says what is checked there\n\n", .{ settled, t.success, instructions }, ); return false; } if (verdict) |reported| { if (reported != 0) { std.debug.print( " FAIL: reached ${X:0>4} but left {d} at ${X:0>4}, which is its way of\n" ++ " saying a case disagreed\n\n", .{ settled, reported, t.verdict.? }, ); return false; } } std.debug.print( " PASS at ${X:0>4}, after {d} instructions and {d} cycles\n\n", .{ settled, instructions, cycles }, ); return true; } const usage = \\usage: functional BIN_FILES_DIRECTORY [ASSEMBLED...] [--only SUBSTRING] \\ \\Runs Klaus Dormann's functional tests against this project's eight-bit \\cores. BIN_FILES_DIRECTORY is the `bin_files` directory of his \\repository and ASSEMBLED are the two tests he publishes as source only, \\assembled; `zig build run` supplies all three from the fetched copy. \\ \\--only runs just the tests whose name contains SUBSTRING. \\ ; pub fn main(init: std.process.Init) !void { const io = init.io; const gpa = std.heap.smp_allocator; var where: ?[]const u8 = null; var assembled: [assembled_names.len]?[]const u8 = @splat(null); var given: usize = 0; var only: ?[]const u8 = null; var args: std.process.Args.Iterator = .init(init.minimal.args); _ = args.skip(); while (args.next()) |arg| { if (std.mem.eql(u8, arg, "--only")) { only = args.next(); } else if (arg.len > 0 and arg[0] != '-') { if (where == null) { where = arg; } else if (given < assembled.len) { assembled[given] = arg; given += 1; } else { std.debug.print("{s}", .{usage}); std.process.exit(2); } } else { std.debug.print("{s}", .{usage}); std.process.exit(if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) 0 else 2); } } const dir = where orelse { std.debug.print("{s}", .{usage}); std.process.exit(2); }; var failures: usize = 0; var ran: usize = 0; var skipped: usize = 0; inline for (tests) |t| { if (only == null or std.mem.indexOf(u8, t.source.name(), only.?) != null) { switch (t.source) { .bundled => |file| { ran += 1; const full = try std.fs.path.join(gpa, &.{ dir, file }); defer gpa.free(full); if (!try one(t, io, gpa, full)) failures += 1; }, // The assembler is a lazy dependency, so a build that has not // fetched it hands over nothing rather than a path. Saying so // beats reporting a failure that is really an absence. .assembled => |i| if (assembled[i]) |path| { ran += 1; if (!try one(t, io, gpa, path)) failures += 1; } else { skipped += 1; std.debug.print("{s}\n not assembled, so not run\n\n", .{t.source.name()}); }, } } } if (ran == 0 and skipped == 0) { std.debug.print("nothing matched --only\n", .{}); std.process.exit(2); } std.debug.print("{d} of {d} passed", .{ ran - failures, ran }); if (skipped != 0) std.debug.print(", {d} not assembled", .{skipped}); std.debug.print("\n", .{}); if (failures != 0) std.process.exit(1); }