A cycle-accurate Apple II and Apple IIgs emulator written in Zig, usable as both a program and a library.
zig65 CLAUDE.md
13 kB · 247 lines
Markdown
at main

CLAUDE.md #

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

zig65 is a cycle-accurate Apple II and Apple IIgs emulator written in Zig 0.16, usable both as a program and as a library.

Commands #

The toolchain is pinned in flake.nix, so everything goes through it:

nix develop --command zig build test          # unit tests
nix develop --command zig build check         # type check everything, emit nothing
nix develop --command zig build               # build the binary (exercises linking)

The rest of this file writes zig build ... for brevity; prefix each with nix develop --command.

what command
all tests zig build test
one test zig test src/disk2.zig --test-filter "write protect"
formatting zig fmt --check . --exclude zig-pkg --exclude corpus/zig-pkg --exclude woz/zig-pkg --exclude functional/zig-pkg
licence headers reuse lint
run it zig build run -- --rom ROM [--machine iie] [--disk-rom P5] [--disk1 DISK]
a IIgs zig build gs -- --rom ROM, or zig build run -- --machine iigs --rom ROM
WOZ reference set zig build woz
functional tests zig build functional
processor corpus zig build corpus, zig build corpus16
docs zig build docs, zig build docs-serve
throughput zig build bench, zig build bench16
README references zig build references (regenerate from doc/*.bib), zig build references-check

--test-filter is not wired into zig build test, so passing it there is silently ignored and everything runs. To run one test, invoke zig test on the file directly; that works for any module that does not reach the z2d dependency (src/picture.zig and what imports it do, so those need zig build test).

CI (.forgejo/workflows/test.yaml) runs formatting, reuse lint, zig build test, a full build, zig build woz, zig build functional, and type-checks the corpus runners. It deliberately does not run the corpus.

The three test subprojects #

Each is a separate subproject with their own build.zig.zon, so that the large test data they need is fetched lazily and a plain build of the emulator does not pull it.

  • corpus/ — the SingleStepTests corpus: ~2.5M recorded cases across all five 8-bit processors and the 65816. About a gigabyte, fetched from elsewhere, so it is run by hand rather than in CI.

  • woz/ — the WOZ reference images: 45 disk images published for emulator authors. zig build woz reads every track of every image with no ROM needed. Given Apple's own ROMs it also boots them and checks the result against a table of expectations in woz/src/main.zig, which fails in both directions — a disk that stops booting is a regression, and a disk that starts booting means the table is stale and wants updating:

    zig build woz -- --rom APPLE2E.ROM --disk-rom 341-0027-a.p5 \
        --disk-rom-13 DISK2-13sector.rom
    

    A full run takes about a minute and a half; use --only SUBSTRING for one disk.

  • functional/ — Klaus Dormann's functional tests, all four of them, and all four pass. Small and quick, so unlike the corpus this one does run in CI.

    • the 6502 and 65C02 opcode tests, which stop at $3469 and $24F1. The 65C02 image is assembled with rkwl_wdc_op, so it needs the Rockwell bit instructions and runs against the W65C02 core, not the 65C02 one.
    • Bruce Clark's decimal test, which stops in the same place either way and reports in ERROR at $0B.
    • the interrupt test, which needs a feedback register wired to the IRQ and NMI pins — functional/src/feedback.zig, at $BFFC — and passes at $06F5.

    Only the first two ship as binaries. The other two are assembled at build time by aigrette65 (git.jcollie.dev/jeff/aigrette65), the user's own reimplementation of the as65 dialect they are written in. If zig65 ever needs 6502 source assembled, that is the assembler to use.

Architecture #

Everything is comptime-generic over its parts. The processor is CPU(Clock, Memory): src/cpu8.zig takes a clock and a memory model as type parameters, and the instruction table is built at comptime in src/cpu8/opcodes.zig from one file per mnemonic. Memory models live in src/memory8/ (flat, apple1, apple2plus, apple2e, apple3) and src/memory16/.

The cards live in src/slots.zig, once. Which slot a card is in is data rather than a comptime constant, so any card goes in any slot and a machine can have two of a kind. Both 8-bit memory models delegate to it: page for $Cn00-$CnFF and the $C800 window, access for a slot's sixteen device select addresses, claim for the window. What stays on the model is the machine's own business — whether the slots are answering at all, which on a IIe is INTCXROM, SLOTC3ROM and INTC8ROM, asked once in slotsAnswerAt. A IIc has no slots and its slots is void: what it has at those addresses is four ports soldered to the board, in builtInPort.

This apparatus used to exist twice, once per model, near-identically. Do not put it back: that duplication is how a Mockingboard came to work on a IIe and be completely silent on a II Plus for as long as the card had been here.

The 8-bit and 16-bit processors are separate cores on purpose. src/cpu8.zig is the 6502 family and src/cpu16.zig is the 65816, with their own addressing modes, tables and memory models. Do not widen the 8-bit core to cover the 65816.

One binary, chosen at runtime. --machine and --processor are flags, not build options: src/main.zig instantiates every pairing with an inline for over the enums. A configuration nobody builds is a configuration nobody compiles, so this is what keeps all twenty pairings honest — CI relies on a single zig build to exercise them.

Front ends. src/root.zig is the library. src/main.zig is the command line plus the 8-bit debugger; src/gs.zig is the IIgs front end (reached either directly or by --machine iigs); tools/terminal.zig is what they share.

The disk stack is the deepest part of the project and worth reading in order:

  • src/writeback.zig is how a disk gets back into the file it came out of, and is used by both front ends: session8.zig and session16.zig are separate modules, so anything they share has to live in the library. Free functions rather than methods, because a session is brought up with every field set by hand and so cannot be built inside a test.

  • src/diskfile.zig is the single door — every path the user can name goes through it, and it works out whether the file is a bare .dsk/.do/.po, a .2mg, a .nib, a .woz or a ShrinkIt archive.

  • src/woz.zig reads WOZ 1, 2 and 2.1, including flux tracks.

  • src/disk2.zig is a bit-level drive: the surface is bit cells, and the card's shifter and data register turn them into bytes. Quarter-track head positioning, self-sync, weak bits over unrecorded surface, the NE556 turn-off delay and the seven-microsecond hold on a finished byte all live here.

  • src/disk35.zig is the Apple 3.5-inch drive and is byte-level — a different abstraction on purpose, since a 3.5 WOZ is not supported.

  • src/iwm.zig is the disk port of a IIgs and of every IIc, sitting on top of both — and on top of a third thing, which is not a mechanism at all.

  • src/slots.zig is what a card is and where the seven of them are, which is the layer both 8-bit models reach the cards through.

  • src/unidisk.zig and src/cbus.zig are the intelligent drive on that port and the packets it speaks. What makes it answer rather than a mechanism is a combination of the phase lines, and the numbers it answers to come from the host: a IIc starts counting at one and a IIgs at three, so nothing here may assume either.

Conventions #

Match the hardware, not what would be convenient. Where faithful behaviour is surprising or awkward, keep it and make it legible instead — model the thing the real machine gave the user to understand what was happening, and say in the interface what it is waiting for. Any deviation belongs behind an option that is off by default, and should be proposed rather than assumed. When faithful behaviour is genuinely unusable, look for the other configuration the real machine supported rather than inventing one (an 80-column screen is unreadable in composite colour, so it defaults to the monochrome monitor people actually bought).

Settle questions from primary sources. ROMs, service manuals, real disk images and chip documentation, not recollection — and cite them. The README carries a bibliography, and code comments quote it directly, by chapter and sentence. Several long-standing bugs here were fixed by reading the document that says what the hardware does. Sources used should be cited in comments using the APA style guidelines for citations.

The README is a first-class artifact, not a stub: it explains what was built and why, and it goes stale. When a feature lands, sweep it for claims that are no longer true.

Every file needs an SPDX header (reuse lint enforces it). Generated files that would lose a header on the next run are declared in REUSE.toml as SPDX-FileCopyrightText = "NONE" with SPDX-License-Identifier = "CC0-1.0" — nobody wrote them, so claiming authorship of them would claim something that is not there.

The emulated machine owns the keyboard. Every key the Apple had goes to the Apple; the debugger's own commands live behind the alt modifier.

Tests are colocated in the file they test and named as sentences describing the behaviour ("the drive keeps turning for a second after software says stop"). A test that asserts an untrue thing is a bug in the test — several here were found by making the emulator more accurate and watching them fail.

The exception is src/system_tests.zig, which tests whole machines: power on with Apple's ROM, come up in BASIC, type a program, run it, read the screen. One of them boots Zellyn Hunter's a2audit disk and reads its result codes back. It passes clean, and its table of known differences is empty — a code appearing at all is a regression.

misterblack1's Apple II Dead Test is wired in properly, as two tests in src/system_tests.zig: it is a ROM, so it lives in ~/dev/Apple ROMs like any other and the tests skip when it is absent. It replaces the F8 ROM and uses no RAM at all, which makes it the check on what an address with no RAM behind it reads as ($ff, not the video scanner's byte — those are two different floating buses) and on the memory select blocks across all nine configurations.

Tom Charlesworth's mb-audit does the same for the Mockingboard and passes in full (832 tests), but is not wired into the suite: assemble it with acme --report mb-audit.lst mb-audit.a (ACME is in the devshell), load the result at $2000 on a IIe with mockingboard.fitted and CALL 8192. Two of its stages need answering — a real cpu.reset() when it asks for Ctrl-Reset, and ESC to skip the manual tone test. It found nine faults in the 6522, the AY-3-8913 and the reset path; the fixes have unit tests of their own, so the suite covers them even though mb-audit itself is run by hand. Those need the ROMs in ~/dev/Apple ROMs and the disks in ~/dev/Apple Disks and skip when a file is absent, so CI passes without them; when adding a machine, add one there too.

Test ROMs and disk images #

Apple's ROMs and the disk images used for testing are not in this repository and cannot be — they are Apple's code, or somebody else's archive. They live in two projects of their own: ~/dev/Apple ROMs for system ROMs, card firmware and character generators, and ~/dev/Apple Disks for disk and tape images. Each has a README.md cataloguing every file with its size, CRC32 and SHA-256 and what it is. Anything downloaded for testing goes in the right one and gets a row in that README; the files themselves are gitignored.

Reference list #

A reference list using the APA style shall be maintained with a list of materials that have been used in developing the software. If there are online sources for the reference material (PDF, blog post, etc.) include links to that source. Each reference should be annotated with a short description of the material.

Bibliography #

A bibliography section of the README must be maintained with a list of any reference material that may be of interest but was not directly used in developing the software. Each entry should be annotated with a brief description of the document. Maintain the list in the same format as the reference list.