// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! Whole machines, end to end: each test powers a system on with Apple's own //! ROM, waits for it to come up in BASIC, types a short program at the //! keyboard the way a person would, runs it, and reads the answer off the //! screen. Nothing here knows how any of that is done; that is the point. A //! unit test says a switch flips, and these say the machine still computes. //! //! The ROMs are Apple's and cannot be in this repository. They are looked for //! in `~/dev/Apple ROMs`, and the disks in `~/dev/Apple Disks`, whose READMEs //! catalogue each one by size and hash, and a test whose file is not there is //! *skipped* rather than failed, which is //! what lets `zig build test` run this file on a machine that has none of //! them, CI included. On a machine that has them, a skip is worth noticing. //! //! Keys go in the way the front end sends them. Every one of these machines //! has one keyboard latch and no queue behind it, and its firmware clears the //! latch on the way in to reading a line, so a key is only pressed once the //! machine is sitting in a read loop asking for one and coming away empty. //! That is what `empty_polls` counts, and why typing here paces itself by the //! machine rather than by any number of cycles. //! //! The IIgs is the one that needs a disk. A ROM 01 with nothing to start //! from prints `Check startup device!` and keeps scanning, and Control-Reset //! at that point goes back through the reset vector to the scan rather than //! to BASIC — the Firmware Reference lists the cold start as what //! Control-Reset does "if a valid reset vector does not exist" (Apple //! Computer, Inc., 1987a, ch. 2). So it boots a ProDOS disk whose startup //! program leaves the `]` prompt, from the 5.25-inch drive, which is also the //! test that the Speed register's motor-on detectors slow the machine for it. const std = @import("std"); const testing = std.testing; const clock = @import("clock.zig"); const cpu8 = @import("cpu8.zig"); const cpu16 = @import("cpu16.zig"); const disk2 = @import("disk2.zig"); const disk35 = @import("disk35.zig"); const unidisk = @import("unidisk.zig"); const omninet = @import("omninet.zig"); const diskfile = @import("diskfile.zig"); const memory = @import("memory8.zig"); const memory16 = @import("memory16.zig"); const rtc = @import("rtc.zig"); const blockdevice = @import("blockdevice.zig"); const profile = @import("profile.zig"); const prodos = @import("prodos.zig"); const dos33 = @import("dos33.zig"); const pascal = @import("pascal.zig"); const woz = @import("woz.zig"); const writeback = @import("writeback.zig"); const shrinkit = @import("shrinkit"); const scsi = @import("scsi.zig"); /// The two catalogues, under the home directory: one of ROMs, one of disk and /// tape images. const Catalogue = enum { roms, disks, fn directory(self: Catalogue) []const u8 { return switch (self) { .roms => "dev/Apple ROMs", .disks => "dev/Apple Disks", }; } }; /// Reads one of the catalogued files, or skips the test that wanted it. fn catalogued(alloc: std.mem.Allocator, from: Catalogue, name: []const u8) ![]u8 { const home = testing.environ.getPosix("HOME") orelse return error.SkipZigTest; const path = try std.fmt.allocPrint(alloc, "{s}/{s}/{s}", .{ home, from.directory(), name }); defer alloc.free(path); return std.Io.Dir.cwd().readFileAlloc(testing.io, path, alloc, .limited(1 << 24)) catch |err| switch (err) { error.FileNotFound => error.SkipZigTest, else => err, }; } /// A machine's clock rate, for turning seconds into cycles. Every eight-bit /// Apple runs at a hair over a megahertz, and none of the waits below is /// close enough to the edge for the hair to matter. A IIgs's clock counts its /// fast cycles, three to one of these, so its waits are given in `gs_second`. const second: u64 = 1_023_000; const gs_second: u64 = 3 * second; /// Which part of a machine has the keyboard and the text screen on it: the /// memory model itself on an eight-bit machine, and the Mega II on a IIgs. const Front = enum { memory, mega2 }; /// One machine, powered on, with a keyboard to type at and a screen to read. fn System(comptime CPU: type, comptime front: Front) type { return struct { const Self = @This(); cpu: CPU, alloc: std.mem.Allocator, /// The part with the keyboard and the screen on it. fn io(self: *Self) switch (front) { .memory => *CPU.Memory, .mega2 => *@FieldType(CPU.Memory, "mega2"), } { return switch (front) { .memory => &self.cpu.memory, .mega2 => &self.cpu.memory.mega2, }; } /// Executes one instruction. A processor that has jammed or hit a /// BRK is left where it is; the screen will say so soon enough. fn step(self: *Self) void { self.cpu.executeInstruction() catch {}; } /// Runs for so many cycles of the machine's own clock. fn run(self: *Self, cycles: u64) void { const until = self.cpu.clock.cycles + cycles; while (self.cpu.clock.cycles < until) self.step(); } /// Types a line and presses Return. Each key waits until the machine /// is in a read loop asking for one; see the header. fn typeLine(self: *Self, line: []const u8) !void { for (line) |key| try self.press(key); try self.press('\r'); } fn press(self: *Self, key: u8) !void { const started = self.cpu.clock.cycles; // A machine that polls for its keys is given one only once it is // sitting in a read loop, see the header; one that takes them on // an interrupt, as SOS does, needs no such wait, and says so. const Io = @TypeOf(self.io().*); while (self.io().strobe or (!self.byInterrupt() and @hasField(Io, "empty_polls") and self.io().empty_polls < 64)) { self.step(); if (self.cpu.clock.cycles - started > 30 * second) { try self.report(); return error.NeverAskedForAKey; } } // A machine that takes its keys on an interrupt has only just // cleared the strobe, inside the handler; feeding the next key // now can beat the handler to its type-ahead buffer. A frame's // grace lets it finish and get back to its main loop, which is // what pacing keys once a frame does for the interactive front // end. if (self.byInterrupt()) self.run(second / 60); self.io().pressKey(key); } fn byInterrupt(self: *Self) bool { if (comptime @hasDecl(@TypeOf(self.io().*), "takesKeysByInterrupt")) return self.io().takesKeysByInterrupt(); return false; } /// The text screen, one line per row, with a newline before the /// first as well as after every one, so that a prompt at the start /// of a row can be asked for as `"\n]"` and a `]` in the middle of /// `APPLE ][` cannot be mistaken for it. fn screen(self: *Self) ![]u8 { var text: std.Io.Writer.Allocating = .init(self.alloc); defer text.deinit(); try self.io().writeText(&text.writer); const flat = text.written(); const columns = self.io().mode().columns() orelse return error.NotShowingText; var lined: std.Io.Writer.Allocating = .init(self.alloc); errdefer lined.deinit(); try lined.writer.writeByte('\n'); var at: usize = 0; while (at < flat.len) : (at += columns) { const row = flat[at..@min(at + columns, flat.len)]; try lined.writer.writeAll(std.mem.trimEnd(u8, row, " ")); try lined.writer.writeByte('\n'); } return lined.toOwnedSlice(); } fn shows(self: *Self, needle: []const u8) !bool { const text = try self.screen(); defer self.alloc.free(text); return std.mem.indexOf(u8, text, needle) != null; } /// Runs until the screen shows the text, or fails, with the screen /// as it stands, after so many cycles without it. fn waitFor(self: *Self, needle: []const u8, cycles: u64) !void { const until = self.cpu.clock.cycles + cycles; while (self.cpu.clock.cycles < until) { self.run(second / 50); if (try self.shows(needle)) return; } std.debug.print("waited {d} cycles for '{s}' and the screen shows:\n", .{ cycles, needle }); try self.report(); return error.NotShown; } /// Expects the text on the screen now. fn expect(self: *Self, needle: []const u8) !void { if (try self.shows(needle)) return; std.debug.print("expected '{s}' and the screen shows:\n", .{needle}); try self.report(); return error.NotShown; } fn report(self: *Self) !void { const text = try self.screen(); defer self.alloc.free(text); var lines = std.mem.splitScalar(u8, text, '\n'); while (lines.next()) |line| { if (line.len != 0) std.debug.print(" |{s}\n", .{line}); } } }; } /// The program every machine is given: three lines and a loop, so that the /// interpreter has to tokenize, store, branch, multiply and print, and the /// answer on the screen is something no interpreter prints by accident. const program = [_][]const u8{ "10 FOR I=1 TO 3", "20 PRINT \"SQUARE \";I*I", "30 NEXT I", }; /// Types the program, runs it, and checks all three answers came out. fn typeAndRun(system: anytype) !void { for (program) |line| try system.typeLine(line); try system.typeLine("RUN"); try system.waitFor("SQUARE 9", 2 * second); try system.expect("SQUARE 1"); try system.expect("SQUARE 4"); } /// An eight-bit machine: a processor around a memory model, with the /// keyboard and screen on the model. fn EightBit(comptime Processor: fn (type, fn (type) type) type, comptime Model: fn (type) type) type { return System(Processor(clock.FakeClock, Model), .memory); } /// Brings one up on a ROM image, as `--rom` would. fn powerOn( comptime Processor: fn (type, fn (type) type) type, comptime Model: fn (type) type, rom: []const u8, ) !EightBit(Processor, Model) { var system: EightBit(Processor, Model) = .{ .cpu = undefined, .alloc = testing.allocator }; try system.cpu.init(null, null); try system.cpu.memory.loadROMAtEnd(rom); system.cpu.reset(); return system; } test "an Apple II Plus comes up in Applesoft, takes a program at the keyboard, and runs it" { const image = try catalogued(testing.allocator, .roms, "APPLE2.ROM"); defer testing.allocator.free(image); // The 20K image was dumped from a machine with a Disk II card in slot 6, // and the card's boot PROM came with it at $c600. The model takes the // image's slot space at its word, so that machine boots the card and // waits for a disk, as the real one did. The system ROM proper is the // 12K at the top, and a machine given only that has empty slots. const rom = image[image.len - 0x3000 ..]; var system = try powerOn(cpu8.CPU, memory.AppleIIPlus(.{}), rom); // The Autostart ROM looks through the slots for a disk controller, finds // none, and lands in BASIC. try system.waitFor("\n]", 2 * second); try typeAndRun(&system); } test "an enhanced Apple IIe comes up in Applesoft, takes a program at the keyboard, and runs it" { // The 32K image is the 1985 enhanced firmware, and says so at $fbc0; the // enhancement's processor was the 65C02, and its firmware uses it. const rom = try catalogued(testing.allocator, .roms, "APPLE2E.ROM"); defer testing.allocator.free(rom); var system = try powerOn(cpu8.CMOS, memory.AppleIIe(.{}), rom); try testing.expectEqual(memory.apple2e.Firmware.enhanced, system.cpu.memory.firmware); // "An original Apple IIe will display Apple ][ at the top of the monitor // screen, while an enhanced Apple IIe will display Apple //e" (Apple // Computer, Inc., 1985b, p. xxix). try system.waitFor("Apple //e", 2 * second); try system.waitFor("\n]", 2 * second); try typeAndRun(&system); } test "an enhanced Apple IIe with a RamWorks card boots and runs a program, the card not in the way" { // RamWorks lives in the auxiliary slot and does nothing until a program // writes $C073, so a machine with one fitted comes up exactly as it would // without: bank zero is the motherboard's own auxiliary 64K, which is what // the eighty-column firmware and everything else use. Three megabytes is a // RamWorks III, forty-seven banks on top of the one the machine has. const rom = try catalogued(testing.allocator, .roms, "APPLE2E.ROM"); defer testing.allocator.free(rom); var system = try powerOn(cpu8.CMOS, memory.AppleIIe(.{}), rom); const banks = try testing.allocator.alloc(memory.apple2e.AuxiliaryBank, 47); defer testing.allocator.free(banks); system.cpu.memory.fitRamWorks(banks); try system.waitFor("Apple //e", 2 * second); try system.waitFor("\n]", 2 * second); try typeAndRun(&system); // And the card is really there: a byte put in bank one is kept, and bank // zero is still the machine's own auxiliary memory, untouched by the visit. system.cpu.memory.aux.ram[0x3000] = 0x5a; system.cpu.memory.write(u8, 0xc005, 0); // RAMWRT on system.cpu.memory.write(u8, 0xc003, 0); // RAMRD on system.cpu.memory.write(u8, 0xc073, 1); // bank one system.cpu.memory.write(u8, 0x3000, 0xa5); try testing.expectEqual(@as(u8, 0xa5), banks[0].ram[0x3000]); system.cpu.memory.write(u8, 0xc073, 0); // bank zero try testing.expectEqual(@as(u8, 0x5a), system.cpu.memory.read(u8, 0x3000)); } test "an Apple IIe with an Uthernet II reaches the W5100 through the card's device selects" { const rom = try catalogued(testing.allocator, .roms, "APPLE2E.ROM"); defer testing.allocator.free(rom); var system = try powerOn(cpu8.CMOS, memory.AppleIIe(.{}), rom); system.cpu.memory.fitUthernet(3); // The Uthernet II wires the W5100's indirect bus to four of slot 3's // sixteen device selects, which are $C0B0 to $C0B3: the mode register, the // pointer's two bytes, and the data register. Driving them from the // machine's own bus opens a TCP socket the way IP65 would — write the // socket's mode register, then its command register — and the chip answers // in its status register. const bus = struct { fn poke(sys: anytype, pointer: u16, value: u8) void { sys.cpu.memory.write(u8, 0xc0b1, @truncate(pointer >> 8)); sys.cpu.memory.write(u8, 0xc0b2, @truncate(pointer)); sys.cpu.memory.write(u8, 0xc0b3, value); } fn peek(sys: anytype, pointer: u16) u8 { sys.cpu.memory.write(u8, 0xc0b1, @truncate(pointer >> 8)); sys.cpu.memory.write(u8, 0xc0b2, @truncate(pointer)); return sys.cpu.memory.read(u8, 0xc0b3); } }; system.cpu.memory.write(u8, 0xc0b0, 0x00); // mode: no auto-increment // Socket 0's registers are at $0400. Mode register (offset 0) = TCP, then // command register (offset 1) = OPEN. bus.poke(&system, 0x0400, 0x01); // Sn_MR = TCP bus.poke(&system, 0x0401, 0x01); // Sn_CR = OPEN // The chip took the command and moved the socket to SOCK_INIT ($13), which // it reports in the status register at offset 3. try testing.expectEqual(@as(u8, 0x13), bus.peek(&system, 0x0403)); // And the command register cleared itself, as the real chip does. try testing.expectEqual(@as(u8, 0x00), bus.peek(&system, 0x0401)); } test "an Apple IIe with an Uthernet reaches the CS8900A through the card's device selects" { const rom = try catalogued(testing.allocator, .roms, "APPLE2E.ROM"); defer testing.allocator.free(rom); var system = try powerOn(cpu8.CMOS, memory.AppleIIe(.{}), rom); system.cpu.memory.fitCs8900(3); // The Uthernet wires the CS8900A's I/O ports to slot 3's sixteen device // selects, $C0B0 to $C0BF. The PacketPage pointer is the port at $C0BA and // the data port at $C0BC, each a sixteen-bit port over a pair of bytes. // Point the window at the product code the way a driver checks the chip is // there, and read it back: $630E says it is a CS8900A. system.cpu.memory.write(u8, 0xc0ba, 0x00); // pointer low: PacketPage 0x0000 system.cpu.memory.write(u8, 0xc0bb, 0x00); // pointer high const low = system.cpu.memory.read(u8, 0xc0bc); // data low const high = system.cpu.memory.read(u8, 0xc0bd); // data high try testing.expectEqual(@as(u16, 0x630e), @as(u16, low) | @as(u16, high) << 8); } test "an original Apple IIe comes up in Applesoft, takes a program at the keyboard, and runs it" { // The 1983 CD and EF ROMs as one 16K image, on the 6502 the machine had. const rom = try catalogued(testing.allocator, .roms, "apple2e-unenhanced.rom"); defer testing.allocator.free(rom); var system = try powerOn(cpu8.CPU, memory.AppleIIe(.{}), rom); try testing.expectEqual(memory.apple2e.Firmware.original, system.cpu.memory.firmware); try system.waitFor("Apple ][", 2 * second); try system.waitFor("\n]", 2 * second); try typeAndRun(&system); } test "an Apple IIc with no disk in it is reset into Applesoft, takes a program at the keyboard, and runs it" { // The first IIc's ROM, which is the one the machine was written against. const rom = try catalogued(testing.allocator, .roms, "Apple IIc ROM FF - 342-0272-A.bin"); defer testing.allocator.free(rom); // A IIc is a 65C02, and its firmware uses the instructions that says. var system = try powerOn(cpu8.CMOS, memory.AppleIIc(.{}), rom); // A IIc's drive is built in, so its firmware does not look for a card: // it starts the drive and waits for a disk that is not there, and what // the owner did about that was press Control-Reset, which the firmware // takes as a warm start into BASIC. system.run(second); system.cpu.reset(); try system.waitFor("\n]", 2 * second); try typeAndRun(&system); } test "an Apple IIc with the memory-expansion ROM boots a ProDOS disk into Applesoft" { const alloc = testing.allocator; // ROM 3, the Memory Expansion revision: 32K, two banks reached through // $C028, and a firmware that goes looking for a UniDisk 3.5 and a memory // card on the disk port before it will start from the drive in the case. const rom = try catalogued(alloc, .roms, "Apple IIc ROM 03 - 341-0445-A.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "ProDOS BASIC Programming Examples - 680-0235-A.dsk"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "examples.dsk"); defer opened.deinit(alloc); const floppy = try alloc.create(disk2.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data, opened.image.order() orelse return error.NibbleImage); floppy.write_protected = opened.image.write_protected; var system = try powerOn(cpu8.CMOS, memory.AppleIIc(.{}), rom); system.cpu.memory.drives().insert(0, floppy); system.cpu.reset(); // The scan for the drives that are not there has to finish before the // machine will read the one that is. try system.waitFor("\n]", 300 * second); try typeAndRun(&system); } test "an Apple IIc still boots with the memory expansion card in the connector" { const alloc = testing.allocator; // The card answers where a slot 4 card's registers would be, which is // territory the machine otherwise leaves alone; putting one in must not // disturb the way the machine starts. What the card does at those // registers is proved in `memory8/apple2e.zig`; this is the machine // around it. // // ProDOS is not asked for a RAMdisk here, and could not give one: the // ProDOS on this disk is the 1983 release, which greets the machine as an // Apple //e and knows nothing of a card that was sold three years later. // It does see something at slot 4 and calls it a ProFile, which is what a // catalogue of that age makes of registers it has no driver for. const rom = try catalogued(alloc, .roms, "Apple IIc ROM 03 - 341-0445-A.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "ProDOS BASIC Programming Examples - 680-0235-A.dsk"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "examples.dsk"); defer opened.deinit(alloc); const floppy = try alloc.create(disk2.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data, opened.image.order() orelse return error.NibbleImage); floppy.write_protected = opened.image.write_protected; const ram = try alloc.alloc(u8, 512 * 1024); defer alloc.free(ram); @memset(ram, 0); var system = try powerOn(cpu8.CMOS, memory.AppleIIc(.{}), rom); try system.cpu.memory.fitMemoryExpansion(ram); system.cpu.memory.drives().insert(0, floppy); system.cpu.reset(); try system.waitFor("\n]", 300 * second); try typeAndRun(&system); } test "an Apple IIc with the later memory-expansion ROM boots a ProDOS disk into Applesoft" { const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIc ROM 04 - 341-0445-B.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "ProDOS BASIC Programming Examples - 680-0235-A.dsk"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "examples.dsk"); defer opened.deinit(alloc); const floppy = try alloc.create(disk2.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data, opened.image.order() orelse return error.NibbleImage); floppy.write_protected = opened.image.write_protected; var system = try powerOn(cpu8.CMOS, memory.AppleIIc(.{}), rom); system.cpu.memory.drives().insert(0, floppy); system.cpu.reset(); // ROM 4 is ROM 3's later build and scans the port the same way. try system.waitFor("\n]", 300 * second); try typeAndRun(&system); } test "an Apple IIc with the UniDisk 3.5 ROM boots a ProDOS disk into Applesoft" { const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIc ROM 00 - 342-0033-A - 1985.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "ProDOS BASIC Programming Examples - 680-0235-A.dsk"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "examples.dsk"); defer opened.deinit(alloc); const floppy = try alloc.create(disk2.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data, opened.image.order() orelse return error.NibbleImage); floppy.write_protected = opened.image.write_protected; var system = try powerOn(cpu8.CMOS, memory.AppleIIc(.{}), rom); system.cpu.memory.drives().insert(0, floppy); system.cpu.reset(); // ROM 0 is the revision that first went looking for a UniDisk 3.5. try system.waitFor("\n]", 300 * second); try typeAndRun(&system); } test "an Apple III with no disk in it runs its ROM's diagnostics and asks for a retry" { const rom = try catalogued(testing.allocator, .roms, "Apple III/342-0031.bin"); defer testing.allocator.free(rom); var system = try powerOn(cpu8.CPU, memory.AppleIII(.{}), rom); // "RETRY: The disk boot failed. Either there is no diskette in the // built-in disk drive, or the diskette is unformatted, or the data on // the diskette is not that of a bootable diskette" (Apple Computer, // Inc., 1981a, p. 90). The machine's clock is 2 MHz, so its seconds // are twice the II's. try system.waitFor("RETRY", 20 * second); } test "an Apple III boots the SOS System Utilities disk in its internal drive" { const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple III/342-0031.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "Apple III/sos_13_sys_utils.dsk"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "sos_13_sys_utils.dsk"); defer opened.deinit(alloc); const floppy = try alloc.create(disk2.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data, opened.image.order() orelse return error.NibbleImage); floppy.write_protected = opened.image.write_protected; var system = try powerOn(cpu8.CPU, memory.AppleIII(.{}), rom); system.cpu.memory.disk.insert(0, floppy); // A clock chip in its socket, set to a morning in 1983, the year SOS // 1.3's utilities are dated; the year goes into the chip's RAM where // SOS keeps it, since the chip has no counter for one. system.cpu.memory.clock.fitted = true; system.cpu.memory.clock.set(.{ .year = 1983, .month = 11, .day = 17, .hour = 8, .minute = 30 }, system.cpu.clock.cycles); system.cpu.reset(); // The ROM's diagnostics take most of a second, then it reads the boot // block, SOS loads its kernel, the interpreter and the drivers, and the // interpreter — Pascal — loads the utilities themselves, sixty // kilobytes off a drive that reads about five a second. Forty seconds, // or so, on the real machine too. try system.waitFor("Apple /// Utilities", 120 * second); try system.waitFor("Main Menu", 5 * second); // A key goes to SOS on the interrupt the keyboard raises, not by being // polled for, and comes out the other side transformed by the console // driver: D, from the encoder's $44 with shift up, opens the menu it // names. try system.press('d'); try system.waitFor("Device Handling Commands Menu", 5 * second); // And T asks the clock, through SOS's GET.TIME: the counters in BCD, // the year out of the RAM latches, with the century SOS assumes. try system.press('t'); try system.waitFor("17 Nov 83", 5 * second); } test "an Apple III boots Business BASIC, takes a program at the keyboard, and runs it" { const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple III/342-0031.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "Apple III/apple_bus_basic.dsk"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "apple_bus_basic.dsk"); defer opened.deinit(alloc); const floppy = try alloc.create(disk2.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data, opened.image.order() orelse return error.NibbleImage); floppy.write_protected = opened.image.write_protected; var system = try powerOn(cpu8.CPU, memory.AppleIII(.{}), rom); system.cpu.memory.disk.insert(0, floppy); system.cpu.reset(); // SOS loads Business BASIC as its interpreter, and BASIC runs the disk's // HELLO program: a banner and a catalog, whose last line is the room // left. Only then is the `)` prompt waiting for a line, and a key typed // before that is taken by the program rather than the prompt. try system.waitFor("BLOCKS FREE", 120 * second); try system.waitFor("\n)", 10 * second); try typeAndRun(&system); } test "an Apple III runs Apple's Apple II emulation, boots a DOS 3.3 disk in it, and runs a program in Applesoft" { const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple III/342-0031.bin"); defer alloc.free(rom); const emulation = try catalogued(alloc, .disks, "Apple III/apple_emulation.dsk"); defer alloc.free(emulation); const opened = try diskfile.open(alloc, emulation, "apple_emulation.dsk"); defer opened.deinit(alloc); const floppy = try alloc.create(disk2.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data, opened.image.order() orelse return error.NibbleImage); // A DOS 3.3 disk whose HELLO leaves the prompt: Logo's sample programs. const dos = try catalogued(alloc, .disks, "Apple LOGO Sample Programs.dsk"); defer alloc.free(dos); const opened2 = try diskfile.open(alloc, dos, "Apple LOGO Sample Programs.dsk"); defer opened2.deinit(alloc); const floppy2 = try alloc.create(disk2.Floppy); defer alloc.destroy(floppy2); floppy2.* = .{}; try floppy2.load(opened2.image.data, opened2.image.order() orelse return error.NibbleImage); floppy2.write_protected = true; var system = try powerOn(cpu8.CPU, memory.AppleIII(.{}), rom); system.cpu.memory.disk.insert(0, floppy); system.cpu.reset(); // The emulation disk's menu, in a font of its own. Its BOOT DISK is a // II Plus's autostart: the ROM finds the disk card's signature at $C600, // where the emulation keeps a boot routine in the RAM under the slot // windows, and boots whatever is in the drive — so the Apple II disk // goes in first, as the machine's owner was told to do. try system.waitFor("BOOT", 60 * second); system.cpu.memory.disk.insert(0, floppy2); try system.press('\r'); try system.waitFor("APPLE LOGO SAMPLE PROGRAM DISK", 60 * second); try system.waitFor("\n]", 10 * second); // DOS is up under Applesoft in an emulated 48K II Plus, and answers. try system.typeLine("CATALOG"); try system.waitFor("DISK VOLUME 254", 10 * second); // DOS stops a long catalog after a screenful and waits for a key; this // one is longer, so a key lets it finish, and the last file's name says // it has. try system.press(' '); try system.waitFor("INFO.LOGO", 10 * second); system.run(2 * second); // The disk's HELLO is still the program in memory, and its lines would // run alongside the three typed over them; NEW clears it, and TEXT the // window it left. try system.typeLine("NEW"); try system.typeLine("TEXT"); try typeAndRun(&system); } test "an Apple III catalogs a ProFile from Business BASIC" { const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple III/342-0031.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "Apple III/apple_bus_basic.dsk"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "apple_bus_basic.dsk"); defer opened.deinit(alloc); const floppy = try alloc.create(disk2.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data, opened.image.order() orelse return error.NibbleImage); // A ProFile with an empty SOS volume on it, laid out as the utilities' // Format would lay it: the volume directory in blocks 2 to 5, headed by // its name, the directory's shape and the size of the volume, and the // bitmap from block 6, with the nine blocks so far taken marked used. // SOS's file system is ProDOS's, which was written to read SOS disks. const image = try alloc.alloc(u8, profile.blocks * blockdevice.block_size); defer alloc.free(image); @memset(image, 0); const bs = blockdevice.block_size; const directory = image[2 * bs ..][0..bs]; directory[2] = 3; // next block const name = "PROFILE"; directory[4] = 0xf0 | @as(u8, name.len); @memcpy(directory[5..][0..name.len], name); directory[0x22] = 0xc3; // access: destroy, rename, write, read directory[0x23] = 0x27; // entry length directory[0x24] = 0x0d; // entries per block directory[0x27] = 6; // bitmap pointer directory[0x29] = @truncate(profile.blocks); directory[0x2a] = @truncate(profile.blocks >> 8); for (3..6) |b| { const block = image[b * bs ..][0..bs]; block[0] = @intCast(b - 1); block[2] = if (b < 5) @intCast(b + 1) else 0; } const bitmap = image[6 * bs ..]; @memset(bitmap[0 .. profile.blocks / 8], 0xff); bitmap[0] = 0x00; // blocks 0 to 7 bitmap[1] = 0x7f; // block 8 var volume: blockdevice.Volume = .{ .image = image, .write_protected = false }; var system = try powerOn(cpu8.CPU, memory.AppleIII(.{}), rom); system.cpu.memory.disk.insert(0, floppy); system.cpu.memory.insertVolume(0, &volume); system.cpu.reset(); try system.waitFor("BLOCKS FREE", 120 * second); try system.waitFor("\n)", 10 * second); // .PROFILE is the driver's name for it, in slot 4 where the driver on // this disk expects the card; the driver reads block 2 and the bitmap // through the card's pseudo-DMA, and BASIC totals what it finds. try system.typeLine("CATALOG .PROFILE"); try system.waitFor("BLOCKS FREE: 9719", 20 * second); try system.expect("PROFILE"); // And the other way down the cable: a text file written to it takes a // block of the volume, and the directory and bitmap are written back. try system.typeLine("OPEN#1 AS OUTPUT,\".PROFILE/NOTE\""); try system.typeLine("PRINT#1;\"A NOTE ON THE HARD DISK\""); try system.typeLine("CLOSE#1"); try system.typeLine("CATALOG .PROFILE"); try system.waitFor("BLOCKS FREE: 9718", 20 * second); try system.expect("NOTE"); try testing.expect(volume.dirty); } test "an Apple II comes up in the Monitor, is sent into Integer BASIC, takes a program at the keyboard, and runs it" { const rom = try catalogued(testing.allocator, .roms, "apple2o.rom"); defer testing.allocator.free(rom); var system = try powerOn(cpu8.CPU, memory.AppleII(.{}), rom); // The old Monitor has no autostart: reset is its `*` prompt, and Integer // BASIC is entered from it by hand. try system.waitFor("\n*", second); try system.typeLine("E000G"); try system.waitFor("\n>", second); try typeAndRun(&system); } test "an Apple-1 loads BASIC from tape through the Cassette Interface, takes a program at the keyboard, and runs it" { const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "wozmon.bin"); defer alloc.free(rom); const card = try catalogued(alloc, .roms, "aci.rom"); defer alloc.free(card); const wav = try catalogued(alloc, .disks, "apple1-basic.wav"); defer alloc.free(wav); // The tape as the card's comparator sees it: which side of zero each // sample is on. The file is what the catalogue says it is, 16-bit mono // with its samples from byte 44. try testing.expectEqualStrings("data", wav[36..40]); const rate = std.mem.readInt(u32, wav[24..28], .little); const levels = try alloc.alloc(u8, (wav.len - 44) / 2); defer alloc.free(levels); for (levels, 0..) |*level, i| { level.* = @intFromBool(std.mem.readInt(i16, wav[44 + 2 * i ..][0..2], .little) > 0); } var system: EightBit(cpu8.CPU, memory.AppleI(.{})) = .{ .cpu = undefined, .alloc = alloc }; try system.cpu.init(null, null); try system.cpu.memory.loadROMAtEnd(rom); try system.cpu.memory.fitMemory(0x2000); try system.cpu.memory.fitCassetteInterface(card); system.cpu.reset(); // Press play, enter the card's program, and ask it for the second bank. system.cpu.memory.playTape(levels, rate); try system.waitFor("\n\\", second); try system.typeLine("C100R"); try system.waitFor("*", second); try system.typeLine("E000.EFFFR"); // The whole tape: two seconds of leader, ten of header and twenty-six of // data, after which the program returns to the Monitor's backslash. const tape_length = @as(u64, levels.len) * second / rate; system.run(tape_length); try system.typeLine("E000R"); try system.waitFor("\n>", second); try typeAndRun(&system); } test "an Apple IIgs boots a ProDOS disk into Applesoft, takes a program at the keyboard, and runs it" { const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIGS ROM 01 - 342-0077-B.bin"); defer alloc.free(rom); // Apple's 1983 examples disk: ProDOS, BASIC.SYSTEM and a STARTUP program // that describes the machine it finds itself on and leaves the prompt. const file = try catalogued(alloc, .disks, "ProDOS BASIC Programming Examples - 680-0235-A.dsk"); defer alloc.free(file); // Into the 5.25-inch drive on the disk port, nibblized the way a head // would find it, with the sector order the file's name gives. const opened = try diskfile.open(alloc, file, "examples.dsk"); defer opened.deinit(alloc); const floppy = try alloc.create(disk2.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data, opened.image.order() orelse return error.NibbleImage); floppy.write_protected = opened.image.write_protected; const CPU = cpu16.Chip(.{}, clock.FakeClock, memory16.AppleIIgs(.{})); var system: System(CPU, .mega2) = .{ .cpu = undefined, .alloc = alloc }; try system.cpu.init(alloc, null); defer system.cpu.deinit(); try system.cpu.memory.loadROM(rom); system.cpu.memory.iwm.drives.insert(0, floppy); // The clock chip has a time in it, as one with a battery does; the // front end sets it from the host, and this sets it to a moment in 1987 // so that a test does not depend on the day it is run. system.cpu.memory.rtc.set(rtc.Rtc.epoch_1904 + 536_457_600, 0); // 1987-01-01 00:00:00 UTC system.cpu.reset(); // The firmware tests its memory, finds the disk in slot 6, and hands over // to the boot PROM with the machine slowed to 1.024 MHz by the Speed // register's motor-on detector, without which the software written for // a Disk II reads nothing. ProDOS then finds itself on a IIgs and says // what it finds, which takes a while. // BASIC.SYSTEM shows its prompt once before it has loaded STARTUP off // the disk, so the prompt to wait for is the one after the report. try system.waitFor("SLOT 7: USED", 300 * gs_second); try system.waitFor("\n]", 30 * gs_second); try typeAndRun(&system); } test "an Apple IIgs boots an 800K disk from its 3.5-inch drive" { const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIGS ROM 01 - 342-0077-B.bin"); defer alloc.free(rom); // The 800K System Disk, which is what a 3.5-inch drive was sold to read. const file = try catalogued(alloc, .disks, "Apple II System Disk 3.2 on 800k image.2mg"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "system.2mg"); defer opened.deinit(alloc); const floppy = try alloc.create(disk35.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data); floppy.write_protected = opened.image.write_protected; const CPU = cpu16.Chip(.{}, clock.FakeClock, memory16.AppleIIgs(.{})); var system: System(CPU, .mega2) = .{ .cpu = undefined, .alloc = alloc }; try system.cpu.init(alloc, null); defer system.cpu.deinit(); try system.cpu.memory.loadROM(rom); system.cpu.memory.iwm.disks35.insert(0, floppy); system.cpu.memory.rtc.set(rtc.Rtc.epoch_1904 + 536_457_600, 0); // 1987-01-01 system.cpu.reset(); // This disk starts the System Utilities rather than BASIC, so what says it // booted is that program's own menu — text that is nowhere in the ROM and // can only have come off the disk, through the 3.5-inch drive. try system.waitFor("FastCopy", 300 * gs_second); try system.waitFor("Copyright Apple Computer, Inc. 1987-90", 60 * gs_second); } test "an Apple IIgs boots the System Disk from an Apple II SCSI Card in slot 7" { const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIGS ROM 01 - 342-0077-B.bin"); defer alloc.free(rom); // The Apple II SCSI Card's firmware, which is the dominant mass-storage // card a IIgs was sold with, driving the same 800K System Disk the // 3.5-inch test boots -- here as a hard disk image on the SCSI chain. const firmware = try catalogued(alloc, .roms, "341-0437-a.bin"); defer alloc.free(firmware); const file = try catalogued(alloc, .disks, "Apple II System Disk 3.2 on 800k image.2mg"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "system.2mg"); defer opened.deinit(alloc); // The card borrows the image, so it has to outlive the machine. const image = try alloc.dupe(u8, opened.image.data); defer alloc.free(image); const CPU = cpu16.Chip(.{}, clock.FakeClock, memory16.AppleIIgs(.{})); var system: System(CPU, .mega2) = .{ .cpu = undefined, .alloc = alloc }; try system.cpu.init(alloc, null); defer system.cpu.deinit(); try system.cpu.memory.loadROM(rom); try system.cpu.memory.fitScsi(7, firmware); // The disk answers to identity six, one below the card's own seven. try system.cpu.memory.scsiCard(7).?.attach(6, image, opened.image.write_protected); system.cpu.memory.rtc.set(rtc.Rtc.epoch_1904 + 536_457_600, 0); // 1987-01-01 system.cpu.reset(); // The same proof as the 3.5-inch boot: the System Utilities' own menu, // text that is nowhere in the ROM and can only have come off the disk -- // this time a block at a time through the card and its NCR 5380. try system.waitFor("FastCopy", 300 * gs_second); try system.waitFor("Copyright Apple Computer, Inc. 1987-90", 60 * gs_second); } test "an Apple IIgs writes a file to its 3.5-inch disk and it is really there" { // Every other 3.5-inch test only reads. This one makes the machine put // something down: the whole chain, from Applesoft tokenising a line, to // ProDOS writing blocks, to the drive laying nibbles on the surface, and // back again through `save` into an image the filesystem can be read from. // What proves it is not the machine's own CATALOG — that is the machine // vouching for itself — but finding the file, and its bytes, in the image // the surface renders back to. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIGS ROM 01 - 342-0077-B.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "Apple II System Disk 3.2 on 800k image.2mg"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "system.2mg"); defer opened.deinit(alloc); const floppy = try alloc.create(disk35.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data); // The shutter open, deliberately: a `Floppy` comes up write protected, and // this is the one test that wants it otherwise. floppy.write_protected = false; const CPU = cpu16.Chip(.{}, clock.FakeClock, memory16.AppleIIgs(.{})); var system: System(CPU, .mega2) = .{ .cpu = undefined, .alloc = alloc }; try system.cpu.init(alloc, null); defer system.cpu.deinit(); try system.cpu.memory.loadROM(rom); system.cpu.memory.iwm.disks35.insert(0, floppy); system.cpu.memory.rtc.set(rtc.Rtc.epoch_1904 + 536_457_600, 0); // 1987-01-01 system.cpu.reset(); // Boot, leave the Utilities for BASIC, and save a program to the volume // the machine booted from. try system.waitFor("FastCopy", 300 * gs_second); try system.typeLine("3"); try system.waitFor("PRODOS BASIC", 60 * gs_second); try system.typeLine("10 PRINT \"ZIG65\""); try system.typeLine("SAVE WRITETEST"); system.run(60 * gs_second); // The drive was actually written to, rather than the write being swallowed. try testing.expect(floppy.dirty); try testing.expect(system.cpu.memory.iwm.disks35.written > 0); // The surface rendered back to an image, sector by sector, reading round // each track for the marks — which is the path that only matters when the // machine wrote them rather than `load` laying them out. const rendered = try alloc.alloc(u8, disk35.image_size); defer alloc.free(rendered); @memcpy(rendered, opened.image.data[0..disk35.image_size]); try floppy.save(rendered); const volume = try prodos.Volume.open(rendered); var name_buffer: [prodos.name_length]u8 = undefined; var path_buffer: [64]u8 = undefined; const path = try std.fmt.bufPrint(&path_buffer, "/{s}/WRITETEST", .{volume.name(&name_buffer)}); // What was on the disk before is still on it: writing a file put nibbles // down in one sector's slot and must not have trodden on its neighbours, // nor on the zoned layout that gives each track its own sector count. var kept_buffer: [64]u8 = undefined; const kept = try std.fmt.bufPrint(&kept_buffer, "/{s}/BASIC.SYSTEM", .{volume.name(&name_buffer)}); try testing.expect(volume.find(kept) != null); const entry = volume.find(path) orelse return error.TheFileIsNotOnTheDisk; try testing.expectEqualStrings("WRITETEST", entry.name()); try testing.expectEqual(prodos.FileType.applesoft, entry.kind); // And the bytes are the program as Applesoft tokenises it: the link to // where a second line would start, line ten, the PRINT token, the string // in its quotes, the end of the line and the two zeros that end the // program. Neither `WRITETEST` nor `ZIG65` occurs anywhere in the ROM or // in the disk image as it was handed in, in either the high-bit-set form // an Apple stores text in or the plain one, so nothing but the machine // writing them could have put them here. var contents: std.Io.Writer.Allocating = .init(alloc); defer contents.deinit(); try volume.read(path, &contents.writer); const tokenised = [_]u8{ 0x0e, 0x08 } ++ [_]u8{ 0x0a, 0x00 } ++ [_]u8{0xba} ++ "\x22ZIG65\x22".* ++ [_]u8{ 0x00, 0x00, 0x00 }; try testing.expectEqualSlices(u8, &tokenised, contents.written()); } test "an Apple IIgs writes a file to a disk that came out of a ShrinkIt archive, and it is saved back into the archive" { // A disk out of a `.SDK` used to be read only, because putting it back // meant writing a ShrinkIt archive. Now it goes home: the machine writes a // file, the eject flush re-archives, and the file is found in the disk // inside the archive the next time it is opened. The whole chain runs -- // unpack, boot, write, save the surface, re-archive, unpack again -- and // what proves it is the file being on the disk that comes back out, not // the machine's own CATALOG. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIGS ROM 01 - 342-0077-B.bin"); defer alloc.free(rom); const source_file = try catalogued(alloc, .disks, "Apple II System Disk 3.2 on 800k image.2mg"); defer alloc.free(source_file); // Build a single-record `.SDK` around the 800K ProDOS disk -- a stored, // uncompressed thread, the same shape `reArchive` writes -- and put it in // a scratch file so the write-back can re-read it the way a session does. const dir = testing.environ.getPosix("TMPDIR") orelse "/tmp"; const path = try std.fmt.allocPrint(alloc, "{s}/zig65-shrinkit-writeback.sdk", .{dir}); defer { std.Io.Dir.cwd().deleteFile(testing.io, path) catch {}; alloc.free(path); } { const source = try diskfile.open(alloc, source_file, "system.2mg"); defer source.deinit(alloc); const sdk = try shrinkit.writer.diskAlloc(alloc, .{ .name = "SYSTEM", .data = source.image.data }, .{}); defer alloc.free(sdk); try std.Io.Dir.cwd().writeFile(testing.io, .{ .sub_path = path, .data = sdk }); } // Open the archive as the front ends do: the disk unpacked into its own // buffer, `owned` set, which is what the write-back keys on. const back_in = try std.Io.Dir.cwd().readFileAlloc(testing.io, path, alloc, .limited(writeback.file_limit)); defer alloc.free(back_in); const opened = try diskfile.open(alloc, back_in, path); defer opened.deinit(alloc); try testing.expect(opened.owned != null); const floppy = try alloc.create(disk35.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data); floppy.write_protected = false; const CPU = cpu16.Chip(.{}, clock.FakeClock, memory16.AppleIIgs(.{})); var system: System(CPU, .mega2) = .{ .cpu = undefined, .alloc = alloc }; try system.cpu.init(alloc, null); defer system.cpu.deinit(); try system.cpu.memory.loadROM(rom); system.cpu.memory.iwm.disks35.insert(0, floppy); system.cpu.memory.rtc.set(rtc.Rtc.epoch_1904 + 536_457_600, 0); // 1987-01-01 system.cpu.reset(); try system.waitFor("FastCopy", 300 * gs_second); try system.typeLine("3"); try system.waitFor("PRODOS BASIC", 60 * gs_second); try system.typeLine("10 PRINT \"ZIG65\""); try system.typeLine("SAVE WRITETEST"); system.run(60 * gs_second); try testing.expect(floppy.dirty); try testing.expect(system.cpu.memory.iwm.disks35.written > 0); // The eject/stop flush, exactly: the surface saved back through the // write-back, which re-reads the `.SDK`, stamps the drive's blocks into it, // and rebuilds the archive around them. try writeback.floppy35(testing.io, alloc, path, floppy); // What is on disk now is still a NuFX archive a reader takes, and the disk // that comes out of it has the file the machine wrote. const back_out = try std.Io.Dir.cwd().readFileAlloc(testing.io, path, alloc, .limited(writeback.file_limit)); defer alloc.free(back_out); _ = try shrinkit.nufx.open(back_out); const reopened = try diskfile.open(alloc, back_out, path); defer reopened.deinit(alloc); const volume = try prodos.Volume.open(reopened.image.data); var name_buffer: [prodos.name_length]u8 = undefined; var path_buffer: [64]u8 = undefined; const written_path = try std.fmt.bufPrint(&path_buffer, "/{s}/WRITETEST", .{volume.name(&name_buffer)}); const entry = volume.find(written_path) orelse return error.TheFileIsNotInTheArchive; try testing.expectEqualStrings("WRITETEST", entry.name()); try testing.expectEqual(prodos.FileType.applesoft, entry.kind); var contents: std.Io.Writer.Allocating = .init(alloc); defer contents.deinit(); try volume.read(written_path, &contents.writer); const tokenised = [_]u8{ 0x0e, 0x08 } ++ [_]u8{ 0x0a, 0x00 } ++ [_]u8{0xba} ++ "\x22ZIG65\x22".* ++ [_]u8{ 0x00, 0x00, 0x00 }; try testing.expectEqualSlices(u8, &tokenised, contents.written()); } test "an Apple IIc Plus runs its firmware instead of falling into the Monitor" { const alloc = testing.allocator; // ROM 5, the IIc Plus: the one machine of the family with the multidrive // interface glue in it. Its firmware leaves $ce00 empty for that chip and // builds the vector it jumps through at $e489 in the chip's RAM, so // without the glue the vector reads as zeros, the machine jumps to $0000 // and sits there in the Monitor. See `mig.zig`. const rom = try catalogued(alloc, .roms, "Apple IIc ROM 05 - IIc Plus.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "ProDOS BASIC Programming Examples - 680-0235-A.dsk"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "examples.dsk"); defer opened.deinit(alloc); const floppy = try alloc.create(disk2.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data, opened.image.order() orelse return error.NibbleImage); var system = try powerOn(cpu8.CMOS, memory.AppleIIc(.{}), rom); // The version byte is what says this machine has the chip at all. try testing.expect(system.cpu.memory.mig_fitted); system.cpu.memory.drives().insert(0, floppy); system.cpu.reset(); system.run(60 * second); // It is past the vector: the firmware is running its own code rather than // BRK-ing its way down from $0000. try testing.expect(system.cpu.program_counter.value >= 0xc000); // And it is using the buffer to do it, which is what says the chip is // carrying the machine rather than merely answering. var written: usize = 0; for (system.cpu.memory.mig.ram) |byte| { if (byte != 0) written += 1; } try testing.expect(written > 0); } test "an Apple IIc Plus boots its internal 3.5-inch drive to the System Utilities" { const alloc = testing.allocator; // ROM 5 talks to the drive built into the case as a 3.5-inch drive: the // phase lines stop being magnets and become an address, with SEL for a // fourth bit, and SEL is the MIG's on this machine (Apple Computer, Inc., // 1989b, Table 11-15, p. 328). Reading a sector then runs through the // chip's buffer, which is what it is there for — "a RAM buffer to support // the high data rate of the 3.5-inch disk drives" (p. 327). const rom = try catalogued(alloc, .roms, "Apple IIc ROM 05 - IIc Plus.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "Apple II System Disk 3.2 on 800k image.2mg"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "system.2mg"); defer opened.deinit(alloc); const floppy = try alloc.create(disk35.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data); var system = try powerOn(cpu8.CMOS, memory.AppleIIc(.{}), rom); system.cpu.memory.disk.disks35.insert(0, floppy); system.cpu.reset(); // It reads the disk and runs what it finds there, all the way to the // program the disk starts: ProDOS loads off the 3.5-inch drive, and the // System Utilities put up their own menu. None of that text is in the // ROM — not "PRODOS 8", not "FastCopy", not either copyright — so it can // only have been read off the disk through the drive and executed. It is // the same place the IIgs reaches from the same image. try system.waitFor("PRODOS 8", 120 * second); try system.expect("COPYRIGHT APPLE COMPUTER, INC., 1983-90"); try system.waitFor("FastCopy", 300 * second); // The menu is still being drawn when its title appears, so the last thing // on it is waited for rather than expected on the spot. try system.waitFor("Copyright Apple Computer, Inc. 1987-90", 120 * second); // And it got there by working the drive. const drives35 = &system.cpu.memory.disk.disks35; try testing.expect(drives35.commanded > 0); try testing.expect(drives35.drives[0].spindle); } test "an Apple IIc Plus boots the 3.5-inch drive on the back rather than the one in the case" { // The other axis of the disk port: not which *kind* of drive, but // *whose*. A IIc Plus lists four places it will start from, and two of // them are 3.5-inch drives that differ only in where they are — "internal // 3.5-inch drive at $C500 (port 5, drive 1)" and "external UniDisk 3.5 or // Apple 3.5 drive at $C500 (port 5, drive 2)" (Apple Computer, Inc., // 1989b, p. 86). // // That difference is the IWM's own pair of enable lines rather than // anything the glue latches. The MIG carries `INTEN*`, a "latched output // bit to enable internal drive", against `ENB2`, which "follows EN2X* or // ROMEN1* if addressing mapped device space to select external drives" // (Table 11-15, p. 328) — one enable each, the second of them the IWM's // ENABLE2 qualified by the address decode so that it is driven only // during an access that is really the port's. So the drive on the back is // reached by selecting drive two, and nothing else about the port // changes. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIc ROM 05 - IIc Plus.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "Apple II System Disk 3.2 on 800k image.2mg"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "system.2mg"); defer opened.deinit(alloc); const floppy = try alloc.create(disk35.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data); var system = try powerOn(cpu8.CMOS, memory.AppleIIc(.{}), rom); // Drive two, and only drive two. The drive in the case is left empty on // purpose: it is the control, and it is what makes this test say anything // the one above does not. If the port ignored the drive select and always // reached the internal drive, there would be no disk there to read and // the machine would sit waiting for one. system.cpu.memory.disk.disks35.insert(1, floppy); system.cpu.reset(); // Same destination as the internal test, by a different door: ProDOS off // the disk, then the System Utilities' own menu. None of that text is in // the ROM — not "PRODOS 8", not "FastCopy", not the copyright — so it // came off the disk, and the only disk is the one on the back. try system.waitFor("PRODOS 8", 120 * second); try system.expect("COPYRIGHT APPLE COMPUTER, INC., 1983-90"); try system.waitFor("FastCopy", 300 * second); // And the drive that turned is the outside one, while the empty drive in // the case holds nothing to have read. const drives35 = &system.cpu.memory.disk.disks35; try testing.expect(drives35.commanded > 0); try testing.expect(drives35.drives[1].spindle); try testing.expect(drives35.drives[0].floppy == null); } test "an Apple IIc Plus writes a file to its 3.5-inch disk and it is really there" { // The IIgs has been made to write to a 3.5-inch disk and have it stick; // this is the same proof for the other machine that drives one, and it is // a different path to the same surface. A IIgs reaches the drive through // its own IWM and takes SEL from bit seven of `$c031`. A IIc Plus has no // such register: SEL is the glue chip's, and every sector on its way to // or from the drive goes through the two kilobytes of static RAM beside // it — "a RAM buffer to support the high data rate of the 3.5-inch disk // drives" (Apple Computer, Inc., 1989b, p. 327). Reading proves the // buffer carries bytes one way; only writing proves it carries them back. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIc ROM 05 - IIc Plus.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "Apple II System Disk 3.2 on 800k image.2mg"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "system.2mg"); defer opened.deinit(alloc); const floppy = try alloc.create(disk35.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data); // The shutter open, deliberately: a `Floppy` comes up write protected. floppy.write_protected = false; var system = try powerOn(cpu8.CMOS, memory.AppleIIc(.{}), rom); system.cpu.memory.disk.disks35.insert(0, floppy); system.cpu.reset(); // Boot, leave the Utilities for BASIC, and save a program to the volume // the machine booted from. try system.waitFor("FastCopy", 300 * second); try system.typeLine("3"); try system.waitFor("PRODOS BASIC", 60 * second); try system.typeLine("10 PRINT \"ZIG65\""); try system.typeLine("SAVE IICWRITE"); system.run(60 * second); // The drive was worked and the surface really changed. try testing.expect(floppy.dirty); try testing.expect(system.cpu.memory.disk.disks35.written > 0); // The surface rendered back to an image, sector by sector, reading round // each track for the marks the machine itself laid down. const rendered = try alloc.alloc(u8, disk35.image_size); defer alloc.free(rendered); @memcpy(rendered, opened.image.data[0..disk35.image_size]); try floppy.save(rendered); const volume = try prodos.Volume.open(rendered); var name_buffer: [prodos.name_length]u8 = undefined; var path_buffer: [64]u8 = undefined; const path = try std.fmt.bufPrint(&path_buffer, "/{s}/IICWRITE", .{volume.name(&name_buffer)}); // What was on the disk before is still on it. var kept_buffer: [64]u8 = undefined; const kept = try std.fmt.bufPrint(&kept_buffer, "/{s}/BASIC.SYSTEM", .{volume.name(&name_buffer)}); try testing.expect(volume.find(kept) != null); const entry = volume.find(path) orelse return error.TheFileIsNotOnTheDisk; try testing.expectEqualStrings("IICWRITE", entry.name()); try testing.expectEqual(prodos.FileType.applesoft, entry.kind); // And the bytes are the program as Applesoft tokenises it. Neither // `IICWRITE` nor `ZIG65` occurs anywhere in this ROM or in the disk image // as it was handed in, in either the high-bit-set form an Apple stores // text in or the plain one, so nothing but the machine writing them // through the glue chip's buffer could have put them here. var contents: std.Io.Writer.Allocating = .init(alloc); defer contents.deinit(); try volume.read(path, &contents.writer); const tokenised = [_]u8{ 0x0e, 0x08 } ++ [_]u8{ 0x0a, 0x00 } ++ [_]u8{0xba} ++ "\x22ZIG65\x22".* ++ [_]u8{ 0x00, 0x00, 0x00 }; try testing.expectEqualSlices(u8, &tokenised, contents.written()); } test "an Apple IIgs formats a blank 3.5-inch disk and what it lays down is a volume" { // The last unexercised corner of the 3.5-inch path. Writing a file rewrites // one sector of a disk somebody else formatted; this lays every track down // from nothing — eighty of them, both sides, through all five zones, each // with its own sector count — and then reads the result back as a // filesystem. Nothing about the surface is given to the machine here: the // blank is unrecorded, and every address field, data field and checksum on // it is one the emulated drive wrote. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIGS ROM 01 - 342-0077-B.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "Apple II System Disk 3.2 on 800k image.2mg"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "system.2mg"); defer opened.deinit(alloc); const floppy = try alloc.create(disk35.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data); // The boot disk goes in unprotected on purpose. It is the control: if the // drive select went astray and the machine formatted the disk it booted // from, nothing would stop it, and the checks at the end would find the // volume gone. floppy.write_protected = false; // And the blank: not an image loaded from anywhere, but an unrecorded // surface, with no address mark anywhere on it. // // What that reads as is noise — the head hears the amplifier, the same as // it does between two tracks on a five-and-a-quarter disk, which is what // `fakeBit` makes there on the WOZ reference's authority (Morris, 2018). // It used to be filled with `$ff` here and called self-sync, and that was // wrong twice over: self-sync is what the *gaps on a formatted disk* hold, // and a blank that hands out `$ff` for ever gives a firmware hunting an // address mark nothing to give up on. A IIgs copes either way. A IIc Plus // does not, and would not format such a disk at all. const blank = try alloc.create(disk35.Floppy); defer alloc.destroy(blank); blank.* = .{}; var noise: u32 = 0x2545f491; for (&blank.nibbles) |*byte| { noise = noise *% 1664525 +% 1013904223; byte.* = @truncate(noise >> 16); } blank.write_protected = false; const CPU = cpu16.Chip(.{}, clock.FakeClock, memory16.AppleIIgs(.{})); var system: System(CPU, .mega2) = .{ .cpu = undefined, .alloc = alloc }; try system.cpu.init(alloc, null); defer system.cpu.deinit(); try system.cpu.memory.loadROM(rom); system.cpu.memory.iwm.disks35.insert(0, floppy); system.cpu.memory.iwm.disks35.insert(1, blank); system.cpu.memory.rtc.set(rtc.Rtc.epoch_1904 + 536_457_600, 0); // 1987-01-01 system.cpu.reset(); // Boot the System Disk and take its Utilities to Format a Disk, which is // three items down the first menu. try system.waitFor("FastCopy", 300 * gs_second); try system.typeLine("1"); system.run(60 * gs_second); try system.press(0x0a); try system.press(0x0a); try system.press(0x0a); try system.press('\r'); // Where the disk is. The Slot and Drive fields are not drawn until this // screen is accepted, so the RETURN that draws them comes first; then U // moves to the Drive field and a digit sets it. Drive 2 is the blank. try system.waitFor("Where is your disk?", 60 * gs_second); try system.press('\r'); try system.waitFor("Slot:", 60 * gs_second); try system.press(0x15); try system.press('2'); system.run(2 * gs_second); try system.expect("Drive: 2"); try system.press('\r'); try system.waitFor("Select the Operating System", 60 * gs_second); try system.press('\r'); // ProDOS, the first of the two. // The name field comes up holding the booted volume's name, so it is // cleared before the new one is typed. A name of its own is what makes the // volume found at the end unmistakably this one and not the disk in the // other drive. try system.waitFor("Enter volume name", 60 * gs_second); for (0..prodos.name_length) |_| try system.press(0x7f); try system.typeLine("BLANKDISK"); // The drive ejects the disk to ask for the one to be written, which is the // drive's own eject line and not the program being polite: the surface is // out of the machine at this point and has to be put back. try system.waitFor("Please Place Destination Disk", 60 * gs_second); try testing.expect(system.cpu.memory.iwm.disks35.drives[1].floppy == null); system.cpu.memory.iwm.disks35.insert(1, blank); try system.press('\r'); try system.waitFor("Formatting Complete", 300 * gs_second); // Something really went down onto the surface. try testing.expect(blank.dirty); try testing.expect(system.cpu.memory.iwm.disks35.written > 0); // Now read the surface back as an image. The buffer is handed in full of a // byte no sector of a fresh ProDOS volume holds, and `save` leaves a sector // it could not find exactly as it was given — so a block still full of it // is a block the machine never laid down. Checking every one of them is // what covers the zones: the five of them give the eighty tracks four // different sector counts, and a track written to the wrong count would // leave its tail unreadable here. const sentinel = 0xe5; const rendered = try alloc.alloc(u8, disk35.image_size); defer alloc.free(rendered); @memset(rendered, sentinel); try blank.save(rendered); var missing: usize = 0; var first_missing: usize = 0; var block: usize = 0; while (block * prodos.block_size < rendered.len) : (block += 1) { const contents = rendered[block * prodos.block_size ..][0..prodos.block_size]; if (std.mem.allEqual(u8, contents, sentinel)) { if (missing == 0) first_missing = block; missing += 1; } } if (missing != 0) { std.debug.print("{d} of {d} blocks were never written, from block {d}\n", .{ missing, rendered.len / prodos.block_size, first_missing, }); std.debug.print(" first missing: ", .{}); var shown: usize = 0; var b: usize = 0; while (b * prodos.block_size < rendered.len and shown < 24) : (b += 1) { if (std.mem.allEqual(u8, rendered[b * prodos.block_size ..][0..prodos.block_size], sentinel)) { std.debug.print("{d} ", .{b}); shown += 1; } } std.debug.print("\n", .{}); return error.TheMachineLeftPartOfTheDiskUnformatted; } // And what it laid down is a ProDOS volume: the name that was typed, the // whole eight hundred kilobytes of it, and a directory that reads. const volume = try prodos.Volume.open(rendered); var name_buffer: [prodos.name_length]u8 = undefined; try testing.expectEqualStrings("BLANKDISK", volume.name(&name_buffer)); try testing.expectEqual(@as(u16, 1600), volume.blocks()); try testing.expect(volume.freeBlocks() > 1500); // The disk in the other drive is untouched: it was writable throughout, so // this is the check that the machine formatted the disk it was told to. const kept = try alloc.alloc(u8, disk35.image_size); defer alloc.free(kept); @memcpy(kept, opened.image.data[0..disk35.image_size]); try floppy.save(kept); const booted = try prodos.Volume.open(kept); var booted_name: [prodos.name_length]u8 = undefined; var path_buffer: [64]u8 = undefined; const path = try std.fmt.bufPrint(&path_buffer, "/{s}/BASIC.SYSTEM", .{booted.name(&booted_name)}); try testing.expect(booted.find(path) != null); } test "an Apple IIgs reads back through the drive a disk it formatted itself" { // The format test proves what went onto the surface by rendering it with // `save` and reading the image. That is the emulator checking its own // work. This is the loop closed the other way: the machine formats a // blank, and then reads those same tracks back *through the drive* — it // catalogs the volume it made, writes a program onto it, forgets the // program, and loads it back off the disk and runs it. // // The boot disk is write protected here, so the only surface anything can // be written to is the one the machine formatted. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIGS ROM 01 - 342-0077-B.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "Apple II System Disk 3.2 on 800k image.2mg"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "system.2mg"); defer opened.deinit(alloc); const floppy = try alloc.create(disk35.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data); // Nothing on it: no address mark anywhere, and the amplifier's own noise // where a recorded surface would have flux, which is how a disk that has // never been formatted reads. See the test above for why that is noise // rather than a run of ones. const blank = try alloc.create(disk35.Floppy); defer alloc.destroy(blank); blank.* = .{}; var noise: u32 = 0x2545f491; for (&blank.nibbles) |*byte| { noise = noise *% 1664525 +% 1013904223; byte.* = @truncate(noise >> 16); } blank.write_protected = false; const CPU = cpu16.Chip(.{}, clock.FakeClock, memory16.AppleIIgs(.{})); var system: System(CPU, .mega2) = .{ .cpu = undefined, .alloc = alloc }; try system.cpu.init(alloc, null); defer system.cpu.deinit(); try system.cpu.memory.loadROM(rom); system.cpu.memory.iwm.disks35.insert(0, floppy); system.cpu.memory.iwm.disks35.insert(1, blank); system.cpu.memory.rtc.set(rtc.Rtc.epoch_1904 + 536_457_600, 0); // 1987-01-01 system.cpu.reset(); // Format the blank in drive two, the same way a person would: the // Utilities, three items down to Format a Disk, the drive field set to // two, ProDOS, and a name of its own typed over the one it offers. try system.waitFor("FastCopy", 300 * gs_second); try system.typeLine("1"); system.run(60 * gs_second); try system.press(0x0a); try system.press(0x0a); try system.press(0x0a); try system.press('\r'); try system.waitFor("Where is your disk?", 60 * gs_second); try system.press('\r'); try system.waitFor("Slot:", 60 * gs_second); try system.press(0x15); try system.press('2'); system.run(2 * gs_second); try system.expect("Drive: 2"); try system.press('\r'); try system.waitFor("Select the Operating System", 60 * gs_second); try system.press('\r'); try system.waitFor("Enter volume name", 60 * gs_second); for (0..prodos.name_length) |_| try system.press(0x7f); try system.typeLine("BLANKDISK"); // The drive puts the disk out to ask for the one to be written on, so it // has to go back in before there is anything to format. try system.waitFor("Please Place Destination Disk", 60 * gs_second); try testing.expect(system.cpu.memory.iwm.disks35.drives[1].floppy == null); system.cpu.memory.iwm.disks35.insert(1, blank); try system.press('\r'); try system.waitFor("Formatting Complete", 300 * gs_second); try testing.expect(blank.dirty); // Start the machine again and take the boot menu's way out to BASIC, // which is simpler than leaving the Utilities from inside them. system.cpu.reset(); try system.waitFor("FastCopy", 300 * gs_second); try system.typeLine("3"); try system.waitFor("PRODOS BASIC", 60 * gs_second); // The machine reads the volume it laid down: its name, and the whole // eight hundred kilobytes of it, off the surface and not out of `save`. try system.typeLine("CATALOG /BLANKDISK"); system.run(30 * gs_second); try system.expect("/BLANKDISK"); try system.expect("TOTAL BLOCKS: 1600"); // Then a program onto those tracks, forgotten, and fetched back off them. try system.typeLine("10 PRINT 8191*3"); try system.typeLine("SAVE /BLANKDISK/LOOPTEST"); system.run(60 * gs_second); try system.typeLine("NEW"); try system.typeLine("LOAD /BLANKDISK/LOOPTEST"); system.run(60 * gs_second); try system.typeLine("LIST"); system.run(10 * gs_second); try system.typeLine("RUN"); system.run(10 * gs_second); // What LIST shows is Applesoft's own rendering of the tokens it read back // — spaces around the `*` that were never typed — so it is the program // off the disk rather than the line still on the screen. And `24573` is // nowhere in what was typed at all: only running what came back prints // it, which is why the sum is there rather than a word. try system.expect(" 10 PRINT 8191 * 3"); try system.expect("24573"); } test "an Apple IIc with the 3.5 ROM finds an intelligent drive on its port and initialises it" { // The first exchange over the bus a UniDisk 3.5 is spoken to on, end to // end through the machine rather than in a unit test: Apple's firmware // frames a packet, an emulated drive takes it in, reads it, and answers, // and the firmware accepts the answer and carries on. // // Everything the handshake needs was read out of the ROM. The firmware // chooses the second connector and starts the motor, then polls the sense // line as bit seven of `$c0ee` fifty times over, giving up if it never // comes up (bank 1 `$c88e`). Having sent, it waits on that same line // *falling* before it will receive (`$c9c1`), and waits on it falling // again once the answer is in (`$cd39`), dropping REQ — which is phase // zero — immediately afterwards. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIc ROM 00 - 342-0033-A - 1985.bin"); defer alloc.free(rom); var system = try powerOn(cpu8.CMOS, memory.AppleIIc(.{}), rom); system.cpu.memory.disk.unidisk.drives[0].fitted = true; system.cpu.reset(); // Far enough to be past the startup exchange and into the ordinary // business of looking for something to boot. try system.waitFor("Apple //c", 120 * second); const drive = &system.cpu.memory.disk.unidisk.drives[0]; // One packet, taken in whole and answered. The command is `Init`, which // is what the reset code sends "to force a reset of the PC Bus". try testing.expectEqual(@as(u64, 1), drive.received); try testing.expectEqual(@as(u64, 1), drive.replied); try testing.expectEqual(unidisk.Command.init, drive.last.?); // And exactly one, because the drive answers only to its own address. The // firmware walks the chain — `Init` to unit one, then unit two, and on // until nothing answers — so a drive that replied to every address would // be an endless chain of drives. Before the address was checked this ran // to seventy-one of them. try testing.expectEqual(unidisk.State.idle, drive.state); // The exchange left the machine well: it is running its own firmware, // past the vector and out of the Monitor, rather than sitting in a // handshake that never completed. try testing.expect(system.cpu.program_counter.value >= 0xc000); } test "an Apple IIc reads blocks off a UniDisk 3.5 exactly as they lie on the disk" { // The whole chain, through the machine: Apple's firmware frames a `READ // BLOCK` packet, an emulated intelligent drive reads it, fetches the block // out of a disk image and frames five hundred and twelve bytes of it back, // and the firmware puts them where it was asked to. That the machine then // runs what it read is the test below; this one is about the bytes. // // Getting here needed the drive on the port to be reachable at all, and it // was not. A IIc "attempts to boot from the built-in disk drive. If this // fails, it attempts to boot from the first device attached to the // Protocol Converter" (Apple Computer, Inc., n.d.-b, p. 4), and the // built-in drive fails by a counter running out — `DEC $03` at bank 0 // `$c644`, which hands over to `$c500` when it reaches nought. That // counter only comes round when the read loop above it finds a byte, so a // drive that reads as silence rather than as noise holds the machine there // for ever. See `readNibble` in `disk2.zig`. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIc ROM 00 - 342-0033-A - 1985.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "Apple II System Disk 3.2 on 800k image.2mg"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "system.2mg"); defer opened.deinit(alloc); var system = try powerOn(cpu8.CMOS, memory.AppleIIc(.{}), rom); system.cpu.memory.disk.unidisk.drives[0].fitted = true; system.cpu.memory.disk.unidisk.drives[0].blocks = opened.image.data[0 .. 1600 * 512]; system.cpu.reset(); // Only as far as the first few blocks. The machine goes on from here to // boot the disk outright — the test below does that — and ProDOS writes // over the low memory the early blocks were read into, so what is checked // here has to be checked while it is still there. const drive = &system.cpu.memory.disk.unidisk.drives[0]; const until = system.cpu.clock.cycles + 300 * second; while (system.cpu.clock.cycles < until and drive.received < 6) system.run(second / 50); // It asked for blocks, and the boot block is block nought. try testing.expectEqual(unidisk.Command.read_block, drive.last.?); try testing.expectEqual(drive.received, drive.replied); // And what arrived is what is on the disk, to the byte. Block two goes to // `$0c00`, which the firmware chose and nothing here arranged. for (0..unidisk.block_size) |i| { const got = system.cpu.memory.peek(@intCast(0x0c00 + i)); try testing.expectEqual(opened.image.data[2 * unidisk.block_size + i], got); } } test "an Apple IIc boots ProDOS off a UniDisk 3.5 and reaches the System Disk's menu" { // The whole of it, through Apple's own firmware and Apple's own disk: a // IIc with the 32K ROM starts, fails to boot the drive in its case, hands // over to the Protocol Converter, finds an intelligent drive on the port, // reads its boot block, runs it, and loads ProDOS a block at a time until // the System Disk puts up its menu. // // None of that text is in the ROM — not "System Disk 3.2", not // "FastCopy", not the copyright — so it came off the disk, and the only // way it could have is through the packets in `cbus.zig` and the drive in // `unidisk.zig`. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIc ROM 00 - 342-0033-A - 1985.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "Apple II System Disk 3.2 on 800k image.2mg"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "system.2mg"); defer opened.deinit(alloc); var system = try powerOn(cpu8.CMOS, memory.AppleIIc(.{}), rom); system.cpu.memory.disk.unidisk.drives[0].fitted = true; system.cpu.memory.disk.unidisk.drives[0].blocks = opened.image.data[0 .. 1600 * 512]; system.cpu.reset(); // The title appears while the rest of the menu is still being drawn, so // the wait is for the last thing on it rather than the first. try system.waitFor("System Disk 3.2", 600 * second); try system.waitFor("FastCopy", 120 * second); try system.expect("Exit to BASIC"); try system.expect("Copyright Apple Computer, Inc. 1987-90"); // And it got there by asking the drive for blocks, one packet at a time. const drive = &system.cpu.memory.disk.unidisk.drives[0]; try testing.expectEqual(unidisk.Command.read_block, drive.last.?); try testing.expect(drive.received > 50); try testing.expectEqual(drive.received, drive.replied); } test "an Apple IIc writes a file to a UniDisk 3.5 and it is really on the disk" { // The other direction over the same bus. Reading a block takes one packet // each way; writing takes three — the command saying which block, then the // five hundred and twelve bytes behind it in a packet of their own, then // the drive's answer. The types are the machine's own: a command goes out // as `$80` and the block behind it as `$82`. // // What proves it is not the machine's own CATALOG, which is the machine // vouching for itself, but finding the file and its bytes in the image the // drive was handed. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIc ROM 00 - 342-0033-A - 1985.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "Apple II System Disk 3.2 on 800k image.2mg"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "system.2mg"); defer opened.deinit(alloc); // The drive's own copy, which is what the machine writes into. const blocks = try alloc.dupe(u8, opened.image.data[0 .. 1600 * unidisk.block_size]); defer alloc.free(blocks); var system = try powerOn(cpu8.CMOS, memory.AppleIIc(.{}), rom); const drive = &system.cpu.memory.disk.unidisk.drives[0]; drive.fitted = true; drive.blocks = blocks; drive.write_protected = false; system.cpu.reset(); // Boot, leave the menu for BASIC, and save a program to the volume the // machine booted from. try system.waitFor("FastCopy", 600 * second); try system.typeLine("3"); try system.waitFor("PRODOS BASIC", 120 * second); try system.typeLine("10 PRINT \"ZIG65\""); try system.typeLine("SAVE UNIWRITE"); system.run(120 * second); // Blocks really went the other way. try testing.expect(drive.written > 0); // And the file is in the image, with the bytes Applesoft tokenises the // line into: the link to where a second line would start, line ten, the // PRINT token, the string in its quotes, and the two zeros that end a // program. Neither `UNIWRITE` nor `ZIG65` occurs anywhere in this ROM or // in the image as it was handed in, in either the high-bit-set form an // Apple stores text in or the plain one. const volume = try prodos.Volume.open(blocks); var name_buffer: [prodos.name_length]u8 = undefined; var path_buffer: [64]u8 = undefined; const path = try std.fmt.bufPrint(&path_buffer, "/{s}/UNIWRITE", .{volume.name(&name_buffer)}); const entry = volume.find(path) orelse return error.TheFileIsNotOnTheDisk; try testing.expectEqualStrings("UNIWRITE", entry.name()); try testing.expectEqual(prodos.FileType.applesoft, entry.kind); var contents: std.Io.Writer.Allocating = .init(alloc); defer contents.deinit(); try volume.read(path, &contents.writer); const tokenised = [_]u8{ 0x0e, 0x08 } ++ [_]u8{ 0x0a, 0x00 } ++ [_]u8{0xba} ++ "\x22ZIG65\x22".* ++ [_]u8{ 0x00, 0x00, 0x00 }; try testing.expectEqualSlices(u8, &tokenised, contents.written()); } test "an Apple IIgs finds a UniDisk 3.5 on its own disk port and boots it" { // The same intelligent drive on the other machine that has a SmartPort. // Nothing in `unidisk.zig` is a IIc's: what a resident answers to is the // bus enable on the phase lines, and every host that speaks this protocol // puts it there. // // The machine's own drives are left empty, so the only place the text // below can come from is the drive on the port. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIGS ROM 01 - 342-0077-B.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "Apple II System Disk 3.2 on 800k image.2mg"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "system.2mg"); defer opened.deinit(alloc); const CPU = cpu16.Chip(.{}, clock.FakeClock, memory16.AppleIIgs(.{})); var system: System(CPU, .mega2) = .{ .cpu = undefined, .alloc = alloc }; try system.cpu.init(alloc, null); defer system.cpu.deinit(); try system.cpu.memory.loadROM(rom); for (&system.cpu.memory.iwm.disks35.drives) |*d| d.fitted = false; system.cpu.memory.iwm.unidisk.drives[0].fitted = true; system.cpu.memory.iwm.unidisk.drives[0].blocks = opened.image.data[0 .. 1600 * 512]; system.cpu.memory.rtc.set(rtc.Rtc.epoch_1904 + 536_457_600, 0); // 1987-01-01 system.cpu.reset(); // The System Utilities' own menu, which is nowhere in the ROM: it can only // have come off the disk, through the packets in `cbus.zig` and the drive // in `unidisk.zig`. try system.waitFor("FastCopy", 300 * gs_second); try system.expect("Exit to BASIC"); try testing.expectEqual(@as(?u8, 1), system.cpu.memory.iwm.unidisk.drives[0].unit); } test "an Apple IIgs numbers a UniDisk 3.5 after the drives it already has" { // The same machine with its own two 3.5-inch drives on the cable in front // of the intelligent one, which is the order Apple lays down: "Apple 3.5 // drives first, followed by UniDisk 3.5 drives, followed by Disk II // drives" (Apple Computer, Inc., 1987a, Figure 6-1, p. 110). // // The machine keeps one and two for those and offers the drive on the port // the number **three**, which is the whole reason a drive here takes its // number from the host rather than being born as unit one. A drive born as // unit one hears that packet, decides it is somebody else's, and says // nothing; the machine then finds nothing on the port at all. // // And it does not boot it, which is not a fault: the startup goes to the // first device on the port, that is an Apple 3.5 drive with nothing in it, // and it stops there. A machine whose owner has a UniDisk on the port has // no Apple 3.5 drives in front of it, which is what the test above is. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIGS ROM 01 - 342-0077-B.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "Apple II System Disk 3.2 on 800k image.2mg"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "system.2mg"); defer opened.deinit(alloc); const CPU = cpu16.Chip(.{}, clock.FakeClock, memory16.AppleIIgs(.{})); var system: System(CPU, .mega2) = .{ .cpu = undefined, .alloc = alloc }; try system.cpu.init(alloc, null); defer system.cpu.deinit(); try system.cpu.memory.loadROM(rom); system.cpu.memory.iwm.unidisk.drives[0].fitted = true; system.cpu.memory.iwm.unidisk.drives[0].blocks = opened.image.data[0 .. 1600 * 512]; system.cpu.memory.rtc.set(rtc.Rtc.epoch_1904 + 536_457_600, 0); // 1987-01-01 system.cpu.reset(); try system.waitFor("Check startup device", 300 * gs_second); const drive = &system.cpu.memory.iwm.unidisk.drives[0]; try testing.expectEqual(@as(?u8, 3), drive.unit); // One packet, answered: the call that gave it its number, and nothing // after it, because the machine never came back to ask for a block. try testing.expectEqual(unidisk.Command.init, drive.last.?); try testing.expectEqual(@as(u64, 1), drive.received); try testing.expectEqual(drive.received, drive.replied); } test "an Apple IIc formats a second UniDisk 3.5 on the chain" { // What a second drive is for. The firmware finds out what is on the port // by asking — `Init` to unit one, then to unit two, and on until nothing // answers — so a chain is not a thing that had to be invented here, only // modelled. With two on it the machine can boot from one and lay the other // down, which is the only way to see `FORMAT` work through a machine // rather than through a unit test. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIc ROM 00 - 342-0033-A - 1985.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "Apple II System Disk 3.2 on 800k image.2mg"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "system.2mg"); defer opened.deinit(alloc); const system_disk = try alloc.dupe(u8, opened.image.data[0 .. 1600 * unidisk.block_size]); defer alloc.free(system_disk); // The blank: not an image of anything, and not a surface either — this // drive deals in blocks, so what an unformatted one holds is whatever was // last on it. A byte no fresh ProDOS volume has is what makes it possible // to say afterwards which blocks the machine really wrote. const blank = try alloc.alloc(u8, 1600 * unidisk.block_size); defer alloc.free(blank); @memset(blank, 0xa5); var system = try powerOn(cpu8.CMOS, memory.AppleIIc(.{}), rom); const chain = &system.cpu.memory.disk.unidisk; chain.drives[0] = .{ .unit = 1, .fitted = true, .blocks = system_disk, .write_protected = false }; chain.drives[1] = .{ .unit = 2, .fitted = true, .blocks = blank, .write_protected = false }; system.cpu.reset(); // Boot the System Disk off the first drive and take its Utilities to // Format a Disk, three items down the first menu. try system.waitFor("FastCopy", 600 * second); try system.typeLine("1"); system.run(60 * second); try system.press(0x0a); try system.press(0x0a); try system.press(0x0a); try system.press('\r'); // Where the disk is. The Slot and Drive fields are not drawn until this // screen is accepted, so the RETURN that draws them comes first; then U // moves to the Drive field and a digit sets it. Both drives are on the // Protocol Converter, which is slot five, so only the drive number differs. try system.waitFor("Where is your disk?", 120 * second); try system.press('\r'); try system.waitFor("Slot:", 120 * second); try system.press(0x15); try system.press('2'); system.run(2 * second); try system.expect("Drive: 2"); try system.press('\r'); try system.waitFor("Select the Operating System", 120 * second); try system.press('\r'); // ProDOS, the first of the two. try system.waitFor("Enter volume name", 120 * second); for (0..prodos.name_length) |_| try system.press(0x7f); try system.typeLine("CHAINED"); // The program asks for the disk to be put in before it lays it down. It // is already there — a drive on this chain is not one anybody opens — so // this is a RETURN and nothing else. try system.waitFor("Please Place Destination Disk", 120 * second); try system.press('\r'); try system.waitFor("Formatting Complete", 600 * second); // The medium was laid down and then written to: `FORMAT` itself writes no // filesystem — "bitmaps and catalogs are not written by this call" — so // the volume on it came block by block afterwards. try testing.expect(chain.drives[1].formatted > 0); try testing.expect(chain.drives[1].written > 0); // And what is there is a ProDOS volume with the name that was typed, of // the size this drive holds. const volume = try prodos.Volume.open(blank); var name_buffer: [prodos.name_length]u8 = undefined; try testing.expectEqualStrings("CHAINED", volume.name(&name_buffer)); try testing.expectEqual(@as(u16, 1600), volume.blocks()); try testing.expect(volume.freeBlocks() > 1500); // The disk the machine booted from is untouched, and it was writable // throughout — so this is what says the right drive on the chain was the // one laid down. const booted = try prodos.Volume.open(system_disk); var booted_name: [prodos.name_length]u8 = undefined; var path_buffer: [64]u8 = undefined; const path = try std.fmt.bufPrint(&path_buffer, "/{s}/BASIC.SYSTEM", .{booted.name(&booted_name)}); try testing.expect(booted.find(path) != null); } test "the drive in a IIc Plus's case is the one ProDOS calls drive one" { // Which way round the port's two drives are is not something the boot // tests can settle — the firmware tries both, so a disk in either one // boots and neither test can tell you which drive it was. What can settle // it is asking ProDOS, which keeps the device it last touched in `DEVNUM` // at `$bf30`: the slot in bits six to four, and bit seven set for drive // two. // // The manual says which of those the drive in the case is — "internal // 3.5-inch drive at $C500 (port 5, drive 1)" against "external UniDisk 3.5 // or Apple 3.5 drive at $C500 (port 5, drive 2)" (Apple Computer, Inc., // 1989b, p. 86) — so booting with the only disk in the first drive must // leave `$5x` there and not `$dx`. // // It left `$d0` before the select was turned round, which is how the // reversal was found: this machine's own drive answers to the *second* of // the port's selects, very likely because `INTEN*` is what should be // choosing it and nothing here can place that latch. See `internal_on_two` // in `iwm.zig`. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIc ROM 05 - IIc Plus.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "Apple II System Disk 3.2 on 800k image.2mg"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "system.2mg"); defer opened.deinit(alloc); const floppy = try alloc.create(disk35.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data); var system = try powerOn(cpu8.CMOS, memory.AppleIIc(.{}), rom); system.cpu.memory.disk.disks35.insert(0, floppy); system.cpu.reset(); try system.waitFor("FastCopy", 400 * second); const devnum = system.cpu.memory.peek(0xbf30); try testing.expectEqual(@as(u8, 5), (devnum >> 4) & 0x07); // slot five try testing.expectEqual(@as(u8, 0), devnum & 0x80); // and drive one } test "an Apple IIe runs Corvus's own firmware to reach the Transporter" { // Everything before this drove the card from the outside. This lets // Corvus's own firmware do it, executed by the emulated 65C02 out of slot // seven's page, entered where the machine's startup scan would enter it. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "APPLE2E.ROM"); defer alloc.free(rom); const prom = try catalogued(alloc, .roms, "Corvus Transporter A2 slot PROM - U15 63S281.bin"); defer alloc.free(prom); var system = try powerOn(cpu8.CMOS, memory.AppleIIe(.{}), rom); try system.cpu.memory.fitTransporter(prom, 0x1f); system.cpu.reset(); // Let the machine start before anything is asked of the card, so that what // runs afterwards runs on a machine in an ordinary state rather than a // half-reset one. Not as far as the BASIC prompt, though: the card's PROM // carries the Pascal signature in its first bytes, so the startup scan // finds something bootable in slot seven and goes to it — which is what a // machine with a network card in it and a network to boot from would do. system.run(2 * second); // A `Who Am I` command vector at $2000, its result record at $3000, and // the return code set to the value the host writes before it asks. system.cpu.memory.write(u8, 0x2000, @intFromEnum(omninet.Command.who_am_i)); system.cpu.memory.write(u8, 0x2001, 0x00); system.cpu.memory.write(u8, 0x2002, 0x30); system.cpu.memory.write(u8, 0x2003, 0x00); system.cpu.memory.write(u8, 0x3000, omninet.pending); // And then Corvus's firmware itself, entered where the machine's own // startup scan would enter it. It works out which slot it is in the way // slot firmware always has — `LDA #$60`, `STA $00`, `JSR $0000`, then read // the return address off the stack — and turns that into the card's // address arithmetically: `LDA $01` gives `$c7`, four `ASL`s make `$70`, // and `ADC #$80` makes `$f0`, which is `$c0f0`. system.cpu.program_counter.jump(0xc700); for (0..200_000) |_| system.step(); // The firmware reached the card: whatever it asked for, it asked through // the address it worked out for itself, and nothing here wrote to `$c0f0`. try testing.expect(system.cpu.memory.slots.cards[7].transporter.card.commands > 0); // And what it settles into is trying to talk to somebody: with nothing // else on the wire the card answers every `Send Message` with "no // acknowledgement", and the firmware goes round again. A machine looking // for a network that is not there is the right thing for it to be doing. try testing.expectEqual(omninet.Command.send_message, system.cpu.memory.slots.cards[7].transporter.card.last.?); } test "a host console card carries PR#n output to the host and takes IN#n input from it" { // The card an embedding program uses to give a headless machine a console: // everything the machine prints goes to a std.Io.Writer, everything it // reads comes from a std.Io.Reader, reached from BASIC by PR#n and IN#n. // Driven here through the real Monitor rather than by poking the firmware. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "APPLE2E.ROM"); defer alloc.free(rom); var system = try powerOn(cpu8.CMOS, memory.AppleIIe(.{}), rom); var out: std.Io.Writer.Allocating = .init(alloc); defer out.deinit(); // What the host "types" once BASIC is reading from the console: a line to // run, then IN#0 to hand input back to the keyboard, so the reader running // dry does not leave BASIC reading empty lines for ever. var in: std.Io.Reader = .fixed("PRINT 6*7\rIN#0\r"); system.cpu.memory.slots.cards[2] = .{ .console = .{ .fitted = true, .out = &out.writer, .in = &in, } }; try system.waitFor("\n]", 2 * second); // Output: PR#2 sends everything the machine prints to the card; print a // line, then PR#0 takes output back to the screen. The printed line // reaches the host writer, carriage return turned into a line feed. try system.typeLine("PR#2"); try system.typeLine("PRINT \"ZIG65\""); try system.typeLine("PR#0"); try system.waitFor("\n]", 2 * second); try testing.expect(std.mem.indexOf(u8, out.written(), "ZIG65\n") != null); // Input: IN#2 takes the command line from the card. BASIC reads // "PRINT 6*7" from the host and prints its answer to the screen, which is // the input having come in through the card. try system.typeLine("IN#2"); try system.waitFor("42", 2 * second); } test "PR#2 sends what the machine prints out of the Super Serial Card" { // The far end of the serial line is where the front end can hang an // ImageWriter II (its `std.Io.Writer` becomes the session's serial sink); // this checks the near end, that PR#2 really puts the machine's printing // onto the card's transmitter, which is the stream that sink receives. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "APPLE2E.ROM"); defer alloc.free(rom); const ssc = try catalogued(alloc, .roms, "341-0065-a.bin"); defer alloc.free(ssc); var system = try powerOn(cpu8.CMOS, memory.AppleIIe(.{}), rom); try system.cpu.memory.fitSerial(2, ssc); system.cpu.reset(); try system.waitFor("\n]", 2 * second); // Everything printed goes to the card until PR#0 takes it back. The line // reaches the card's transmitter, which is what the session drains each // frame to the serial sink. try system.typeLine("PR#2"); try system.typeLine("PRINT \"ZIG65\""); try system.typeLine("PR#0"); // Let the last characters clock out of the transmitter at the card's rate. system.run(second); // Nothing consumes the transmitter here, so what it holds is the whole of // what was sent since power-on: the printed line is in it. // The machine transmits its text with the high bit set, the way it holds // it on screen, so the bytes on the wire are the printed line with bit 7 // on. Masking it off is what a printer set for seven-bit ASCII does, and // is enough to see the line came through. const sent = system.cpu.memory.serialSent(); const masked = try alloc.alloc(u8, sent.len); defer alloc.free(masked); for (sent, masked) |b, *m| m.* = b & 0x7f; try testing.expect(std.mem.indexOf(u8, masked, "ZIG65") != null); } /// Zellyn Hunter's a2audit, booted and read. /// /// The suite is a bootable DOS 3.3 disk rather than a binary, and what it /// checks is the part of a machine that has no corpus behind it: the language /// card's bank switching, the auxiliary memory soft switches, what reading a /// soft switch rather than writing it does, and which ROM answers in the $Cxxx /// pages. Its aim is stated on the tin — "eventually, it should comprise a /// complete emulator test suite, enabling emulator writers to systematically /// identify and eliminate software-testable differences from real hardware" /// (Hunter, 2025) — and it reports a difference by printing a code that is /// documented one for one in the repository's `v0/index.md`. /// /// ## What is checked and what cannot be /// /// The memory tests decide for themselves and say so. The video tests that /// follow them do not: they put two modes on the screen and ask a person which /// looks right, so there is nothing for a test to assert and they are skipped /// here with the key the suite provides for it. /// /// ## Known differences /// /// This is the same bargain as the WOZ expectations table, and it fails in /// both directions: a new code appearing is a regression, and a listed code no /// longer appearing means the table is stale and wants updating. const AuditDifference = struct { code: []const u8, why: []const u8, }; /// Nothing, at present: every code a2audit has to give has been answered. /// /// It was not always empty. `E000B`, the $Cxxx ROM test, stood here until the /// slot pages learned to float — see `withoutCard` in `src/memory8/apple2e.zig` /// — and this is the table it was struck from. const audit_known = [_]AuditDifference{}; /// Runs until the screen shows `needle`, collecting every audit code printed /// along the way. /// /// Collecting as it goes is not optional: the suite calls HOME between groups /// of tests, so by the time it prints END the screen holds nothing but END and /// every code it reported has scrolled away. fn runCollectingAuditCodes( system: anytype, codes: *std.ArrayList([]const u8), alloc: std.mem.Allocator, needle: []const u8, cycles: u64, ) !void { // The audit's own marker, printed immediately before the four hex digits // of the code: "ZELLYN.COM/A2AUDIT/V0#E0007" and so on. const marker = "V0#E"; const slice = second / 20; var spent: u64 = 0; while (spent < cycles) : (spent += slice) { system.run(slice); const text = try system.screen(); defer alloc.free(text); var at: usize = 0; while (std.mem.indexOfPos(u8, text, at, marker)) |found| { at = found + marker.len; if (at + 4 > text.len) break; const code = text[at..][0..4]; for (codes.items) |seen| { if (std.mem.eql(u8, seen, code)) break; } else try codes.append(alloc, try alloc.dupe(u8, code)); } if (std.mem.indexOf(u8, text, needle) != null) return; } return error.AuditNeverGotThere; } test "an Apple IIe boots a disk from a controller in slot 5" { // The whole point of the exercise, through Apple's own ROM and Apple's own // disk: a Disk II controller in a slot no controller has ever been in // here, booted by the machine's own scan. // // Nothing had to be told where to look. A IIe's reset counts down from // slot 7 looking for a card whose page says it can boot, and finds this // one in 5 — which is exactly why a card could be sold for any slot, and // why the constant this replaces was never anything but a convention. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "APPLE2E.ROM"); defer alloc.free(rom); const p5 = try catalogued(alloc, .roms, "341-0027-a.p5"); defer alloc.free(p5); const file = try catalogued(alloc, .disks, "ProDOS BASIC Programming Examples - 680-0235-A.dsk"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "examples.dsk"); defer opened.deinit(alloc); const floppy = try alloc.create(disk2.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data, opened.image.order() orelse return error.NibbleImage); floppy.write_protected = opened.image.write_protected; var system = try powerOn(cpu8.CMOS, memory.AppleIIe(.{}), rom); try system.cpu.memory.fitDisk(5, p5); system.cpu.memory.drives().insert(0, floppy); system.cpu.reset(); try system.waitFor("\n]", 300 * second); try typeAndRun(&system); // And ProDOS agrees about where it came from. It keeps the device it last // touched in DEVNUM at $bf30, as the slot in bits six to four with bit // seven set for drive two — so slot 5 drive 1 is $50. try testing.expectEqual(@as(u8, 5), (system.cpu.memory.peek(0xbf30) >> 4) & 7); } test "an enhanced Apple IIe passes a2audit's language card, auxiliary memory and soft switch tests" { const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "APPLE2E.ROM"); defer alloc.free(rom); // The audit is delivered the way a person would have got it: a DOS 3.3 // disk that boots, so the machine needs the card's boot PROM as well. const p5 = try catalogued(alloc, .roms, "341-0027-a.p5"); defer alloc.free(p5); const file = try catalogued(alloc, .disks, "a2audit 1.7.dsk"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "a2audit.dsk"); defer opened.deinit(alloc); const floppy = try alloc.create(disk2.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data, opened.image.order() orelse return error.NibbleImage); floppy.write_protected = opened.image.write_protected; var system = try powerOn(cpu8.CMOS, memory.AppleIIe(.{}), rom); try system.cpu.memory.loadCardROM(p5); system.cpu.memory.drives().insert(0, floppy); system.cpu.reset(); var codes: std.ArrayList([]const u8) = .empty; defer { for (codes.items) |code| alloc.free(code); codes.deinit(alloc); } // The machine tests run to the one prompt in the suite that waits for a // key, which is where they are over. try runCollectingAuditCodes(&system, &codes, alloc, "PRESS 'Y', 'N', SPACE, OR ESC", 30 * second); try system.press(' '); // The video tests are the ones a person has to judge. SPACE is the only // key the suite's first prompt accepts — it wants one with the high bit // set and the carry clear, which rules out ESC, Y and N — and ESC at the // next prompt is what skips the rest of them. try runCollectingAuditCodes(&system, &codes, alloc, "HIT SPACE TO START", 5 * second); try system.press(' '); system.run(second); try system.press(0x1b); try system.waitFor("END", 5 * second); // Every code seen has to be one that is written down, and every code // written down has to have been seen. for (codes.items) |code| { for (audit_known) |known| { if (std.mem.eql(u8, known.code, code)) break; } else { std.debug.print( "a2audit reported E{s}, which is not a known difference.\n" ++ "What it means is at https://github.com/zellyn/a2audit/blob/master/v0/index.md#e{s}\n", .{ code, code }, ); return error.NewAuditDifference; } } for (audit_known) |known| { for (codes.items) |code| { if (std.mem.eql(u8, known.code, code)) break; } else { std.debug.print( "a2audit no longer reports E{s}, so this table is stale:\n{s}\n", .{ known.code, known.why }, ); return error.AuditDifferenceFixed; } } } /// Where the dead test ROM writes how much RAM it found, which is row 22 of /// the text screen. The banner reads "TESTING RAM FROM $0200 TO $XXFF". const deadtest_banner_row: u16 = 0x400 + 0x80 * 6 + 0x28 * 2; fn deadtestLine(system: anytype, row_base: u16) [40]u8 { var line: [40]u8 = undefined; for (&line, 0..) |*at, col| at.* = system.cpu.memory.peek(row_base + @as(u16, @intCast(col))) & 0x7f; return line; } test "the dead test ROM finds every RAM configuration an Apple II could be built in" { // misterblack1's dead test is a diagnostic ROM that replaces the F8 ROM // and tests memory without using any: no zero page, no stack, everything // in the two kilobytes of itself. That makes it a check on the parts of // this model that a machine which boots never exercises — what an address // with no RAM behind it reads as, and whether the memory select blocks put // the rows where the manual says. // // It counts RAM by writing 0 at the top of each 4K block and reading it // back, on the stated assumption that "reads from empty locations return // $FF regardless of what was written there". That assumption is Sather's // too (1983, p. 5-25) and it is what this model had wrong: the video // scanner's byte was answering instead, so the ROM found 48K in a 4K // machine. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "apple2dead v1.0.2.bin"); defer alloc.free(rom); // Every configuration the 1978 manual gives memory select blocks for // (Apple Computer, Inc., 1978, pp. 133-134), and the address each one // should end at. const configurations = [_]struct { usize, []const u8 }{ .{ 4, "$0FFF" }, .{ 8, "$1FFF" }, .{ 12, "$2FFF" }, .{ 16, "$3FFF" }, .{ 20, "$4FFF" }, .{ 24, "$5FFF" }, .{ 32, "$7FFF" }, .{ 36, "$8FFF" }, .{ 48, "$BFFF" }, }; for (configurations) |configuration| { const kilobytes, const top = configuration; var system = try powerOn(cpu8.CPU, memory.AppleII(.{}), rom); try system.cpu.memory.fitRam(kilobytes * 1024, .contiguous); system.cpu.reset(); // Long enough for the March-U pass over the zero page and the stack, // the page error test and the RAM count, and short enough to stop // before the pass over all of memory overwrites the screen with its // patterns. system.run(4 * second); const banner = deadtestLine(&system, deadtest_banner_row); if (std.mem.indexOf(u8, &banner, top) == null) { std.debug.print( "with {d}K fitted the dead test says:\n |{s}|\nand it should end at {s}\n", .{ kilobytes, &banner, top }, ); return error.WrongMemorySize; } } } test "the dead test ROM passes the zero page and stack" { // The first thing it does, and the thing it exists for: a March-U test of // $0000-$01FF run entirely out of ROM, so that a machine whose first bank // of RAM is bad can still say so. A failure beeps a bit number and drops // into Low-Res mixed rather than printing, so what says it passed is the // line above the banner. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "apple2dead v1.0.2.bin"); defer alloc.free(rom); var system = try powerOn(cpu8.CPU, memory.AppleII(.{}), rom); try system.cpu.memory.fitRam(48 * 1024, .contiguous); system.cpu.reset(); system.run(4 * second); const line = deadtestLine(&system, 0x400 + 0x80 * 3 + 0x28 * 2); // row 19 try testing.expect(std.mem.indexOf(u8, &line, "ZERO/STACK PAGES OK") != null); } test "an Apple IIc Plus boots a five-and-a-quarter disk on the back of the machine" { // The fourth of the four places a IIc Plus will start from: "external // 5.25-inch drive at $C600 (port 6, drive 1)" (Apple Computer, Inc., // 1989b, p. 86). The machine in the case is a 3.5-inch drive, so this is // the only five-and-a-quarter it has, and reaching it is a question about // the MIG rather than about the drive. // // `3.5DRIVE*` decides what is on the end of the cable, and the MIG's // reset line is tied to ROM address 14, so the chip is held in reset for // as long as the main ROM bank is selected (MG, 2018, MIG Chip -> // Pins/Signals). The code that boots this disk is in that bank -- the // two-instruction read loop at $c65e -- so while it runs the latch cannot // be anything but its reset value. A real IIc Plus boots such a disk; // therefore the reset value means five-and-a-quarter, and this test is // what says so. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIc ROM 05 - IIc Plus.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "ProDOS BASIC Programming Examples - 680-0235-A.dsk"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "examples.dsk"); defer opened.deinit(alloc); const floppy = try alloc.create(disk2.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data, opened.image.order() orelse return error.NibbleImage); floppy.write_protected = opened.image.write_protected; var system = try powerOn(cpu8.CMOS, memory.AppleIIc(.{}), rom); system.cpu.memory.drives().insert(0, floppy); system.cpu.reset(); try system.waitFor("\n]", 300 * second); try typeAndRun(&system); // And ProDOS agrees about where it came from. DEVNUM at $bf30 holds the // device it last touched, as the slot in bits six to four with bit seven // set for drive two, and a IIc's five-and-a-quarter port answers as slot // 6 -- so $60 is that port, drive one. Nothing else in the machine can // have put ProDOS in memory to write it. try testing.expectEqual(@as(u8, 0x60), system.cpu.memory.peek(0xbf30)); // The port was talking five-and-a-quarter while it did it, which is the // thing this test is really about: `3.5DRIVE*` was never asserted, // because the code that boots this disk runs in the ROM bank that holds // the MIG in reset and so cannot assert it. try testing.expect(!system.cpu.memory.disk.three_and_a_half); } test "an Apple IIc Plus formats a blank 3.5-inch disk in the drive on the back" { // The IIc Plus's half of the format proof. The IIgs lays a disk down // through its own IWM; this machine lays one down through the glue chip's // buffer, and every address field, data field and checksum on the surface // is one the emulated drive wrote at this machine's direction. It also // exercises the drive select under load: eighty tracks of writing all have // to land in the drive on the back while the disk the machine booted from // sits unprotected in the one in the case. // // It is the only test here that catches a head being chosen wrongly, and // it is why the block-by-block check below covers all sixteen hundred // rather than sampling. Reading is forgiving: a firmware that finds itself // on the wrong side reads an address field that says so and looks again. // Writing is not, and a model that latched the head on a register read // laid every one of a million and a half bytes on side nought and left the // odd-numbered halves of all eighty tracks blank. See `head` in // `disk35.zig`. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIc ROM 05 - IIc Plus.bin"); defer alloc.free(rom); const file = try catalogued(alloc, .disks, "Apple II System Disk 3.2 on 800k image.2mg"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "system.2mg"); defer opened.deinit(alloc); const floppy = try alloc.create(disk35.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data); // The boot disk goes in unprotected on purpose, as the control: if the // drive select went astray and the machine formatted what it booted from, // nothing would stop it and the checks at the end would find it gone. floppy.write_protected = false; // The blank: an unrecorded surface rather than an image, which is what // self-sync reads as, with no address mark anywhere on it. const blank = try alloc.create(disk35.Floppy); defer alloc.destroy(blank); blank.* = .{}; // What an unrecorded surface reads as, which is noise and not a run of // ones. The difference is the whole of why this test could not be written // before: filled with `$ff` a blank disk hands the firmware self-sync for // ever, and its hunt for a `D5` address mark at bank 1 `$e0cd` has no way // out of that. Given noise the hunt fails the way it fails on a real blank // disk, the firmware gives up on reading and lays the surface down // instead. The same amplifier noise is what `disk2.zig` makes with // `fakeBit` over unrecorded five-and-a-quarter surface, for the same // reason and on the same authority (Morris, 2018). var noise: u32 = 0x2545f491; for (&blank.nibbles) |*byte| { noise = noise *% 1664525 +% 1013904223; byte.* = @truncate(noise >> 16); } blank.write_protected = false; // And a recorded disk to occupy the drive on the back while the machine // starts, which the blank cannot do. Two things stand in the way of simply // putting the blank there. This firmware hunts the `D5 AA 96` address mark // in a loop at `$e0cd` that has no way out while the drive keeps handing // it bytes, so an unrecorded surface in any drive at power-on holds the // machine before it has even drawn its banner — the same shape as a Disk // II with no disk in it, and no more a fault here than it is there. And // ProDOS counts its devices once, as it starts, so a drive standing empty // then is not one the Utilities can be pointed at afterwards. A disk that // reads answers both: the machine boots past it and ProDOS counts it, and // it is swapped for the blank at the point the program asks for the disk // to be written. // It carries a name of its own rather than the booted volume's, so that // what the program says it is about to destroy names which disk it read. const stand_in = try alloc.alloc(u8, disk35.image_size); defer alloc.free(stand_in); @memcpy(stand_in, opened.image.data[0..disk35.image_size]); const header = 2 * prodos.block_size + 4; // the volume directory header stand_in[header] = 0xf0 | @as(u8, "PLACEHOLDER".len); @memcpy(stand_in[header + 1 ..][0.."PLACEHOLDER".len], "PLACEHOLDER"); { const check = try prodos.Volume.open(stand_in); var nb: [prodos.name_length]u8 = undefined; try testing.expectEqualStrings("PLACEHOLDER", check.name(&nb)); } const placeholder = try alloc.create(disk35.Floppy); defer alloc.destroy(placeholder); placeholder.* = .{}; try placeholder.load(stand_in); placeholder.write_protected = false; var system = try powerOn(cpu8.CMOS, memory.AppleIIc(.{}), rom); system.cpu.memory.disk.disks35.insert(0, floppy); system.cpu.memory.disk.disks35.insert(1, placeholder); system.cpu.reset(); // Boot the System Disk and take its Utilities to Format a Disk, three // items down the first menu. Both disks are in before the machine starts, // because ProDOS counts its devices once at boot: a drive that was empty // then is not a drive the Utilities can be pointed at afterwards. try system.waitFor("FastCopy", 600 * second); try system.typeLine("1"); system.run(60 * second); try system.press(0x0a); try system.press(0x0a); try system.press(0x0a); try system.press('\r'); // The Slot and Drive fields are not drawn until this screen is accepted, // so the RETURN that draws them comes first; then U moves to the Drive // field and a digit sets it. Drive 2 is the blank, on the back. try system.waitFor("Where is your disk?", 60 * second); try system.press('\r'); try system.waitFor("Slot:", 60 * second); try system.press(0x15); try system.press('2'); system.run(2 * second); try system.expect("Drive: 2"); try system.press('\r'); try system.waitFor("Select the Operating System", 60 * second); try system.press('\r'); // ProDOS, the first of the two. try system.waitFor("Enter volume name", 60 * second); for (0..prodos.name_length) |_| try system.press(0x7f); try system.typeLine("IICPLUSFMT"); // Here is the swap the whole arrangement was for. The program asks for // the destination disk before it reads it, which is the moment the disk // that got the machine this far comes out of the drive on the back and // the unrecorded one goes in — so everything written from here lands on a // surface carrying nothing anybody put there, and there is no volume left // on it for the program to stop and ask about destroying. try system.waitFor("Please Place Destination Disk", 60 * second); system.cpu.memory.disk.disks35.insert(1, blank); try system.press('\r'); try system.waitFor("Formatting Complete", 900 * second); // Something really went down onto the surface. try testing.expect(blank.dirty); try testing.expect(system.cpu.memory.disk.disks35.written > 0); // Read the surface back. The buffer is handed in full of a byte no sector // of a fresh ProDOS volume holds, and `save` leaves a sector it could not // find exactly as given — so a block still full of it is one the machine // never laid down. Checking every one covers the five zones, whose eighty // tracks carry four different sector counts between them. const sentinel = 0xe5; const rendered = try alloc.alloc(u8, disk35.image_size); defer alloc.free(rendered); @memset(rendered, sentinel); try blank.save(rendered); var missing: usize = 0; var first_missing: usize = 0; var block: usize = 0; while (block * prodos.block_size < rendered.len) : (block += 1) { const contents = rendered[block * prodos.block_size ..][0..prodos.block_size]; if (std.mem.allEqual(u8, contents, sentinel)) { if (missing == 0) first_missing = block; missing += 1; } } if (missing != 0) { std.debug.print("{d} of {d} blocks were never written, from block {d}\n first missing: ", .{ missing, rendered.len / prodos.block_size, first_missing, }); var shown: usize = 0; var b: usize = 0; while (b * prodos.block_size < rendered.len and shown < 24) : (b += 1) { if (std.mem.allEqual(u8, rendered[b * prodos.block_size ..][0..prodos.block_size], sentinel)) { std.debug.print("{d} ", .{b}); shown += 1; } } std.debug.print("\n", .{}); return error.TheMachineLeftPartOfTheDiskUnformatted; } // And what it laid down is a ProDOS volume: the name that was typed, the // whole eight hundred kilobytes of it, and a directory that reads. const volume = try prodos.Volume.open(rendered); var name_buffer: [prodos.name_length]u8 = undefined; try testing.expectEqualStrings("IICPLUSFMT", volume.name(&name_buffer)); try testing.expectEqual(@as(u16, 1600), volume.blocks()); try testing.expect(volume.freeBlocks() > 1500); // The disk in the case is untouched: it was writable throughout, so this // is what says the machine formatted the drive it was told to. const kept = try alloc.alloc(u8, disk35.image_size); defer alloc.free(kept); @memcpy(kept, opened.image.data[0..disk35.image_size]); try floppy.save(kept); const booted = try prodos.Volume.open(kept); var booted_name: [prodos.name_length]u8 = undefined; var path_buffer: [64]u8 = undefined; const path = try std.fmt.bufPrint(&path_buffer, "/{s}/BASIC.SYSTEM", .{booted.name(&booted_name)}); try testing.expect(booted.find(path) != null); } test "an Apple IIc Plus answers the accelerator's own commands" { // The four-megahertz cache is not modelled and cannot be -- see the README // -- but its *interface* is a firmware one, and all of that is here. Every // command in Appendix H goes through the entry point at `$c7c7`, which // flips the ROM bank, runs code in the other one, and keeps its state in // the glue chip's buffer. So this exercises the bank thunk, the chip's RAM // window and its page stepping, and the six write-only addresses at // `$c05a-$c05f` all at once, on Apple's own ROM. // // Each command is its own `JSR`, which is how Apple's own sample shell // makes them (Apple Computer, Inc., 1989b, p. 634): "push the command // parameters onto the stack, then execute a JSR instruction to the // accelerator entry point, $C7C7" (p. 627). A command that is understood // returns `$00` in the accumulator. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "Apple IIc ROM 05 - IIc Plus.bin"); defer alloc.free(rom); // No disk anywhere, which on this machine reaches Applesoft by way of a // complaint rather than by hanging: it has an intelligent port and asks // it, where a II Plus with a Disk II card spins for ever. var system = try powerOn(cpu8.CMOS, memory.AppleIIc(.{}), rom); system.cpu.reset(); try system.waitFor("UNABLE TO FIND A BOOTABLE DISK", 120 * second); try system.waitFor("\n]", 30 * second); // One routine per command, sixteen bytes apart, each leaving the // accumulator it was answered with in a byte of its own. const routines = [_]struct { u16, []const u8, []const u8 }{ .{ 0x300, "unlock", &[_]u8{ 0xa9, 0x04, 0x48, 0x20, 0xc7, 0xc7, 0x8d, 0x90, 0x03, 0x60 } }, .{ 0x310, "read", &[_]u8{ 0xa9, 0x03, 0x48, 0xa9, 0x80, 0x48, 0xa9, 0x05, 0x48, 0x20, 0xc7, 0xc7, 0x8d, 0x91, 0x03, 0x60 } }, .{ 0x320, "disable", &[_]u8{ 0xa9, 0x02, 0x48, 0x20, 0xc7, 0xc7, 0x8d, 0x92, 0x03, 0x60 } }, .{ 0x330, "read", &[_]u8{ 0xa9, 0x03, 0x48, 0xa9, 0x84, 0x48, 0xa9, 0x05, 0x48, 0x20, 0xc7, 0xc7, 0x8d, 0x93, 0x03, 0x60 } }, .{ 0x340, "enable", &[_]u8{ 0xa9, 0x01, 0x48, 0x20, 0xc7, 0xc7, 0x8d, 0x94, 0x03, 0x60 } }, .{ 0x350, "read", &[_]u8{ 0xa9, 0x03, 0x48, 0xa9, 0x88, 0x48, 0xa9, 0x05, 0x48, 0x20, 0xc7, 0xc7, 0x8d, 0x95, 0x03, 0x60 } }, .{ 0x360, "write", &[_]u8{ 0xa9, 0x40, 0x48, 0xa9, 0x00, 0x48, 0xa9, 0x06, 0x48, 0x20, 0xc7, 0xc7, 0x8d, 0x96, 0x03, 0x60 } }, .{ 0x370, "read", &[_]u8{ 0xa9, 0x03, 0x48, 0xa9, 0x8c, 0x48, 0xa9, 0x05, 0x48, 0x20, 0xc7, 0xc7, 0x8d, 0x97, 0x03, 0x60 } }, .{ 0x3a0, "write back", &[_]u8{ 0xa9, 0x00, 0x48, 0xa9, 0x67, 0x48, 0xa9, 0x06, 0x48, 0x20, 0xc7, 0xc7, 0x8d, 0x98, 0x03, 0x60 } }, .{ 0x3b0, "lock", &[_]u8{ 0xa9, 0x03, 0x48, 0x20, 0xc7, 0xc7, 0x8d, 0x99, 0x03, 0x60 } }, }; for (routines) |routine| { for (routine[2], 0..) |byte, i| system.cpu.memory.poke(@intCast(routine[0] + i), byte); } // The buffers and the answers, filled with a byte no command writes. for (0x380..0x39a) |address| system.cpu.memory.poke(@intCast(address), 0xee); var line: [16]u8 = undefined; for (routines, 0..) |routine, i| { try system.typeLine(try std.fmt.bufPrint(&line, "CALL {d}", .{routine[0]})); system.run(second); // The Monitor's prompt would mean the machine had fallen out of // Applesoft, which is where a command it did not survive would leave // it -- and it would leave every later check meaningless. if (try system.shows("\n*")) { std.debug.print("the machine fell into the Monitor at step {d} ({s})\n", .{ i, routine[1] }); try system.report(); return error.TheMachineDidNotSurviveTheCommand; } try testing.expectEqual(@as(u8, 0x00), system.cpu.memory.peek(@intCast(0x390 + i))); } const word = struct { fn at(sys: anytype, address: u16) [2]u8 { return .{ sys.cpu.memory.peek(address), sys.cpu.memory.peek(address + 1) }; } }.at; // The control word this machine comes up holding. Its low byte is not a // guess: it is `$67`, the byte at bank 1 `$fe8a`, which the reset path at // `$fd96` loads into X and hands to the routine that writes the chip's // registers -- so reading it back through the firmware is the ROM's own // power-on default coming out the other end. // // Read literally, Table H-1 makes that `$67` "ports 1, 2, 3, 6 and 7 fast, // ports 4 and 5 slow, speaker slow" (Apple Computer, Inc., 1989b, p. 631), // which is not the default the same appendix describes in prose two pages // earlier -- "ROM code for ports 1, 2, 5, and 6 ... cannot be cached ... // The code for ports 3, 4, and 7 can be" (p. 626). The two agree on the // speaker and, through the high byte, on the paddles, and disagree about // every port. The ROM is what the machine does, so the ROM is what is // asserted here; the discrepancy is Apple's and is recorded rather than // resolved. try testing.expectEqual([2]u8{ 0x67, 0x00 }, word(&system, 0x380)); // Disable and Enable move one documented bit and nothing else: high byte // bit 3, "CGGA enable (1 = disabled)" (Table H-1). It is the one bit the // table says the Write command may not touch, and the firmware keeps it in // its shadow rather than in the chip, because the chip has no way to be // asked. try testing.expectEqual([2]u8{ 0x67, 0x08 }, word(&system, 0x384)); try testing.expectEqual([2]u8{ 0x67, 0x00 }, word(&system, 0x388)); // And Write takes a word and Read gives it back. Everything slow. try testing.expectEqual([2]u8{ 0x00, 0x00 }, word(&system, 0x38c)); // And the side effect the appendix warns about, three pages before it // describes a single command: "executing a CGGA command changes the state // of the DHiRes switch, altering the state of graphics screens. You must // return the DHiRes switch to its original state when you are finished // executing any CGGA command" (Apple Computer, Inc., 1989b, p. 626). // // It is true here because `IOUDis` is on -- which is where the firmware // leaves it -- so `$c05e` and `$c05f` are the video's, and the routine at // `$fe54` that writes the chip's registers uses all four of `$c05c` to // `$c05f`. Its last two stores are `STZ $C05D` and `STZ $C05E`, and // clearing annunciator 3 is what turns double resolution on. This // assertion is the reason the switch is now modelled the way the manual // has it: with it the other way about, these writes went to the mouse's // edge selector and the documented side effect did not happen at all. try testing.expect(system.cpu.memory.double_hires); // The machine is still the machine afterwards: Applesoft answers, which is // what says none of this left it somewhere it cannot come back from. try system.typeLine("PRINT 6*7"); try system.waitFor("42", 5 * second); } test "an Apple IIe boots ProDOS off a SCSI disk through Apple's own card firmware" { // The whole stack, end to end and none of it ours: Apple's card firmware // runs on the emulated NCR 5380, which drives an emulated SCSI bus, on // which a disk answers INQUIRY, READ CAPACITY and READ(6) until ProDOS is // in memory and the System Disk's menu is on the screen. // // Nothing on that path is firmware written here, which is the difference // between this card and the block device in `blockdevice.zig`: that one // answers ProDOS with code written for this project, and this one is a // sixteen-kilobyte ROM Apple wrote in 1986 working real registers. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "APPLE2E.ROM"); defer alloc.free(rom); const firmware = try catalogued(alloc, .roms, "341-0437-a.bin"); defer alloc.free(firmware); const file = try catalogued(alloc, .disks, "Apple II System Disk 3.2 on 800k image.2mg"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "system.2mg"); defer opened.deinit(alloc); // The image goes on the bus rather than in a drive: a SCSI disk is blocks // and a command set, with no track, no sector and no head anywhere in it. const image = try alloc.dupe(u8, opened.image.data); defer alloc.free(image); var system = try powerOn(cpu8.CMOS, memory.AppleIIe(.{}), rom); try system.cpu.memory.fitScsi(7, firmware); const card = system.cpu.memory.scsiCard(7).?; try card.attach(6, image, false); system.cpu.reset(); // The card is in slot 7, which is where the boot scan starts, so nothing // has to be typed: the machine finds it, runs its firmware, and the // firmware finds the disk. try system.waitFor("System Disk 3.2", 300 * second); try system.waitFor("Main Menu", 60 * second); // The menu is still being drawn when its title appears, so the last thing // on it is waited for rather than expected on the spot. try system.waitFor("Quit to another program", 60 * second); // And it got there over the bus rather than by any shortcut: the last // thing the disk was asked was a read, and it answered without complaint. // None of that could have been faked by the card, because none of it is // modelled anywhere but in `scsi.zig`. try testing.expect(card.disks[6].cdb[0] == 0x08 or card.disks[6].cdb[0] == 0x28); try testing.expectEqual(scsi.SenseKey.none, card.disks[6].sense); try testing.expect(card.chip.bus.selected == null); // and the bus was let go } test "two drives on the SCSI bus, and ProDOS finds them both" { // A bus rather than a card with a drive on it. Two disks at two // identities, and the firmware's scan finds each of them and hands ProDOS // two volumes -- which is the whole difference between a SCSI card and the // block device, whose two drives are two fields. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "APPLE2E.ROM"); defer alloc.free(rom); const firmware = try catalogued(alloc, .roms, "341-0437-a.bin"); defer alloc.free(firmware); const file = try catalogued(alloc, .disks, "Apple II System Disk 3.2 on 800k image.2mg"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "system.2mg"); defer opened.deinit(alloc); // The one it boots from, at six. const booted = try alloc.dupe(u8, opened.image.data); defer alloc.free(booted); // And a second, at five, with a volume of its own on it so that finding it // means something: a blank would be found as damaged rather than as a // disk. Four megabytes, which no floppy could be and which is the point of // hanging a hard disk off a card. const other = try alloc.alloc(u8, 8192 * prodos.block_size); defer alloc.free(other); @memset(other, 0); _ = try prodos.Volume.format(other, "SECOND"); var system = try powerOn(cpu8.CMOS, memory.AppleIIe(.{}), rom); try system.cpu.memory.fitScsi(7, firmware); const card = system.cpu.memory.scsiCard(7).?; try card.attach(6, booted, false); try card.attach(5, other, false); system.cpu.reset(); try system.waitFor("Main Menu", 300 * second); try system.waitFor("Quit to another program", 60 * second); // Both were spoken to: each answered a command, and neither has anything // to complain about. try testing.expect(card.disks[6].cdb[0] != 0); try testing.expect(card.disks[5].cdb[0] != 0); try testing.expectEqual(scsi.SenseKey.none, card.disks[6].sense); try testing.expectEqual(scsi.SenseKey.none, card.disks[5].sense); // And ProDOS has two devices rather than one. Its device count is at // $bf31 and the list of them starts at $bf32; both of ours are in slot 7, // which is the high nybble of a device number. const count = system.cpu.memory.peek(0xbf31) + 1; var in_seven: usize = 0; for (0..count) |i| { const device = system.cpu.memory.peek(@intCast(0xbf32 + i)); if ((device >> 4) & 7 == 7) in_seven += 1; } try testing.expectEqual(@as(usize, 2), in_seven); } test "a II Plus boots a disk in its Disk II drive" { // There was no such test, which is exactly how a II Plus came to be unable // to boot any disk at all while every other machine still could: the WOZ // reference set boots on a IIe, and the one II Plus test here had no drive // in it. A machine that cannot boot is the thing this suite exists to // notice. const alloc = testing.allocator; const image = try catalogued(alloc, .roms, "APPLE2.ROM"); defer alloc.free(image); const p5 = try catalogued(alloc, .roms, "341-0027-a.p5"); defer alloc.free(p5); const file = try catalogued(alloc, .disks, "Apple Logo 1.5.dsk"); defer alloc.free(file); const opened = try diskfile.open(alloc, file, "logo.dsk"); defer opened.deinit(alloc); const floppy = try alloc.create(disk2.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.load(opened.image.data, opened.image.order() orelse return error.NibbleImage); floppy.write_protected = true; // The top 12K is the system ROM proper; the 20K image carries the slot // space it was dumped with, and the card fitted below is what should // answer at $c600. const rom = image[image.len - 0x3000 ..]; var system = try powerOn(cpu8.CPU, memory.AppleIIPlus(.{}), rom); try system.cpu.memory.fitDisk(6, p5); system.cpu.memory.drives().insert(0, floppy); system.cpu.reset(); // DOS 3.3 loads and Logo starts: text that is nowhere in the ROM and can // only have come off the disk, through the card, a bit at a time. try system.waitFor("PRESS THE RETURN KEY TO BEGIN", 60 * second); } test "a file saved to a WOZ disk is written back into the .woz file" { // WOZ used to be read-only: the reference disk format could be booted but // never persisted. This boots a DOS 3.3 System Master WOZ, SAVEs a program // to it, writes the disk back to a .woz file, and re-opens that file to // find the program really on it. const alloc = testing.allocator; const rom = try catalogued(alloc, .roms, "APPLE2E.ROM"); defer alloc.free(rom); const p5 = try catalogued(alloc, .roms, "341-0027-a.p5"); defer alloc.free(p5); const original = try catalogued(alloc, .disks, "woz/WOZ 2.0/DOS 3.3 System Master.woz"); defer alloc.free(original); // A writable copy on disk for the write-back to land in. const dir = testing.environ.getPosix("TMPDIR") orelse "/tmp"; const path = try std.fmt.allocPrint(alloc, "{s}/zig65-wozwrite.woz", .{dir}); defer { std.Io.Dir.cwd().deleteFile(testing.io, path) catch {}; alloc.free(path); } try std.Io.Dir.cwd().writeFile(testing.io, .{ .sub_path = path, .data = original }); const floppy = try alloc.create(disk2.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.loadWoz(try woz.open(original)); floppy.write_protected = false; var system = try powerOn(cpu8.CMOS, memory.AppleIIe(.{}), rom); try system.cpu.memory.fitDisk(6, p5); system.cpu.memory.drives().insert(0, floppy); system.cpu.reset(); // The System Master boots to Applesoft. Save a one-line program; the SAVE // is a real disk write, so the drive comes back dirty. try system.waitFor("\n]", 300 * second); try system.typeLine("NEW"); try system.typeLine("10 PRINT \"ON THE WOZ\""); try system.typeLine("SAVE WOZWRITE"); system.run(20 * second); try testing.expect(floppy.dirty); // Write it back to the .woz file, re-read that file (its CRC must check // out or `woz.open` refuses it), and render it to a sectored image. try writeback.floppy(testing.io, alloc, path, floppy); const back = try std.Io.Dir.cwd().readFileAlloc(testing.io, path, alloc, .limited(woz.max_file_size)); defer alloc.free(back); const reloaded = try alloc.create(disk2.Floppy); defer alloc.destroy(reloaded); reloaded.* = .{}; try reloaded.loadWoz(try woz.open(back)); // The nibbles carry no sector order of their own; this disk is DOS 3.3, so // render it in DOS order for the filesystem reader. reloaded.order = .dos; const image = try alloc.alloc(u8, disk2.image_size); defer alloc.free(image); try reloaded.save(image); // And DOS 3.3 finds the file on it, so the write reached the file and the // disk still reads as the volume it was. var disk = try dos33.Disk.open(image); try testing.expect(disk.find("WOZWRITE") != null); } test "writing back an untouched WOZ 1.0 disk reproduces it byte for byte" { // The write-back copies each track's bits into the same slot and redoes // the CRC, so a disk nothing wrote to comes back identical -- which also // exercises the version-1 track layout (fixed 6,656-byte slots) that the // version-2 machine test does not. const alloc = testing.allocator; const original = try catalogued(alloc, .disks, "woz/WOZ 1.0/DOS 3.3 System Master.woz"); defer alloc.free(original); const dir = testing.environ.getPosix("TMPDIR") orelse "/tmp"; const path = try std.fmt.allocPrint(alloc, "{s}/zig65-woz1-roundtrip.woz", .{dir}); defer { std.Io.Dir.cwd().deleteFile(testing.io, path) catch {}; alloc.free(path); } try std.Io.Dir.cwd().writeFile(testing.io, .{ .sub_path = path, .data = original }); const floppy = try alloc.create(disk2.Floppy); defer alloc.destroy(floppy); floppy.* = .{}; try floppy.loadWoz(try woz.open(original)); try writeback.floppy(testing.io, alloc, path, floppy); const back = try std.Io.Dir.cwd().readFileAlloc(testing.io, path, alloc, .limited(woz.max_file_size)); defer alloc.free(back); try testing.expectEqualSlices(u8, original, back); } test "the UCSD Pascal filesystem reads a real Apple II Pascal disk" { // Apple's own APPLE1 startup disk, read the way the catalogue notes it has // to be: a p-System volume, like a ProDOS one, keeps its blocks in the // logical order DOS interleaves, and the `.dsk` holds them in DOS sector // order, so it is put into block order first. const alloc = testing.allocator; const dsk = try catalogued(alloc, .disks, "Apple II Pascal 1.1 APPLE1_ 680-0004-01.dsk"); defer alloc.free(dsk); const blocks = try alloc.alloc(u8, disk2.image_size); defer alloc.free(blocks); try disk2.reorder(dsk, blocks, .dos, .prodos); const volume = try pascal.Volume.open(blocks); var name_buffer: [pascal.volume_name_length]u8 = undefined; try testing.expectEqualStrings("APPLE1", volume.name(&name_buffer)); try testing.expectEqual(@as(u16, 280), volume.totalBlocks()); try testing.expectEqual(@as(u16, 8), volume.numFiles()); // The eight files Apple put on the startup disk, in the order the directory // holds them, which is ascending order of the block each starts on. const expected = [_][]const u8{ "SYSTEM.APPLE", "SYSTEM.PASCAL", "SYSTEM.MISCINFO", "SYSTEM.EDITOR", "SYSTEM.FILER", "SYSTEM.LIBRARY", "SYSTEM.CHARSET", "SYSTEM.SYNTAX", }; var files = volume.catalog(); for (expected) |want| { const entry = files.next() orelse return error.TooFewFiles; try testing.expectEqualStrings(want, entry.name()); } try testing.expectEqual(@as(?pascal.Entry, null), files.next()); // SYSTEM.MISCINFO is a single block, so reading it hands back exactly the // 512 bytes it stores and the read path is exercised end to end. const info = volume.find("SYSTEM.MISCINFO") orelse return error.NotFound; try testing.expectEqual(@as(u32, 512), info.size()); try testing.expectEqual(pascal.FileKind.data, info.kind); var got: std.Io.Writer.Allocating = .init(alloc); defer got.deinit(); try volume.read("SYSTEM.MISCINFO", &got.writer); try testing.expectEqual(@as(usize, 512), got.written().len); }