Something went wrong. Try again.
A cycle-accurate Apple II and Apple IIgs emulator written in Zig, usable as both a program and a library.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! The IIgs machine-driving core, with no front end in it.//!//! This is the 65816 counterpart to `session8.zig`: everything the IIgs front//! end does that has nothing to do with how the machine is looked at — pacing//! the clock and running instructions in arrears (`stepDue`, `frameDue`),//! handing typed keys to the keyboard as it becomes ready (`feedKeyboard`),//! changing the disks (`insert`, `eject`, `mount`), moving bytes along the//! modem and printer ports and the LocalTalk network (`pumpSerial`,//! `pumpNetwork`), recording the Ensoniq, and keeping the run speed and the//! measured rate. None of it draws anything or reads a key event.//!//! It is a separate core from the eight-bit `Session` on purpose, the same way//! `cpu16` and `memory16` are separate from `cpu8` and the eight-bit memory//! models: a IIgs is a different machine with a different keyboard bus, disk//! port, sound chip and a network, and none of that belongs in the eight-bit//! core. The machine is a single concrete configuration rather than a//! comptime-generic one, so this is a plain struct rather than a function//! returning a type.//!//! `gs.zig` embeds one of these and adds the drawing and the keystrokes on//! top; a different front end would embed the same `Session`, render from the//! library's own screen surface, translate its own input into the model's//! latches and the `Session`'s own actions, and control time by supplying the//! `std.Io` it is given. Building the machine stays with the front end that//! knows the ROM and the disks, the same division the eight-bit side makes.
const std = @import("std");
const zig65 = @import("zig65");const ltoudp = @import("ltoudp.zig");
const disk2 = zig65.disk2;const disk35 = zig65.disk35;const snapshot = zig65.snapshot;const diskfile = zig65.diskfile;
pub const CPU = zig65.cpu16.Chip(.{}, zig65.clock.FakeClock, zig65.memory16.AppleIIgs(.{}));pub const Memory = @TypeOf(@as(CPU, undefined).memory);
/// How fast the machine is meant to go, in the cycles this model counts.////// The IIgs's fast side is about 2.8 MHz, and this model counts a slow access/// as three cycles, so its second is three cycles of its own for each of the/// Mega II's — which is the number the machine's own one-second interrupt is/// counted in too.pub const cycles_per_second = Memory.cycles_per_frame * 60;
/// Sixty frames a second, and how long the processor may run inside one/// before the loop has to go and look at the keyboard again.pub const frame_ns = 16 * std.time.ns_per_ms;pub const step_budget_ns = 12 * std.time.ns_per_ms;
/// A clock that does not jump when the system time is put right, since a/// machine that lurched every time NTP spoke would be no use.pub const pacing_clock: std.Io.Clock = .awake;
/// Compact disc rate, which is above anything the chip does.pub const sample_rate = 44_100;
/// What the processor is doing between redraws, and why it is not running when/// it is not. Both come from the library rather than from here, because the/// eight-bit front end is a separate module and needs the same two words for/// the same two things -- see `zig65.debug`.pub const State = zig65.debug.State;
/// Twenty-four bits of address, unlike the eight-bit machine's sixteen: a/// 65816 fetches through a program bank register, and an address without its/// bank does not say where anything is.pub const Stop = zig65.debug.Stop(u24);
/// The range the run speed can be dialled through. The bottom is a thousand/// cycles a second, which is slow enough to watch a program work; the top is/// as fast as the host manages, since asking for more than that simply gets/// however much there is.pub const min_hz = 1_000;pub const max_hz = 1_000_000_000;
/// Which of the machine's two drives a disk is going into.////// They are not two of a kind. A IIgs has a 3.5-inch drive and a 5.25-inch/// one on the same port, and which of them a disk belongs in is settled by the/// disk: eight hundred kilobytes only fits one and a hundred and forty only/// fits the other. So a path typed at either prompt goes wherever it fits, and/// naming a drive is a way of saying which one to *empty*.pub const Drive = enum { three_and_a_half, five_and_a_quarter,
pub fn name(self: Drive) []const u8 { return switch (self) { .three_and_a_half => "3.5-inch", .five_and_a_quarter => "5.25-inch", }; }};
/// What is in one drive, and where it came from.pub const Slot = struct { name: [128]u8 = undefined, len: usize = 0,
pub fn set(self: *Slot, path: []const u8) void { const base = std.fs.path.basename(path); self.len = @min(base.len, self.name.len); @memcpy(self.name[0..self.len], base[0..self.len]); }
pub fn shown(self: *const Slot) []const u8 { return if (self.len == 0) "empty" else self.name[0..self.len]; }};
pub const Session = struct { const Self = @This();
io: std.Io, gpa: std.mem.Allocator, cpu: *CPU,
/// Keys the front end has handed over that the machine has not taken yet. /// There is one keyboard latch and no queue behind it, and a terminal /// delivers a burst far faster than any program could poll for one, so the /// queue is here rather than in the machine. typed: [256]u8 = undefined, /// And which modifiers were down when each was pressed. They are handed /// over with the key rather than when it was typed, because the machine /// reads them at `$c025` when it takes the key out of the latch and a /// queue means those are not the same moment. typed_mods: [256]u8 = undefined, typed_len: usize = 0,
/// The two drives and what is in them. floppy35: *disk35.Floppy, floppy: *disk2.Floppy, slots: [2]Slot = .{ .{}, .{} },
/// The hard disk's two drives: the image in memory, where it came from, /// and its name to show. Unlike a floppy, a hard disk is written back to /// its file when the machine stops. volumes: [2]?*zig65.blockdevice.Volume = .{ null, null }, /// The whole file each volume came out of, which is not the same thing /// when the file is a 2IMG: the volume is a slice of this with the header /// in front of it, and it is this that gets written back. volume_files: [2]?[]u8 = .{ null, null }, volume_paths: [2]?[]const u8 = .{ null, null }, volume_slots: [2]Slot = .{ .{}, .{} }, /// Where each floppy came from, in the same order as `slots`: the /// 3.5-inch drive first and the 5.25-inch one second. /// /// `Slot` keeps only the base name, which is all the display wants; this /// is the whole path, which is what writing the disk back needs. Without /// it a IIgs kept everything the machine wrote in memory and dropped it on /// the way out, which its hard-disk volumes never did. disk_paths: [2]?[]const u8 = .{ null, null },
/// And the intelligent drive on the port, if one is plugged in: the disk /// as blocks, where it came from, and its name to show. /// /// This is not one of the machine's own drives. An Apple IIgs has an /// Integrated Woz Machine and a socket on the back, and what goes on that /// socket is whatever the owner bought; a UniDisk 3.5 is a device with a /// processor of its own that answers packets, not a mechanism the machine /// drives. So it is kept apart from `floppy35`, which is the dumb Apple /// 3.5 drive, and the two are never both in front of the other on the /// cable — see `--unidisk` in the README. unidisk_blocks: [2]?[]u8 = .{ null, null }, unidisk_paths: [2]?[]const u8 = .{ null, null }, unidisk_slots: [2]Slot = .{ .{}, .{} }, /// What the sound chip has played, if anybody asked for it. recording: ?zig65.ensoniq.Recorder = null,
/// The two ends of the modem port's wire. `serial_in` is the whole of a /// file read in at the start, since a serial line is a stream and a file /// is the nearest thing to one that a program can be handed. serial_out: ?std.Io.File = null, serial_in: ?[]u8 = null, serial_in_at: usize = 0, serial_in_due: u64 = 0, /// A Hayes modem on the SCC's modem port (channel B), dialing out over TCP, /// when one is attached in place of the serial files — the same modem the /// eight-bit machines put on the Super Serial Card. modem: ?zig65.modem.Modem = null, modem_line: zig65.modem.Line = .{}, modem_in_due: u64 = 0,
/// And the printer port's outward end, which is channel A. Only outward: /// the channel is the same as the other one and would carry bytes back /// perfectly well, but a printer is a thing you send to. printer_out: ?std.Io.File = null,
/// The network, if the machine is on one: the far end of whichever port /// the firmware put on LocalTalk, bridged to the multicast group other /// emulators use. And a log of every frame that crossed, if asked for. network: ?ltoudp.Network = null, network_log: ?std.Io.File = null,
/// The host end of an Uthernet II, if one is fitted: the four sockets that /// stand in for the W5100's. Idle and costing nothing until a program /// opens a socket. uthernet: zig65.uthernet.Ports = .{}, /// The host end of an Uthernet (the original): the multicast group its /// CS8900A's frames cross, opened by the front end when the card is fitted. ethernet: ?zig65.ethernet.Bridge = null,
/// How many transfers the card had done when the last frame was drawn, /// which is how the light on it is known to be worth lighting. volume_accesses: u64 = 0, volume_lit: bool = false,
/// And the same for the intelligent drive on the port, which has no /// spindle anything here can see: what says it is working is that it has /// answered another packet since the last frame was drawn. unidisk_packets: u64 = 0, unidisk_lit: bool = false,
/// What to say about the last thing that happened. message: [72]u8 = undefined, message_len: usize = 0,
/// What the processor is doing, and why it stopped if it did. A machine /// brought up halted sits on its reset vector until somebody says /// otherwise, which is what `--halted` is for. state: State = .running, stopped: ?Stop = null,
/// How fast it is being asked to go, in the cycles this model counts. /// Starts at the rate the machine's own crystal gives and is dialled up /// and down from there. target_hz: u64 = cycles_per_second,
/// Pacing. owed: i96 = 0, last_step: std.Io.Timestamp = .{ .nanoseconds = 0 }, next_frame: std.Io.Timestamp = .{ .nanoseconds = 0 }, measured_at: std.Io.Timestamp = .{ .nanoseconds = 0 }, measured_cycles: u64 = 0, measured_hz: f64 = 0,
/// Which of the two Apple keys are being held down. A terminal reports /// presses and never releases, so they are toggled rather than held. apple: [2]bool = .{ false, false },
/// When the machine actually started running, which is after the terminal /// has been asked what it can do — a query that waits up to a second for /// an answer, and counting it as running time made the machine look an /// eighth slower than it is. started: std.Io.Timestamp = .{ .nanoseconds = 0 }, started_cycles: u64 = 0,
/// Puts a disk in whichever drive it fits, or takes one out. /// /// A 2IMG has its wrapper taken off first, and is believed about which way /// round its sectors are; a bare image has only its name to go on. /// /// Nothing is ever written back to the file: what is in the drive is a /// copy in memory, and it is write enabled because a machine that cannot /// write to its disk cannot be made to do very much. A disk whose file /// says it was write protected is left that way, since that is the file /// saying something rather than this program assuming it. /// Puts a disk in whichever drive it fits. `writable` is a per-disk /// override for a library entry: false write protects it whatever the file /// says, so a boot disk stays pristine. Null leaves it to the file, which /// is what a path typed at the prompt does — the IIgs writes to a disk /// unless the image itself says not to. pub fn insert(self: *Self, path: []const u8, writable: ?bool) !void { const file = try std.Io.Dir.cwd().readFileAlloc(self.io, path, self.gpa, .unlimited); defer self.gpa.free(file); // Which of the three kinds of file it is is settled here rather than // by whoever typed the name: a bare dump, a 2IMG, or a ShrinkIt // archive with a disk somewhere inside it. const opened = try diskfile.open(self.gpa, file, path); defer opened.deinit(self.gpa); const image = opened.image;
// A recording of a surface is a 5.25-inch disk and nothing else: the // format is thirty-five tracks of what a Disk II's head saw, and an // 800K drive's head sees something else entirely. if (image.isWoz() or image.isNibble()) { if (image.isWoz()) try self.floppy.loadWoz(try zig65.woz.open(image.data)) else try self.floppy.loadNibbles(image.data); self.floppy.write_protected = image.write_protected or (writable == false); self.cpu.memory.iwm.drives.insert(0, self.floppy); self.remember(1, path); self.say("{s} in the 5.25-inch drive", .{self.slots[1].shown()}); return; }
const order = image.order() orelse return error.NibbleImage; if (self.floppy35.load(image.data)) |_| { self.floppy35.write_protected = image.write_protected or (writable == false); self.cpu.memory.iwm.disks35.insert(0, self.floppy35); self.remember(0, path); self.say("{s} in the 3.5-inch drive", .{self.slots[0].shown()}); return; } else |_| {} try self.floppy.load(image.data, order); self.floppy.write_protected = image.write_protected or (writable == false); self.cpu.memory.iwm.drives.insert(0, self.floppy); self.remember(1, path); self.say("{s} in the 5.25-inch drive", .{self.slots[1].shown()}); }
/// Notes what is in a drive and where it came from, taking whatever was /// there out first. fn remember(self: *Self, which: usize, path: []const u8) void { self.slots[which].set(path); if (self.disk_paths[which]) |old| self.gpa.free(old); self.disk_paths[which] = self.gpa.dupe(u8, path) catch null; }
/// Writes back what the machine wrote to a floppy, if anything, and if the /// disk is one that can be written back at all. pub fn save(self: *Self, drive: Drive) void { const which: usize = switch (drive) { .three_and_a_half => 0, .five_and_a_quarter => 1, }; const path = self.disk_paths[which] orelse return; const outcome = switch (drive) { .three_and_a_half => blk: { if (!self.floppy35.dirty or self.floppy35.write_protected) return; break :blk zig65.writeback.floppy35(self.io, self.gpa, path, self.floppy35); }, .five_and_a_quarter => blk: { if (!self.floppy.dirty or self.floppy.write_protected) return; break :blk zig65.writeback.floppy(self.io, self.gpa, path, self.floppy); }, }; outcome catch |err| { self.say("could not write {s} back: {s}", .{ std.fs.path.basename(path), @errorName(err) }); return; }; switch (drive) { .three_and_a_half => self.floppy35.dirty = false, .five_and_a_quarter => self.floppy.dirty = false, } }
/// Puts a block image in one of the two intelligent drives on the port. /// /// A UniDisk 3.5 holds sixteen hundred blocks, which is the eight hundred /// kilobytes of a double-sided 3.5-inch disk, and that is what is offered /// to it; anything else is refused rather than quietly truncated. What is /// kept is the image and not a surface, because this drive is asked for /// numbered blocks and has no notion of a track. /// /// The machine's own 3.5-inch drives come off the cable with the first of /// these, unless something is already in one of them. They sit in front of /// it -- "Apple 3.5 drives first, followed by UniDisk 3.5 drives" -- and /// the startup goes to the first device on the port and stops there, so a /// pair of empty drives nobody owns is a pair of empty drives the machine /// tries to boot. An empty drive that is not there is not a drive. pub fn insertUnidisk(self: *Self, which: u1, path: []const u8, writable: ?bool) !void { const file = try std.Io.Dir.cwd().readFileAlloc(self.io, path, self.gpa, .unlimited); defer self.gpa.free(file); const opened = try diskfile.open(self.gpa, file, path); defer opened.deinit(self.gpa); const image = opened.image;
const wanted = 1600 * zig65.unidisk.block_size; if (image.isWoz() or image.isNibble() or image.data.len < wanted) return error.NotABlockImage;
const kept_blocks = try self.gpa.dupe(u8, image.data[0..wanted]); errdefer self.gpa.free(kept_blocks); const kept_path = try self.gpa.dupe(u8, path); errdefer self.gpa.free(kept_path);
self.ejectUnidisk(which); self.unidisk_blocks[which] = kept_blocks; self.unidisk_paths[which] = kept_path; self.unidisk_slots[which].set(path);
const drive = &self.cpu.memory.iwm.unidisk.drives[which]; drive.blocks = kept_blocks; drive.write_protected = image.write_protected or (writable == false); drive.fitted = true;
for (&self.cpu.memory.iwm.disks35.drives) |*mechanism| { if (mechanism.floppy == null) mechanism.fitted = false; } self.say("{s} in the UniDisk 3.5", .{self.unidisk_slots[which].shown()}); }
/// Writes back what the machine wrote to one of them. pub fn saveUnidisk(self: *Self, which: u1) void { const drive = &self.cpu.memory.iwm.unidisk.drives[which]; // The session's own pointer and not the drive's: they are the same // memory, and only this one survives the machine ejecting the disk // from inside with a `CONTROL` call. const blocks = self.unidisk_blocks[which] orelse return; const path = self.unidisk_paths[which] orelse return; if (!drive.dirty or drive.write_protected) return; zig65.writeback.blocks(self.io, self.gpa, path, blocks) catch |err| { self.say("could not write {s} back: {s}", .{ std.fs.path.basename(path), @errorName(err) }); return; }; drive.dirty = false; }
/// Takes the disk out and the drive off the cable with it: an empty /// intelligent drive and none at all are the same thing to the firmware, /// which finds one by its answering at all. pub fn ejectUnidisk(self: *Self, which: u1) void { self.saveUnidisk(which); const drive = &self.cpu.memory.iwm.unidisk.drives[which]; drive.blocks = null; drive.fitted = false; drive.reset(); if (self.unidisk_blocks[which]) |blocks| self.gpa.free(blocks); self.unidisk_blocks[which] = null; if (self.unidisk_paths[which]) |path| self.gpa.free(path); self.unidisk_paths[which] = null; self.unidisk_slots[which].len = 0; }
/// The most a snapshot file is allowed to be: a IIgs with eight megabytes /// and disks in every drive, comfortably rounded up. const snapshot_limit = 64 * 1024 * 1024;
/// Writes the whole IIgs — its memory, its processor, every chip, and the /// disks in its drives — to a file, to be brought back with `loadSnapshot`. pub fn saveSnapshot(self: *Self, path: []const u8) !void { var writer: snapshot.Writer = .{ .gpa = self.gpa }; defer writer.deinit(); try snapshot.writeHeader(&writer, CPU); try writer.value(CPU, self.cpu); try self.writeDisks(&writer); try std.Io.Dir.cwd().writeFile(self.io, .{ .sub_path = path, .data = writer.list.items }); }
/// Brings the machine back from a snapshot, disks and all. The state is /// read into this live machine, so a snapshot of a differently built one is /// refused rather than loaded wrong. pub fn loadSnapshot(self: *Self, path: []const u8) !void { const data = try std.Io.Dir.cwd().readFileAlloc(self.io, path, self.gpa, .limited(snapshot_limit)); defer self.gpa.free(data); var reader: snapshot.Reader = .{ .data = data, .gpa = self.gpa }; try snapshot.readHeader(&reader, CPU); try reader.value(CPU, self.cpu); try self.readDisks(&reader); }
/// The disk section of a snapshot. The two floppy drives are always here — /// their `Floppy` is allocated whether or not a disk is in it, and its /// surface is what carries whether one is — followed by each hard-disk /// volume and each intelligent drive on the port. fn writeDisks(self: *Self, writer: *snapshot.Writer) !void { try writer.value(disk2.Floppy, self.floppy); try writer.value(disk35.Floppy, self.floppy35); inline for (0..2) |which| { if (self.volumes[which]) |volume| { try writer.int(u8, 1); try writer.value(zig65.blockdevice.Volume, volume); } else try writer.int(u8, 0); } inline for (0..2) |which| { if (self.unidisk_blocks[which]) |blocks| { try writer.int(u8, 1); try writer.int(u64, blocks.len); try writer.raw(blocks); } else try writer.int(u8, 0); } }
/// Reads the disk section back in the same order. The floppy surfaces go /// straight into their live `Floppy`s; a hard disk and an intelligent drive /// are read into the ones already fitted, since their images are sized by /// the files they came from and neither is swapped mid-run. fn readDisks(self: *Self, reader: *snapshot.Reader) !void { try reader.value(disk2.Floppy, self.floppy); try reader.value(disk35.Floppy, self.floppy35); inline for (0..2) |which| { if (try reader.int(u8) != 0) { const volume = self.volumes[which] orelse return error.NoHardDisk; try reader.value(zig65.blockdevice.Volume, volume); } } inline for (0..2) |which| { if (try reader.int(u8) != 0) { const blocks = self.unidisk_blocks[which] orelse return error.NoUniDisk; if (try reader.int(u64) != blocks.len) return error.WrongMachine; try reader.raw(blocks); } } }
pub fn eject(self: *Self, drive: Drive) void { // Taking a disk out is when what was written to it goes back. self.save(drive); const which: usize = switch (drive) { .three_and_a_half => 0, .five_and_a_quarter => 1, }; if (self.disk_paths[which]) |path| self.gpa.free(path); self.disk_paths[which] = null; switch (drive) { .three_and_a_half => { _ = self.cpu.memory.iwm.disks35.eject(0); self.slots[0].len = 0; }, .five_and_a_quarter => { _ = self.cpu.memory.iwm.drives.eject(0); self.slots[1].len = 0; }, } self.say("the {s} drive is empty", .{drive.name()}); }
/// Puts a freshly formatted blank disk in the named drive, so a game that /// wants a scratch disk to save to has one without a file to make first. /// /// The size follows the drive, since the two are not interchangeable: an /// 800K ProDOS volume for the 3.5-inch drive, a 140K DOS 3.3 disk for the /// 5.25-inch one. A blank is always writable — there is no file behind it /// to save back over, so the read-only question does not arise — and its /// changes live until it is ejected. pub fn insertBlank(self: *Self, drive: Drive) void { switch (drive) { .three_and_a_half => { const image = self.gpa.alloc(u8, disk35.image_size) catch return; defer self.gpa.free(image); _ = zig65.prodos.Volume.format(image, "BLANK") catch return; self.floppy35.load(image) catch return; self.floppy35.write_protected = false; self.cpu.memory.iwm.disks35.insert(0, self.floppy35); self.slots[0].set("blank ProDOS 800K"); self.say("{s} in the 3.5-inch drive", .{self.slots[0].shown()}); }, .five_and_a_quarter => { const image = self.gpa.alloc(u8, disk2.image_size) catch return; defer self.gpa.free(image); _ = zig65.dos33.Disk.format(image, 254) catch return; self.floppy.load(image, .dos) catch return; self.floppy.write_protected = false; self.cpu.memory.iwm.drives.insert(0, self.floppy); self.slots[1].set("blank DOS 3.3 disk"); self.say("{s} in the 5.25-inch drive", .{self.slots[1].shown()}); }, } }
pub fn say(self: *Self, comptime format: []const u8, args: anytype) void { const written = std.fmt.bufPrint(&self.message, format, args) catch self.message[0..]; self.message_len = written.len; }
/// Runs one instruction and says what became of it. /// /// A 65816 stops for different reasons than a 6502 does, and the /// difference is worth stating rather than papering over. The NMOS part's /// JAM opcodes are *undefined encodings* that wedge the processor by /// accident; this processor has no undefined encodings at all -- all 256 /// decode -- and the only thing that stops its clock is `STP`, which is an /// instruction whose whole purpose is to do that until the reset line /// moves. So `stopped` on the core is a flag rather than an error, and it /// is asked about rather than caught. Both leave a machine that only a /// reset starts, so both are shown the same way. pub fn step(self: *Self) void { // Taken before the step, because executing an opcode moves the program // counter past it -- and with the bank, since a program counter on // this processor does not say which of the two hundred and fifty-six // banks it is counting in. const address = self.cpu.program_counter.address();
// Nothing in this core raises any of the three. The 256 encodings all // decode, since a 65816 has no undefined ones; STP sets the flag asked // about below rather than raising Jam; and **BRK is a real interrupt // here rather than an error**, which is the one place this debugger // differs from the eight-bit one and is worth being plain about. The // eight-bit core hands BRK back to its caller so the debugger can stop // on it, which is what a BRK is usually planted for. This core does // what the processor does: pushes the bank, the address and the flags // and vectors, and carries on. So a IIgs stops on STP and not on BRK, // and the arm below would work if that ever changed. self.cpu.executeInstruction() catch |err| { switch (err) { error.Break => { self.state = .single_step; self.stopped = .{ .brk = .{ .address = address, .vector = self.cpu.program_counter.address(), } }; }, error.IllegalOpcode, error.Jam => unreachable, } return; };
// And the one that is a flag rather than an error. It is asked after // the step rather than before, so the address reported is the STP // itself and not the instruction that would have followed it. if (self.cpu.stopped) { self.state = .halted; self.stopped = .{ .jam = .{ .address = address, .opcode = self.cpu.memory.peek(address), } }; return; }
// The instruction ran to completion, so whatever stopped the processor // last time is no longer what it is doing now. self.stopped = null; }
/// Starts it running, timing the first instruction from now rather than /// from whenever the state was last left -- otherwise a machine that had /// been sitting halted for a minute would owe a minute of cycles and run /// flat out to catch up. pub fn start(self: *Self) void { if (self.state == .halted) return; self.state = .running; self.owed = 0; self.last_step = .now(self.io, pacing_clock); }
/// What the reset key does. A halted processor is the one machine this /// rescues, and it comes back stopped rather than running, so that whoever /// was looking at where it jammed can see what the reset made of it. pub fn reset(self: *Self) void { self.cpu.reset(); self.stopped = null; if (self.state == .halted) self.state = .single_step; }
/// Runs whatever the time that has gone by is worth, and hands keys over /// as the machine becomes ready for them rather than once a frame, so that /// typing keeps pace with the machine rather than with the display. pub fn stepDue(self: *Self) void { // A machine that is not running owes nothing, and must not be allowed // to accumulate a debt while it is stopped: the clock still moves, and // without this a machine paused for a minute would sprint on release. if (self.state != .running) { self.last_step = .now(self.io, pacing_clock); self.owed = 0; self.pumpSerial(); return; } const now: std.Io.Timestamp = .now(self.io, pacing_clock); const deadline = now.nanoseconds + step_budget_ns; const elapsed = now.nanoseconds - self.last_step.nanoseconds; self.last_step = now; self.owed += @divFloor(elapsed * @as(i96, @intCast(self.target_hz)), std.time.ns_per_s); // A machine that has fallen behind does not owe the whole of however // long it was behind for: carrying that forward would only make the // next frame later still. // A machine that has fallen behind does not owe the whole of however // long it was behind for: carrying that forward would only make the // next frame later still. Two frames rather than one, though, because // drawing a frame costs a millisecond or two of the sixteen and with a // one-frame ceiling that time is lost for good — the machine ran at // eighty-seven per cent of its speed and never caught any of it up. // Two lets it make back a frame's jitter and no more. const most = @divFloor(@as(i96, @intCast(self.target_hz)) * 2 * frame_ns, std.time.ns_per_s); if (self.owed > most) self.owed = most;
var since_check: usize = 0; while (self.state == .running and self.owed > 0) { const before = self.cpu.clock.cycles; self.step(); self.owed -= @intCast(self.cpu.clock.cycles -| before); self.feedKeyboard(); since_check += 1; if (since_check < 4096) continue; since_check = 0; // However far behind it is, the loop still has to get back to the // terminal: a machine nobody can type at is not going faster. if (std.Io.Timestamp.now(self.io, pacing_clock).nanoseconds > deadline) break; } self.pumpSerial(); }
/// Moves bytes each way along the modem port's wire. /// /// Out is whatever the machine has sent since the last look. In is paced: /// a byte goes in only when the chip has room for one and enough time has /// passed for one to have arrived at the rate the chip was set to, since a /// port that hands over its input as fast as the machine will take it is /// not a serial port at all — the same bargain the Super Serial Card in /// the eight-bit machines makes. pub fn pumpSerial(self: *Self) void { self.pumpNetwork(); self.pumpEthernet(); self.pumpCs8900(); // The printer port first, which only goes one way. if (self.printer_out) |file| { const printer = self.cpu.memory.scc.channelOf(.a); const printed = printer.sent(); if (printed.len > 0) { file.writeStreamingAll(self.io, printed) catch {}; printer.consume(printed.len); } }
const port = self.cpu.memory.scc.channelOf(.b); if (self.modem != null) return self.pumpModem(port); if (self.serial_out) |file| { const sent = port.sent(); if (sent.len > 0) { file.writeStreamingAll(self.io, sent) catch {}; port.consume(sent.len); } } if (self.serial_in) |bytes| { while (self.serial_in_at < bytes.len and port.receiving() and self.cpu.clock.cycles >= self.serial_in_due) { _ = port.receive(bytes[self.serial_in_at]); self.serial_in_at += 1; self.serial_in_due = self.cpu.clock.cycles + port.cyclesPerByte(self.cpu.memory.scc.cycles_per_second); } } }
/// The modem on the SCC's modem port, driven the way `session8.zig`'s is on /// the Super Serial Card: the machine's bytes go to the modem, the modem's /// come back paced by the port's rate, and what it dials crosses the host's /// TCP. `port` is the SCC's channel B. fn pumpModem(self: *Self, port: anytype) void { const mdm = &(self.modem.?); const cps = self.cpu.memory.scc.cycles_per_second; const cycle = self.cpu.clock.cycles; mdm.cycles_per_tick = cps / 50; self.modem_line.connect_rate = port.rate();
const sent = port.sent(); for (sent) |byte| mdm.fromMachine(byte, cycle); if (sent.len > 0) port.consume(sent.len); mdm.tick(cycle);
switch (mdm.takeWants()) { .nothing => {}, .dial => |d| self.modem_line.dial(d.host, d.port), .hangup => self.modem_line.hangup(), .answer => {}, } self.modem_line.pump(mdm);
while (mdm.to_machine_len > 0 and cycle >= self.modem_in_due) { if (!port.receiving()) break; _ = port.receive(mdm.machineBytes()[0]); mdm.takeMachine(1); self.modem_in_due = cycle + port.cyclesPerByte(cps); } }
/// Moves frames between the chip and the network, both ways. What the /// machine sent goes to the group, minus the handshake the bridge answers /// itself; what the group sent goes onto the chip's wire, minus the /// machine's own frames coming back. A frame arriving is queued on the /// chip and takes its time to arrive from there, byte by byte, which is /// how the firmware's interrupt handler finds the frame's second byte /// behind its first as it expects to. pub fn pumpNetwork(self: *Self) void { const net = &(self.network orelse return); const now = self.cpu.clock.cycles; const scc = &self.cpu.memory.scc; if (self.network_log) |file| { if (net.bridge.attach(scc)) |which| { for (scc.channelOf(which).sentFrames()) |frame| self.logFrame(file, "out", frame.payload()); } } net.bridge.drain(scc, now, net); var buffer: [zig65.localtalk.longest]u8 = undefined; // A few at a time: the machine is paced by the frame it is drawing, // and a group with a great deal to say has to say it at the rate a // cable would carry it. for (0..8) |_| { const datagram = net.receive(&buffer) orelse break; const before = net.bridge.received; net.bridge.deliver(scc, datagram, now); if (self.network_log) |file| if (net.bridge.received != before) { self.logFrame(file, "in ", datagram[zig65.localtalk.tag_len..]); }; } }
/// Whether this machine can hold an Uthernet II. pub fn hasEthernet() bool { return @hasDecl(CPU.Memory, "ethernetChip"); }
/// Drives the Uthernet II's host sockets one step, the way `pumpNetwork` /// drives LocalTalk: takes what each of the W5100's sockets wants done, /// does it against the machine's own sockets, and moves bytes each way. /// Quiet — and free — until a card is fitted and a socket is opened. pub fn pumpEthernet(self: *Self) void { if (comptime hasEthernet()) { if (self.cpu.memory.ethernetChip()) |chip| self.uthernet.pump(chip); } }
/// Whether this machine can hold an Uthernet (its CS8900A). pub fn hasCs8900() bool { return @hasDecl(CPU.Memory, "cs8900Chip"); }
/// Moves Ethernet frames each way for an Uthernet, the way `pumpEthernet` /// moves the Uthernet II's sockets: the CS8900A's queued frame onto the /// multicast group, and frames from the group addressed to the card into /// the chip. pub fn pumpCs8900(self: *Self) void { if (comptime hasCs8900()) { const bridge = &(self.ethernet orelse return); const chip = self.cpu.memory.cs8900Chip() orelse return; if (chip.sent()) |frame| { bridge.send(frame); chip.didSend(); } var buffer: [zig65.cs8900.max_frame]u8 = undefined; while (chip.canReceive()) { const frame = bridge.receive(&buffer) orelse break; if (zig65.ethernet.addressedTo(frame, chip.mac())) chip.receive(frame); } } }
pub fn logFrame(self: *Self, file: std.Io.File, direction: []const u8, bytes: []const u8) void { var line: [3 * zig65.scc.Scc.Frame.longest + 48]u8 = undefined; var w: std.Io.Writer = .fixed(&line); w.print("{d} {s}", .{ self.cpu.clock.cycles, direction }) catch return; for (bytes) |byte| w.print(" {x:0>2}", .{byte}) catch return; w.writeByte('\n') catch return; file.writeStreamingAll(self.io, w.buffered()) catch {}; }
/// Gives the machine the next key when it is asking for one and has come /// away empty a few times, which is what a machine sitting in a read loop /// looks like from outside. pub fn feedKeyboard(self: *Self) void { if (self.typed_len == 0) return; const mega2 = &self.cpu.memory.mega2; if (mega2.strobe or mega2.empty_polls < 8) return; const held: u8 = (if (self.apple[0]) zig65.adb.Adb.Modifier.command else 0) | (if (self.apple[1]) zig65.adb.Adb.Modifier.option else 0); self.cpu.memory.adb.modifiers = self.typed_mods[0] | held; mega2.pressKey(self.typed[0]); std.mem.copyForwards(u8, self.typed[0 .. self.typed_len - 1], self.typed[1..self.typed_len]); std.mem.copyForwards(u8, self.typed_mods[0 .. self.typed_len - 1], self.typed_mods[1..self.typed_len]); self.typed_len -= 1; }
pub fn frameDue(self: *Self) bool { const now: std.Io.Timestamp = .now(self.io, pacing_clock); if (now.nanoseconds < self.next_frame.nanoseconds) return false; self.next_frame.nanoseconds += frame_ns; if (self.next_frame.nanoseconds < now.nanoseconds) self.next_frame.nanoseconds = now.nanoseconds + frame_ns; return true; }
pub fn measureSpeed(self: *Self) void { const now: std.Io.Timestamp = .now(self.io, pacing_clock); const elapsed = now.nanoseconds - self.measured_at.nanoseconds; if (elapsed < 500 * std.time.ns_per_ms) return; const cycles = self.cpu.clock.cycles -| self.measured_cycles; self.measured_hz = @as(f64, @floatFromInt(cycles)) / (@as(f64, @floatFromInt(elapsed)) / std.time.ns_per_s); self.measured_at = now; self.measured_cycles = self.cpu.clock.cycles; }
/// Holds one of the two Apple keys down, or lets it go. /// /// Each is two things at once on this machine: a modifier bit that a IIgs /// program reads at `$c025`, and one of the game connector's buttons that /// an Apple II program reads at `$c061`. Both have to be told. pub fn holdApple(self: *Self, which: u1) void { const down = !self.apple[which]; self.apple[which] = down; self.cpu.memory.adb.hold( if (which == 0) zig65.adb.Adb.Modifier.command else zig65.adb.Adb.Modifier.option, down, ); // And the game connector's button, which is the other half of what // these two keys are. self.cpu.memory.mega2.setButton(which, down); self.say("{s} apple {s}", .{ if (which == 0) "open" else "solid", if (down) "held" else "let go", }); }
/// Puts an image in one of the hard disk's two drives. /// /// It is write enabled, because a hard disk that cannot be written to is /// not much of one, and it is written back when the machine stops. pub fn mount(self: *Self, which: u1, path: []const u8) !void { const file = try std.Io.Dir.cwd().readFileAlloc(self.io, path, self.gpa, .unlimited); const opened = try diskfile.open(self.gpa, file, path); const image = opened.image;
// A disk that came out of an archive is let go of straight away and // what is kept is the disk that came out of it. It is writable like // any other hard disk now, since write-back re-archives the disk into // the file rather than writing the raw blocks over it. var keep = file; const locked = image.write_protected; if (opened.owned) |unpacked| { self.gpa.free(file); keep = unpacked; }
const volume = try self.gpa.create(zig65.blockdevice.Volume); volume.* = .{ .image = image.data, .write_protected = locked }; self.volumes[which] = volume; self.volume_files[which] = keep; self.volume_paths[which] = path; self.volume_slots[which].set(path); self.cpu.memory.insertVolume(which, volume); }
/// Saves whatever the machine wrote and puts the disks away. pub fn unmountAll(self: *Self) void { for (0..2) |which| { const volume = self.volumes[which] orelse continue; const file = self.volume_files[which] orelse volume.image; if (volume.dirty and !volume.write_protected) { if (self.volume_paths[which]) |path| { // The whole file, wrapper and all: the volume is a slice // of it, so a 2IMG keeps its header. std.Io.Dir.cwd().writeFile(self.io, .{ .sub_path = path, .data = file, }) catch |err| std.debug.print( "gs: could not write {s} back: {s}\n", .{ path, @errorName(err) }, ); } } self.cpu.memory.insertVolume(@intCast(which), null); self.gpa.free(file); self.gpa.destroy(volume); self.volumes[which] = null; self.volume_files[which] = null; } }
/// Lets go of everything the session opened: the disks written back and /// taken out, the recording's header put right, and every file closed. /// The processor itself and the front end's own display are let go of by /// whoever built them. pub fn deinit(self: *Self) void { // Both floppies as well as the volumes: the drives are emptied, which // is what saves them. self.eject(.three_and_a_half); self.eject(.five_and_a_quarter); self.ejectUnidisk(0); self.ejectUnidisk(1); self.unmountAll(); if (self.recording) |rec| if (rec.file) |file| file.finish(self.io, self.gpa); self.recording = null; if (self.serial_out) |file| file.close(self.io); self.serial_out = null; if (self.serial_in) |bytes| self.gpa.free(bytes); self.serial_in = null; if (self.printer_out) |file| file.close(self.io); self.printer_out = null; if (self.network) |*net| net.close(); self.network = null; if (self.network_log) |file| file.close(self.io); self.network_log = null; // Closes whatever host sockets the Uthernet II left open. self.uthernet.deinit(); // And leaves the Uthernet's multicast group. if (self.ethernet) |*bridge| bridge.close(); self.ethernet = null; // Hangs up the modem, if one was dialing. self.modem_line.deinit(); }};
const testing = std.testing;
/// Brings up a session with nothing in it but a processor, for the tests/// below. A real one is assembled field by field by the front end, which is/// why this is here rather than a constructor on the type: there is no one/// shape a session is made in.fn bareSession(gpa: std.mem.Allocator, cpu: *CPU) Session { return .{ .io = testing.io, .gpa = gpa, .cpu = cpu, .floppy35 = undefined, .floppy = undefined, };}
test "a stopped machine runs nothing, and starting it does not make it owe time" { const gpa = testing.allocator; const cpu = try gpa.create(CPU); defer gpa.destroy(cpu); try cpu.init(gpa, null); defer cpu.deinit();
var session = bareSession(gpa, cpu); session.state = .single_step; session.last_step = .now(session.io, pacing_clock);
// Time passes and the machine does not: a debt would be a machine that // sprinted the moment it was let go, which is what `owed` being reset on // every stopped look prevents. session.last_step = .{ .nanoseconds = session.last_step.nanoseconds - std.time.ns_per_s }; const before = cpu.clock.cycles; session.stepDue(); try testing.expectEqual(before, cpu.clock.cycles); try testing.expectEqual(@as(i96, 0), session.owed);
session.start(); try testing.expectEqual(State.running, session.state); try testing.expectEqual(@as(i96, 0), session.owed);}
test "one step is one instruction, however many cycles that takes" { const gpa = testing.allocator; const cpu = try gpa.create(CPU); defer gpa.destroy(cpu); try cpu.init(gpa, null); defer cpu.deinit();
var session = bareSession(gpa, cpu); session.state = .single_step;
// NOP, twice. Written into bank zero, which is where the processor comes // up: a 65816 resets into emulation mode in bank zero, so this is the // 6502's address space until something says otherwise. cpu.memory.poke(0x0300, 0xea); cpu.memory.poke(0x0301, 0xea); cpu.program_counter.jump(0x0300);
session.step(); try testing.expectEqual(@as(u16, 0x0301), cpu.program_counter.value); session.step(); try testing.expectEqual(@as(u16, 0x0302), cpu.program_counter.value); // And nothing about either was worth stopping for. try testing.expect(session.stopped == null); try testing.expectEqual(State.single_step, session.state);}
test "STP halts the machine and says where, and only a reset starts it again" { const gpa = testing.allocator; const cpu = try gpa.create(CPU); defer gpa.destroy(cpu); try cpu.init(gpa, null); defer cpu.deinit();
var session = bareSession(gpa, cpu); session.state = .running;
cpu.memory.poke(0x0400, 0xdb); // STP cpu.program_counter.jump(0x0400); session.step();
// Halted, and pointing at the instruction that did it rather than at the // byte after it -- which is the whole reason the address is taken before // the step. try testing.expectEqual(State.halted, session.state); try testing.expect(session.stopped != null); switch (session.stopped.?) { .jam => |jam| { try testing.expectEqual(@as(u24, 0x000400), jam.address); try testing.expectEqual(@as(u8, 0xdb), jam.opcode); }, .brk => return error.WrongReason, }
// A halted processor cannot be started. That is what halted means. session.start(); try testing.expectEqual(State.halted, session.state);
// The reset key is the way out, and it leaves the machine stopped rather // than running, so that whoever was looking can see what it made of it. session.reset(); try testing.expectEqual(State.single_step, session.state); try testing.expect(session.stopped == null); try testing.expect(!cpu.stopped);}
test "BRK on this processor is an interrupt, not a stop" { // The eight-bit debugger stops on a BRK, because a BRK is usually planted // to stop something. This one does not, and the reason is in the core // rather than here: `cpu16`'s BRK pushes the bank, the address and the // flags and vectors through the handler, exactly as the silicon does, // where `cpu8`'s hands the instruction back to its caller. So a IIgs is // stopped by STP and by the user, and by nothing else. const gpa = testing.allocator; const cpu = try gpa.create(CPU); defer gpa.destroy(cpu); try cpu.init(gpa, null); defer cpu.deinit();
var session = bareSession(gpa, cpu); session.state = .running;
cpu.memory.poke(0x0500, 0x00); // BRK cpu.program_counter.jump(0x0500); session.step();
try testing.expectEqual(State.running, session.state); try testing.expect(session.stopped == null); // And it went somewhere: through the vector, rather than on to the next // instruction. try testing.expect(cpu.program_counter.value != 0x0502);}