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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! A clock card, of the kind ProDOS knows how to ask the time of.//!//! The machine has no clock of its own: an Apple II that has been switched on//! knows nothing about when it is, which is why ProDOS stamps a file with no//! date at all unless a card can tell it. ProDOS looks through the slots for//! four bytes in a card's ROM, and having found them calls the card's own//! firmware, which leaves the date and time as text where the machine reads a//! typed line from. That is the whole of the arrangement, and it is what this//! answers to.//!//! The card keeps time by the machine's own cycles rather than by the host's//! clock, so a machine run faster than a real one sees time pass at the rate//! it is being run at, and one that is paused sees it stop. What it says is//! whatever the host last set, plus the seconds that have gone by since.//!//! The ProDOS 8 Technical Reference is where the arrangement below comes from//! (Apple Computer, Inc., n.d.-d, Chapter 6): the signature, the two entry//! points, and the string.
const std = @import("std");const testing = std.testing;
/// What a IIe runs at, which is what the seconds are counted in.pub const cycles_per_second = 1_020_500;
/// The four bytes ProDOS looks for, at $Cn00, $Cn02, $Cn04 and $Cn06. They are/// ordinary instructions on the real card, and they are here too.pub const signature = [_]u8{ 0x08, 0x28, 0x58, 0x70 };
/// Where the string goes: the buffer the machine reads a typed line into,/// which is free while ProDOS is asking the time.pub const buffer = 0x0200;
/// The string is the month, the day of the week, the date, the hour, the/// minute and the second, each two digits, separated by commas. ProDOS reads/// the first five and ignores the last, which is there because the card that/// set the convention sent it.pub const string_length = "mo,da,dt,hr,mn,ss".len;
/// A moment, as the card keeps it.pub const Time = struct { year: u16 = 1970, month: u4 = 1, day: u5 = 1, hour: u5 = 0, minute: u6 = 0, second: u6 = 0,
/// Seconds since the start of 1970, which is only ever a way of getting /// from one of these to another. pub fn toEpoch(self: Time) i64 { const days = daysFromCivil(self.year, self.month, self.day); return ((days * 24 + self.hour) * 60 + self.minute) * 60 + self.second; }
pub fn fromEpoch(seconds: i64) Time { const days = @divFloor(seconds, 24 * 60 * 60); const within = seconds - days * 24 * 60 * 60; const civil = civilFromDays(days); return .{ .year = @intCast(civil.year), .month = @intCast(civil.month), .day = @intCast(civil.day), .hour = @intCast(@divTrunc(within, 60 * 60)), .minute = @intCast(@divTrunc(@mod(within, 60 * 60), 60)), .second = @intCast(@mod(within, 60)), }; }
/// Sunday is nought, which is how the card counts and how ProDOS reads it. /// /// ProDOS needs this because the string carries no year at all: the clock /// this stands for had none in it, so ProDOS takes the month and the date /// as given and works the year out from the day of the week they fall on. /// It arrives at a year of its own choosing rather than the real one — /// told a Tuesday the first of September it answers 2020, and told a /// Thursday the first of September it answers 2022 — and there is nothing /// a card can do about it, which is why ProDOS needed a new driver when /// its guesses ran out. The day here is the real one for the date, which /// is what a real card sends. pub fn weekday(self: Time) u3 { const days = daysFromCivil(self.year, self.month, self.day); // The first of January 1970 was a Thursday. return @intCast(@mod(days + 4, 7)); }};
/// Days from the start of 1970 to a date, and back again. The arithmetic is/// the usual one for a proleptic Gregorian calendar, which counts from March/// so that the leap day falls at the end of a year rather than in the middle.fn daysFromCivil(year: u16, month: u4, day: u5) i64 { const y: i64 = @as(i64, year) - @intFromBool(month <= 2); const era = @divFloor(y, 400); const year_of_era = y - era * 400; const shifted: i64 = if (month > 2) @as(i64, month) - 3 else @as(i64, month) + 9; const day_of_year = @divTrunc(153 * shifted + 2, 5) + day - 1; const day_of_era = year_of_era * 365 + @divTrunc(year_of_era, 4) - @divTrunc(year_of_era, 100) + day_of_year; return era * 146097 + day_of_era - 719468;}
fn civilFromDays(days: i64) struct { year: i64, month: i64, day: i64 } { const z = days + 719468; const era = @divFloor(z, 146097); const day_of_era = z - era * 146097; const year_of_era = @divTrunc( day_of_era - @divTrunc(day_of_era, 1460) + @divTrunc(day_of_era, 36524) - @divTrunc(day_of_era, 146096), 365, ); const y = year_of_era + era * 400; const day_of_year = day_of_era - (365 * year_of_era + @divTrunc(year_of_era, 4) - @divTrunc(year_of_era, 100)); const shifted = @divTrunc(5 * day_of_year + 2, 153); const day = day_of_year - @divTrunc(153 * shifted + 2, 5) + 1; const month = shifted + (if (shifted < 10) @as(i64, 3) else -9); return .{ .year = y + @intFromBool(month <= 2), .month = month, .day = day };}
/// The card itself: what the host set, when it was set, and whichever string/// the firmware is in the middle of handing over.pub const Card = struct { /// Whether there is a card in the slot at all. A machine without one is a /// machine that does not know the date, which is the ordinary case. fitted: bool = false, /// The time the host last set, as seconds, and the cycle it was set at. epoch: i64 = 0, set_at: u64 = 0, /// The string being read out, and how far the firmware has got through it. reading: [string_length]u8 = @splat(0), read_at: u8 = string_length, /// The string being handed back, for a program that sets the time. writing: [string_length]u8 = @splat(0), write_at: u8 = 0,
/// What the ROM answers to. Reading the first register hands over one /// character of the string and moves on; the second starts a fresh /// reading, which is what the firmware does before it begins. pub const Register = enum(u4) { character = 0, start = 1, _, };
pub fn set(self: *Card, when: Time, cycles: u64) void { self.epoch = when.toEpoch(); self.set_at = cycles; }
/// The time now, which is what was set plus the seconds the machine has /// run since. pub fn now(self: *const Card, cycles: u64) Time { const passed: i64 = @intCast((cycles -| self.set_at) / cycles_per_second); return .fromEpoch(self.epoch + passed); }
/// Takes a reading, which is what a program asking the time starts with. pub fn start(self: *Card, cycles: u64) void { const when = self.now(cycles); _ = std.fmt.bufPrint(&self.reading, "{d:0>2},{d:0>2},{d:0>2},{d:0>2},{d:0>2},{d:0>2}", .{ @as(u8, when.month), @as(u8, when.weekday()), @as(u8, when.day), @as(u8, when.hour), @as(u8, when.minute), @as(u8, when.second), }) catch unreachable; self.read_at = 0; self.write_at = 0; }
/// The next character, with the high bit set the way the machine holds /// text, and nought once there is no more. pub fn character(self: *Card) u8 { if (self.read_at >= string_length) return 0; defer self.read_at += 1; return self.reading[self.read_at] | 0x80; }
/// A character of a string a program is setting the time from. The clock /// this stands for had no year in it, so setting one leaves the year as it /// was and moves everything else. pub fn accept(self: *Card, byte: u8, cycles: u64) void { if (self.write_at >= string_length) return; self.writing[self.write_at] = byte & 0x7f; self.write_at += 1; if (self.write_at < string_length) return;
const number = struct { fn at(text: []const u8, offset: usize) ?u8 { return std.fmt.parseInt(u8, text[offset..][0..2], 10) catch null; } }; const was = self.now(cycles); const month = number.at(&self.writing, 0) orelse return; const day = number.at(&self.writing, 6) orelse return; const hour = number.at(&self.writing, 9) orelse return; const minute = number.at(&self.writing, 12) orelse return; const second = number.at(&self.writing, 15) orelse return; if (month < 1 or month > 12 or day < 1 or day > 31) return; if (hour > 23 or minute > 59 or second > 59) return; self.set(.{ .year = was.year, .month = @intCast(month), .day = @intCast(day), .hour = @intCast(hour), .minute = @intCast(minute), .second = @intCast(second), }, cycles); }
pub fn access(self: *Card, offset: u4, is_write: bool, value: u8, cycles: u64) u8 { return switch (@as(Register, @enumFromInt(offset))) { .character => if (is_write) put: { self.accept(value, cycles); break :put 0; } else self.character(), .start => take: { self.start(cycles); break :take 0; }, else => 0, }; }};
/// The card's ROM, which is ours: nothing has to be supplied for this card to/// work, since what a clock card has to do is published.////// The four bytes ProDOS reads are at $Cn00, $Cn02, $Cn04 and $Cn06 and are/// ordinary instructions, so the page can be run into as well as looked at./// The two entry points are where ProDOS calls them, three bytes apart.pub fn firmware(comptime slot: u4) [256]u8 { const io = 0xc080 + @as(u16, slot) * 0x10; const lo: u8 = @truncate(io); const hi: u8 = @truncate(io >> 8); const page: u8 = 0xc0 + @as(u8, slot); const read_at = 0x20; const write_at = 0x40;
var rom: [256]u8 = @splat(0);
const head = [_]u8{ 0x08, // $Cn00 PHP the signature, and code 0x18, // CLC 0x28, // $Cn02 PLP the signature 0x18, // CLC 0x58, // $Cn04 CLI the signature 0x18, // CLC 0x70, 0x00, // $Cn06 BVS +0 the signature; either way on 0x4c, read_at, page, // $Cn08 JMP read 0x4c, write_at, page, // $Cn0b JMP write }; @memcpy(rom[0..head.len], &head);
// Reading: take a fresh reading, then copy characters into the line buffer // until the card says there are no more. const read = [_]u8{ 0xad, lo + 1, hi, // LDA start 0xa0, 0x00, // LDY #$00 0xad, lo, hi, // loop: LDA character 0xf0, 0x08, // BEQ done 0x99, 0x00, 0x02, // STA $0200,Y 0xc8, // INY 0xc0, string_length, // CPY #length 0x90, 0xf3, // BCC loop 0x60, // done: RTS }; @memcpy(rom[read_at..][0..read.len], &read);
// Writing: hand the card what is in the line buffer, which is how a // program sets the time. const write = [_]u8{ 0xad, lo + 1, hi, // LDA start 0xa0, 0x00, // LDY #$00 0xb9, 0x00, 0x02, // loop:LDA $0200,Y 0x8d, lo, hi, // STA character 0xc8, // INY 0xc0, string_length, // CPY #length 0x90, 0xf5, // BCC loop 0x60, // RTS }; @memcpy(rom[write_at..][0..write.len], &write);
comptime { // The signature has to be where ProDOS looks, and the entry points // where it calls them. std.debug.assert(head[0x00] == signature[0]); std.debug.assert(head[0x02] == signature[1]); std.debug.assert(head[0x04] == signature[2]); std.debug.assert(head[0x06] == signature[3]); std.debug.assert(head[0x08] == 0x4c and head[0x0b] == 0x4c); // And the pieces must not run into one another. std.debug.assert(head.len <= read_at); std.debug.assert(read_at + read.len <= write_at); std.debug.assert(write_at + write.len <= 0x100); } return rom;}
/// One page for each slot, since a card's ROM has its own slot's addresses/// assembled into it and which slot that is cannot be known until a machine is/// built. Indexed by the slot number, so there are eight of them and the first/// is never read: slot 0 is not a slot, and two hundred and fifty-six wasted/// bytes are cheaper than an off-by-one waiting to happen.pub const firmwares: [8][256]u8 = blk: { var all: [8][256]u8 = undefined; for (0..all.len) |slot| all[slot] = firmware(@intCast(slot)); break :blk all;};
test "a date and the day it fell on" { // Dates whose day of the week is not in doubt: the first of January 1970 // was a Thursday, and this project's own commits are on the days they say. try testing.expectEqual(@as(u3, 4), (Time{ .year = 1970, .month = 1, .day = 1 }).weekday()); try testing.expectEqual(@as(u3, 2), (Time{ .year = 2000, .month = 2, .day = 29 }).weekday()); try testing.expectEqual(@as(u3, 0), (Time{ .year = 2026, .month = 8, .day = 30 }).weekday()); try testing.expectEqual(@as(u3, 2), (Time{ .year = 2026, .month = 9, .day = 1 }).weekday()); // The centuries that are not leap years, and the one that is. try testing.expectEqual(@as(u3, 1), (Time{ .year = 1900, .month = 1, .day = 1 }).weekday()); try testing.expectEqual(@as(u3, 5), (Time{ .year = 2100, .month = 1, .day = 1 }).weekday());}
test "a moment survives being counted in seconds" { const moments = [_]Time{ .{ .year = 1970, .month = 1, .day = 1 }, .{ .year = 1984, .month = 2, .day = 29, .hour = 23, .minute = 59, .second = 59 }, .{ .year = 2026, .month = 9, .day = 1, .hour = 12, .minute = 34, .second = 56 }, .{ .year = 2100, .month = 3, .day = 1, .hour = 6 }, }; for (moments) |when| { const back: Time = .fromEpoch(when.toEpoch()); try testing.expectEqual(when, back); } // And a day is a day. const noon: Time = .{ .year = 2026, .month = 12, .day = 31, .hour = 12 }; const next: Time = .fromEpoch(noon.toEpoch() + 24 * 60 * 60); try testing.expectEqual(@as(u16, 2027), next.year); try testing.expectEqual(@as(u4, 1), next.month); try testing.expectEqual(@as(u5, 1), next.day);}
test "the card keeps time by the machine's own cycles" { var card: Card = .{}; card.set(.{ .year = 2026, .month = 9, .day = 1, .hour = 12, .minute = 0, .second = 0 }, 0);
// Nothing has run, so nothing has passed. try testing.expectEqual(@as(u6, 0), card.now(0).second); // A second of the machine's cycles is a second on the clock. try testing.expectEqual(@as(u6, 1), card.now(cycles_per_second).second); try testing.expectEqual(@as(u6, 30), card.now(30 * cycles_per_second).second); const later = card.now(3600 * cycles_per_second); try testing.expectEqual(@as(u5, 13), later.hour); try testing.expectEqual(@as(u6, 0), later.minute);}
test "the string is the one ProDOS reads" { var card: Card = .{}; // A Thursday, which is the day the ProDOS manual's own example falls on. card.set(.{ .year = 2026, .month = 7, .day = 16, .hour = 22, .minute = 46, .second = 57 }, 0); card.start(0);
var read: [string_length]u8 = undefined; for (&read) |*into| into.* = card.character() & 0x7f; try testing.expectEqualStrings("07,04,16,22,46,57", &read); // And nothing after it, until another reading is taken. try testing.expectEqual(@as(u8, 0), card.character()); card.start(0); try testing.expectEqual(@as(u8, '0' | 0x80), card.character());}
test "a program can set the clock, keeping the year it cannot say" { var card: Card = .{}; card.set(.{ .year = 2026, .month = 1, .day = 1, .hour = 0, .minute = 0, .second = 0 }, 0);
// What the firmware hands back, character by character. card.start(0); for ("03,00,15,09,30,00") |byte| card.accept(byte | 0x80, 0);
const when = card.now(0); try testing.expectEqual(@as(u4, 3), when.month); try testing.expectEqual(@as(u5, 15), when.day); try testing.expectEqual(@as(u5, 9), when.hour); try testing.expectEqual(@as(u6, 30), when.minute); // The clock this stands for had no year in it, so the year is left alone. try testing.expectEqual(@as(u16, 2026), when.year);
// Nonsense is refused rather than kept. card.start(0); for ("99,00,99,99,99,99") |byte| card.accept(byte, 0); try testing.expectEqual(@as(u4, 3), card.now(0).month);}
test "the firmware says what ProDOS looks for" { const rom = firmware(5); // The four bytes, at the four offsets, which is the whole of how ProDOS // decides a slot holds a clock. try testing.expectEqual(signature[0], rom[0x00]); try testing.expectEqual(signature[1], rom[0x02]); try testing.expectEqual(signature[2], rom[0x04]); try testing.expectEqual(signature[3], rom[0x06]); // The two entry points, which are jumps into the page. try testing.expectEqual(@as(u8, 0x4c), rom[0x08]); try testing.expectEqual(@as(u8, 0x4c), rom[0x0b]); try testing.expectEqual(@as(u8, 0xc5), rom[0x0a]); // The registers it reaches for are the slot's own: $c0d0 and $c0d1 for // slot 5, which is $c080 plus sixteen a slot. try testing.expectEqual(@as(u8, 0xad), rom[0x20]); try testing.expectEqual(@as(u8, 0xd1), rom[0x21]); try testing.expectEqual(@as(u8, 0xc0), rom[0x22]); try testing.expectEqual(@as(u8, 0xad), rom[0x25]); try testing.expectEqual(@as(u8, 0xd0), rom[0x26]); try testing.expectEqual(@as(u8, 0xc0), rom[0x27]);}
test "there is a page of firmware for every slot, and each is that slot's" { // See the same test in `blockdevice.zig`. inline for (0..firmwares.len) |slot| { try testing.expectEqualSlices(u8, &firmware(slot), &firmwares[slot]); } try testing.expect(!std.mem.eql(u8, &firmwares[5], &firmwares[1]));}