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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! The 2IMG wrapper, which is a disk image that says what it is.//!//! Every other image format this program reads is a bare dump: so many bytes,//! and nothing in them to say which way round the sectors are, whether the//! disk was write protected, or even which kind of drive it came out of. The//! sector order has to be guessed from the file's name — `.po` one way, `.do`//! and `.dsk` the other — and a file renamed on its way through a machine that//! did not care carries the wrong answer for the rest of its life.//!//! 2IMG fixes that by putting sixty-four bytes in front of the data. The//! useful ones are the four-character mark `2IMG` at the start, the *format*,//! which says whether what follows is in DOS order, ProDOS order or raw//! nibbles; a flags word whose top bit is the write-protect tab; and the//! offset and length of the data itself, which is what makes the header a//! wrapper rather than a fixed prefix. Everything here reads those and hands//! back a slice of the caller's own bytes, so a program that wants to write//! the disk back to its file writes the whole buffer and the header comes//! along unchanged.//!//! The format was written by Apple II people rather than by Apple, and it//! shows in the good way: it is one page long, it is unambiguous, and the//! fields that were not thought through are marked as such rather than//! reserved for a future that never came. See the bibliography.
const std = @import("std");
const disk2 = @import("disk2.zig");
/// The four bytes at the start of the file, and the four after them that say/// which program wrote it. The creator is not acted on — it is there so that a/// person looking at a file can tell where it came from — but reading it is/// how the header length is known to be trustworthy.pub const magic = "2IMG";
/// How long the header is. The field is in the header, because a later version/// might make it longer, so this is the smallest it can be rather than the/// size of it.pub const header_size = 64;
/// What the data after the header is.pub const Format = enum(u32) { /// Sectors in the order DOS 3.3 numbered them, which is what a `.dsk` or /// `.do` holds. dos = 0, /// Blocks end to end, which is what a `.po` holds and what every 3.5-inch /// image and every hard disk image is. prodos = 1, /// The nibbles as they come off the head, already encoded. A drive takes /// these as they are: see `disk2.Floppy.loadNibbles`. nibble = 2, /// Not a 2IMG format at all: what `diskfile` marks a WOZ with, since a /// recording of the bits is a fourth kind of thing and the enum is where /// the kinds are named. woz = 3, _,};
pub const Error = error{ /// The first four bytes are not `2IMG`. NotTwoImg, /// The header says the data is somewhere the file does not reach. Truncated,};
/// A file with the wrapper taken off.pub const Image = struct { /// The disk itself: a slice of the bytes handed in, so writing to it /// writes to the file's buffer and the header is still in front of it. data: []u8, format: Format, /// Whether the write-protect tab is on, which is the top bit of the flags. write_protected: bool, /// The DOS 3.3 volume number, when the file bothered to record one. The /// flags have a bit that says whether the low byte means anything, which /// is the difference between "volume 0" and "nobody wrote it down". volume_number: ?u8, /// How many blocks the header says there are. Only meaningful for a /// ProDOS-order image, and only a cross-check even then: the length of the /// data is what is actually used, since that is what has to be there. blocks: u32,
/// Whether this is a recording of the surface rather than a description of /// the sectors on it. pub fn isNibble(self: Image) bool { return self.format == .nibble; }
/// Whether this is a recording of the bits themselves. pub fn isWoz(self: Image) bool { return self.format == .woz; }
/// Which sector order to read the data in, for anything that wants one. /// A nibble image is neither, and says so. pub fn order(self: Image) ?disk2.Order { return switch (self.format) { .dos => .dos, .prodos => .prodos, else => null, }; }};
/// Takes the wrapper off, or says the file has none.////// Nothing is copied and nothing is allocated: what comes back points into the/// bytes handed in.pub fn open(bytes: []u8) Error!Image { if (bytes.len < header_size) return error.NotTwoImg; if (!std.mem.eql(u8, bytes[0..4], magic)) return error.NotTwoImg;
const flags = std.mem.readInt(u32, bytes[16..20], .little); const blocks = std.mem.readInt(u32, bytes[20..24], .little); const from = std.mem.readInt(u32, bytes[24..28], .little); const stated = std.mem.readInt(u32, bytes[28..32], .little);
if (from > bytes.len) return error.Truncated; // Sweet16, whose creator code is `WOOF`, writes a zero in the data length // of every image it makes and puts the size in the block count instead; // a whole shelf of 800K disks is wrapped that way. A zero length cannot // be what any header means, so it is read as "the block count says", and // when that is zero too, as "the rest of the file". const length = if (stated != 0) stated else if (blocks != 0) blocks * 512 else @as(u32, @intCast(bytes.len - from)); if (length > bytes.len - from) return error.Truncated;
return .{ .data = bytes[from..][0..length], .format = @enumFromInt(std.mem.readInt(u32, bytes[12..16], .little)), // Bit 31 is the tab. The rest of the word is the DOS volume number and // a bit saying whether it was filled in. .write_protected = flags & 0x8000_0000 != 0, .volume_number = if (flags & 0x0000_0100 != 0) @truncate(flags) else null, .blocks = blocks, };}
/// The wrapper if there is one, and the whole file if there is not.////// This is what a front end wants: a program handed a path has no business/// caring which of the two it got, and a bare image is exactly a 2IMG whose/// header would have said "all of it, in whatever order the name implies".pub fn openOrBare(bytes: []u8, path: []const u8) Error!Image { return open(bytes) catch |err| switch (err) { error.NotTwoImg => .{ .data = bytes, .format = if (disk2.Order.fromPath(path) == .prodos) .prodos else .dos, .write_protected = false, .volume_number = null, .blocks = @intCast(bytes.len / 512), }, else => err, };}
const testing = std.testing;
/// A header with the fields a test wants, and nothing after it.fn testHeader(format: u32, flags: u32, from: u32, length: u32) [header_size]u8 { var out: [header_size]u8 = @splat(0); @memcpy(out[0..4], magic); @memcpy(out[4..8], "ZG65"); std.mem.writeInt(u16, out[8..10], header_size, .little); std.mem.writeInt(u16, out[10..12], 1, .little); std.mem.writeInt(u32, out[12..16], format, .little); std.mem.writeInt(u32, out[16..20], flags, .little); std.mem.writeInt(u32, out[20..24], length / 512, .little); std.mem.writeInt(u32, out[24..28], from, .little); std.mem.writeInt(u32, out[28..32], length, .little); return out;}
test "the header says where the disk is and which way round it is" { var file: [header_size + 1024]u8 = @splat(0); @memcpy(file[0..header_size], &testHeader(1, 0, header_size, 1024)); file[header_size] = 0xa5; file[file.len - 1] = 0x5a;
const image = try open(&file); try testing.expectEqual(Format.prodos, image.format); try testing.expectEqual(@as(?disk2.Order, .prodos), image.order()); try testing.expectEqual(@as(usize, 1024), image.data.len); try testing.expectEqual(@as(u8, 0xa5), image.data[0]); try testing.expectEqual(@as(u8, 0x5a), image.data[image.data.len - 1]); try testing.expectEqual(@as(u32, 2), image.blocks); try testing.expect(!image.write_protected); try testing.expectEqual(@as(?u8, null), image.volume_number);
// And it is the caller's own bytes, not a copy: writing to the disk writes // to the file, which is how a hard disk gets saved with its header on. image.data[0] = 0x42; try testing.expectEqual(@as(u8, 0x42), file[header_size]);}
test "the flags carry the write-protect tab and the DOS volume number" { var file: [header_size + 512]u8 = @splat(0);
@memcpy(file[0..header_size], &testHeader(0, 0x8000_0000, header_size, 512)); var image = try open(&file); try testing.expect(image.write_protected); try testing.expectEqual(Format.dos, image.format); try testing.expectEqual(@as(?u8, null), image.volume_number);
// Bit 8 is what makes the low byte mean anything, which is the difference // between volume nought and nobody having written one down. @memcpy(file[0..header_size], &testHeader(0, 0x0000_0100 | 254, header_size, 512)); image = try open(&file); try testing.expect(!image.write_protected); try testing.expectEqual(@as(?u8, 254), image.volume_number);}
test "the data need not follow the header immediately" { // The offset is a field rather than a constant, which is the whole reason // the header is a wrapper: a writer may leave room for a comment in front // of the disk, and one does. var file: [header_size + 64 + 512]u8 = @splat(0); @memcpy(file[0..header_size], &testHeader(1, 0, header_size + 64, 512)); file[header_size + 64] = 0x11;
const image = try open(&file); try testing.expectEqual(@as(usize, 512), image.data.len); try testing.expectEqual(@as(u8, 0x11), image.data[0]);}
test "a file that is not one says so, and a broken one says something else" { var bare: [512]u8 = @splat(0); try testing.expectError(error.NotTwoImg, open(&bare));
var stub: [8]u8 = @splat(0); try testing.expectError(error.NotTwoImg, open(&stub));
// The mark is there but the header points past the end of the file. var file: [header_size + 16]u8 = @splat(0); @memcpy(file[0..header_size], &testHeader(1, 0, header_size, 4096)); try testing.expectError(error.Truncated, open(&file));}
test "a bare image is treated as the 2IMG it would have been" { // Which is what a front end wants: nothing handed a path should have to // care which of the two kinds of file it got. var bare: [1024]u8 = @splat(0); bare[0] = 0x99;
const as_prodos = try openOrBare(&bare, "somewhere/disk.po"); try testing.expectEqual(Format.prodos, as_prodos.format); try testing.expectEqual(@as(usize, 1024), as_prodos.data.len); try testing.expectEqual(@as(u8, 0x99), as_prodos.data[0]);
const as_dos = try openOrBare(&bare, "somewhere/disk.dsk"); try testing.expectEqual(Format.dos, as_dos.format); try testing.expectEqual(@as(usize, 1024), as_dos.data.len);
// And a real one is read as itself whatever the file is called. var file: [header_size + 512]u8 = @splat(0); @memcpy(file[0..header_size], &testHeader(1, 0, header_size, 512)); const wrapped = try openOrBare(&file, "misleading.dsk"); try testing.expectEqual(Format.prodos, wrapped.format); try testing.expectEqual(@as(usize, 512), wrapped.data.len);}
test "a nibble image is neither order and does not pretend to be" { var file: [header_size + 512]u8 = @splat(0); @memcpy(file[0..header_size], &testHeader(2, 0, header_size, 512)); const image = try open(&file); try testing.expectEqual(Format.nibble, image.format); try testing.expectEqual(@as(?disk2.Order, null), image.order());}
test "a header with no data length is read by its block count, as Sweet16 writes them" { // Sweet16 leaves the data length at zero and fills in the block count. var file: [header_size + 1024]u8 = @splat(0); @memcpy(file[0..header_size], &testHeader(1, 0, header_size, 0)); std.mem.writeInt(u32, file[20..24], 2, .little); file[header_size + 1023] = 0x5a; const image = try open(&file); try testing.expectEqual(@as(usize, 1024), image.data.len); try testing.expectEqual(@as(u8, 0x5a), image.data[1023]); // With neither, the disk is the rest of the file. std.mem.writeInt(u32, file[20..24], 0, .little); const rest = try open(&file); try testing.expectEqual(@as(usize, 1024), rest.data.len); // And a block count the file cannot hold is still a truncated file. std.mem.writeInt(u32, file[20..24], 3, .little); try testing.expectError(error.Truncated, open(&file));}