Portable Host I/O, MinGW-w64 & Wine CI, s7 Scripting & microui Workbench Plan
All four phases of this specification have been implemented in emu/ and verified across native Linux, MinGW-w64 cross-builds, Wine 11 CI, and Nix packages. For live user and contributor documentation, see docs/emulator/README.md and docs/emulator/gui-scripting-and-debug.md.
Historical Specification: Approved technical specification that guided phased implementation (
Phase 1->Phase 2->Phase 3->Phase 4).
Companion Specification: Coordinates directly with cpu-acceleration-plan.md, genera-8.3-cdrom-install.md, emu/AGENTS.md, and AGENTS.md.
1. Executive Summary & Settled Architectural Decisions
This specification extends the from-scratch C11 Symbolics XL1200 hardware emulator (emu/) with four cohesive, minimal-dependency capabilities while preserving a 100% OS-agnostic ISO C11 core (libivory_core.so / libivory_core.dll):
- Portable Host I/O, MinGW-w64 Windows Build & Headless Wine CI (
Phase 1):- Purifies
libivory_coreby extracting Linux-only TAP/AF_PACKETnetworking out ofeth_82586.cinto a host-shell unit (eth_tap_linux.c) and replacing POSIX-only file/thread/loader calls with ~145 LOC of header-only shims (emu_os.h,emu_io.h). - Collapses the emulator shell from 3 threads + 2 POSIX wake pipes down to a strict 2-thread architecture (
Main Thread= SDL3 +microui+s7+ non-blockingdebug_ctl&serial_host;emu_thread= pure CPU slice runner). - Provides multi-transport
debug_ctlIPC: Win32 Named Pipes (\\.\pipe\ivory-xl1200-<pid>, default on Windows),AF_UNIX(/tmp/ivory-xl1200-<pid>.sock, default on Linux), and dual-stack IPv4/IPv6 TCP (--debug-tcp <[addr]:port>) on both OSes. - Adds first-class NixOS cross-compilation (
nix build .#windows,devShells.mingw,make -C emu dist-winproducingivory-xl1200.exe+ hot-reloadablelibivory_core.dll+ self-contained DLL bundle) and persistent-wineserverheadlesswine64test execution (make -C emu test-win test-e2e-win).
- Purifies
- Vendored
s7Scheme Machine Configuration & Cooperativecall/ccWorkbench (Phase 2):- Vendors Stanford CCRMA
s7Scheme (emu/vendor/s7/{s7.c,s7.h}, 0-BSD) intoSHELL_SRCS. - Unifies machine configuration and automation in
.scmfiles: declarative(define-machine ...)configures full hardware identity (Main Board serial & mfg date, I/O Board #0 serial/part/rev/mfg-date/monitor/MAC, persistent MK48T02.nvramfile & RTC offset, ROM/kernel/snapshot, RAM size, SCSI0..6, Ethernetslirp/tap/veth+hostfwds, Serial Ch.A/B backends, display/keymap, checkpoints), while GUI Save Config splices only the top-level(define-machine ...)byte span so user comments, macros, and custom actions in the same file remain untouched. - Provides convenience macros (
define-action,with-paused-cpu), lifecycle/debug hooks (on-boot,on-halt,on-break,on-watch), fast typed C accessors +(emu/cmd "...")over an in-processDebugCtlSink, and a pure-Schemecall/cccooperative task scheduler paired withrt->script_step_ceilingfor cycle-exact multi-million-step automation without blocking the 60 FPS GUI. - Ports the hardware E2E test suite (
test_e2e_puppet.sh) to a cross-platforms7script (emu/tests/e2e_suite.scm) executed identically on Linux andwine64.
- Vendors Stanford CCRMA
- Integrated Disk Management (
fep_convert) & Portable Serial Host Backends (Phase 3):- Links
fep_convert.c(-DFEP_CONVERT_NO_MAIN) into the emulator shell (ivory_fep_tools.h) for in-process blank disk creation, native XL1200 1280B/sector Initial FEPFS formatting (LABL+FEPD+ bootstrapFEPFs), blank SIMH.tapcreation, FEPFS/tape inspection, MacIvory big-endian conversion, and COW.ovloverlay commit-to-base / reset. - Wires DUSCC/8237 Serial Channel A (console/diagnostic) and Channel B (bulkhead RS-232) via
Xl1200SerialCallbacks(serial_host.c) to non-blocking dual-stack IPv4/IPv6 TCP, Named Pipe /AF_UNIX, and file capture backends.
- Links
- Vendored
microuiTop Menu Bar & Floating Workbenches on SDL3SDL_Renderer(Phase 4):- Vendors
rxi/microui(emu/vendor/microui/{microui.c,microui.h}, MIT) rendered inSDL_Rendererwindow space: a dedicated 22px top menu bar above the letterboxed VRAM canvas (auto-hidden in fullscreen) + crisp floating windows (Machine Setup, Disk & Media Manager, Net & Serial, Checkpoints & Debugger, Actions, and Interactives7REPL). - Deletes ~500+ LOC of custom pixel-hitbox popovers (
MENU_CDROM,MENU_TAPE,MENU_KEYMAP,MENU_RESET) fromsdl_console.c, retaining the bottom 28px strip strictly as a passive XL1200 hardware LED bezel (preserving bit-exact1084×840/1152×924.y4mrecordings anddump-panelPPMs). - Enables zero-argument GUI startup (double-clicking
ivory-xl1200.exe): auto-loads<exe_dir>/xl1200.scm(or./xl1200.scm) if present; otherwise opens paused directly in the Machine Setup window instead of exiting with an error.
- Vendors
flowchart TB
subgraph MainThread["Host Shell — Main Thread (Sole Owner of SDL3, microui, s7, debug_ctl, serial_host)"]
UI["SDL3 Window + SDL_Renderer (sdl_console.c + ui_workbench.c)<br/>• 22px microui Top Menu Bar (auto-hide fullscreen)<br/>• Letterboxed Console Texture (1084x840 trim / 1152x924 full)<br/>• Floating microui Windows + SDL_ShowOpen/SaveFileDialog"]
S7["s7 Scheme Engine (emu_script.c)<br/>• (define-machine ...) + Byte-Span Save Config<br/>• (define-action ...) -> Menu + Hotkeys<br/>• Pure-Scheme call/cc *emu-tasks* Scheduler<br/>• on-boot / on-halt / on-break / on-watch Hooks"]
CTL["Unified Command Kernel (debug_ctl.c)<br/>• DebugCtlSink (In-Memory Buffer | Socket | Pipe)<br/>• Replaces 480-LOC duplicate PuppetContext in main.c"]
HOSTIO["Non-Blocking Host I/O (emu_ipc.c / serial_host.c / eth_slirp.c)<br/>• Win32 PIPE_NOWAIT \\\\.\\pipe\\ivory-xl1200-<pid> (Win default)<br/>• AF_UNIX /tmp/ivory-xl1200-<pid>.sock (Linux default)<br/>• Dual-Stack IPv4/IPv6 TCP (--debug-tcp & Serial Ch.A/B)<br/>• libslirp NAT + Linux-only eth_tap_linux.c"]
DISK["Embedded Disk Tools (fep_convert.c -DFEP_CONVERT_NO_MAIN)<br/>• Create Blank / Initial FEPFS / SIMH .tap<br/>• Inspect LABL/FEPD / Convert MacIvory / Commit .ovl"]
end
subgraph EmuThread["Emulator Worker Thread (emu_thread)"]
LOOP["CPU Slice Runner (state_mu + wake_cv)<br/>• Slice clamped to min(slice, next_auto_ckpt, script_step_ceiling)<br/>• Sets pending_hooks bitmask on break/watch/halt & wakes Main"]
end
subgraph CoreDLL["Hot-Reloadable Core (libivory_core.so / libivory_core.dll)"]
CORE["100% Pure ISO C11 (0 writable .data / 0 .bss)<br/>• IvoryCoreApi v4 (exports ivory_core_get_api only)<br/>• IvoryCpu (4096B) | IvoryMem (32768B) | MerlinBoard (278528B)<br/>• Reset-safe Main & IO0 ID ROMs + MK48T02 NVRAM"]
end
UI <--> S7
UI <--> DISK
S7 <--> CTL
HOSTIO <--> CTL
CTL <-->|"state_mu"| LOOP
S7 <-->|"script_step_ceiling + pending_hooks"| LOOP
LOOP <-->|"IvoryCoreApi v4"| CORE
HOSTIO <-->|"EthHostCallbacks / Xl1200SerialCallbacks"| CORE2. Source-Provenance, Frozen-ABI & Companion-Plan Coordination Invariants
Mandatory Invariants (emu/AGENTS.md & AGENTS.md §6):
- Reference Sources Only: Consult only
emu/,docs/,genera-original/, andI_Machine/. Never read, inspect, grep, or citelinux-vlm/,xl1200-emu/, orarchive/. - No Synthetic Guest Code: All tests (
e2e_suite.scm,test_s7_config.c, Wine CI) must execute genuine ROM/kernel binaries (ivory-fep-roms/fep330/rom.dump,macivory/macivory_cdrom.iso) or isolated single-instruction unit checks. - Frozen Struct Sizes Across Linux (
LP64) and Windows x64 (LLP64):sizeof(IvoryCpu) == 4096Usizeof(IvoryMem) == 32768Usizeof(MerlinBoard) == 278528UAll bitfields inivory_hw.huse uniformuint32_t/uint64_tstorage units; retain explicit_Static_assertchecks so MinGW-mms-bitfieldsnever alters layout.
- Zero
.data/.bss& Single-Symbol Export Hygiene:- Linux ELF:
readelf -WS emu/build/obj/core/*.omust report0bytes in writable.dataand.bss, andnm -D --defined-only emu/build/libivory_core.soexports onlyivory_core_get_api. - Windows PE/COFF:
x86_64-w64-mingw32-objdump -h emu/build-win/obj/core/*.omust show zero writable.data/.bsspayload, andx86_64-w64-mingw32-objdump -p emu/build-win/libivory_core.dllmust list onlyivory_core_get_apiin the export table.
- Linux ELF:
Disjoint Coordination with cpu-acceleration-plan.md
To ensure zero merge conflicts regardless of execution order between this plan and cpu-acceleration-plan.md:
- Reserved Padding Allocation:
cpu-acceleration-plan.mdcarvesIvoryMem._reserved[938]->_reserved[937]forIvoryDcache *dcache.- This plan touches zero bytes of
IvoryMem._reservedorIvoryCpu._reserved, carving 1uint64_tslot fromMerlinBoard._reserved[1055]->_reserved[1054]inivory_emu.hto persist Main Board identity across cold power resets:/* Inside struct MerlinBoard, immediately before _reserved: */ uint32_t main_serial; /* Default 1200 (0x000004B0) LE at #o777400040 */ uint16_t main_mfg_days; /* Days since 1982-01-01 LE at #o777400044 */ uint16_t main_id_flags; /* Bit 0: custom main_serial/mfg_days active */ uint64_t _reserved[1054];
- Single Coordinated
IvoryCoreApiBump (IVORY_CORE_ABI_VERSION = 4U):- Remove Linux-specific
eth_82586_open_tapandeth_82586_open_packetfromivory_core_api.h(keepingint fd; int if_index;as inert fields insidestruct Eth82586sosizeof(MerlinBoard)stays278528U). - Add
merlin_set_identityandconsole_hw_set_serial_callbackstoIvoryCoreApi:typedef struct MerlinIdentityConfig { uint32_t main_serial; /* #o777400040 & #o777400060 bytes 0..3 LE (si:machine-model) */ uint16_t main_mfg_days; /* #o777400040 & #o777400060 bytes 4..5 LE */ uint32_t io0_serial; /* #o10400260000 rom[7..10] LE (merlin-io-board) */ uint32_t io0_part_number; /* rom[3..6] LE (default 170082 = 0x00029862) */ uint8_t io0_mfg_rev; /* rom[11] (default 1) */ uint8_t io0_func_rev; /* rom[12] (default 1) */ uint8_t io0_minor_rev; /* rom[13] (default 0) */ uint16_t io0_mfg_days; /* rom[14..15] LE (default 3650 = 0x0E42) */ uint8_t monitor_type; /* rom[22]: 0 = Philips, 1 = Sony */ uint8_t mac_addr[6]; /* rom[16..21], nvram[0x20..0x25], eth.mac_addr & eth.ia_addr */ uint32_t eco_reg; /* board->vme_timeout (0 = keep MERLIN_ECO_DEFAULT) */ int64_t rtc_offset_sec; /* board->nvram.time_offset_sec */ bool update_rtc_offset; } MerlinIdentityConfig; - Reset-Safety Fix in
mem.c:405-419:ivory_boot_comm_init_xl1200(IvoryMem *mem)is called duringivory_mem_reset()anddebug_ctl_power_reset(). Update it to readserial = (mem->board && (mem->board->main_id_flags & 1U)) ? mem->board->main_serial : 1200Uandmfg = (mem->board && (mem->board->main_id_flags & 1U)) ? mem->board->main_mfg_days : 3650U, writing bytes0..5asDTP_FIXNUMbyte words into bothmem->boot_comm[0x20..0x25](#o777400040) and fallbackmem->boot_comm[0x30..0x35](#o777400060) per localgenera-original/sys.sct/i-sys/configuration.lisp:107-123, 400-414.
- Remove Linux-specific
- PE/COFF Export Macro in
ivory_core_api.h:#if defined(_WIN32) # if defined(IVORY_BUILDING_CORE_DLL) # define IVORY_CORE_EXPORT __declspec(dllexport) # else # define IVORY_CORE_EXPORT # endif #elif defined(__GNUC__) || defined(__clang__) # define IVORY_CORE_EXPORT __attribute__((visibility("default"))) #else # define IVORY_CORE_EXPORT #endifWARNINGOn
x86_64-w64-mingw32-gcc, passing-fvisibility=hiddenor__attribute__((visibility("default")))triggers-Wattributeswarnings that fail under-Werror, and omitting__declspec(dllexport)causes GNUldto enable--export-all-symbolsby default. Defining__declspec(dllexport)onivory_core_get_apialone (with-DIVORY_BUILDING_CORE_DLL=1when buildingCORE_OBJSon Windows) keeps-Werrorclean and restricts the DLL export table to that single symbol.
3. Phase 1: Portable I/O, 2-Thread Runtime, MinGW-w64 Build & Headless Wine CI
3.1 Purifying libivory_core (eth_82586.c -> eth_tap_linux.c)
- Remove all POSIX/Linux includes (
<arpa/inet.h>,<fcntl.h>,<linux/if_ether.h>,<linux/if_packet.h>,<linux/if_tun.h>,<net/if.h>,<sys/ioctl.h>,<sys/socket.h>,<unistd.h>) and_GNU_SOURCEfrometh_82586.c. eth_82586.cretains only#include "ivory_emu.h"and#include <string.h>, routing all TX/RX exclusively througheth->host_cb(EthHostCallbacks).- Move TAP (
/dev/net/tun) andAF_PACKETsocket setup/teardown/read/write intoemu/src/eth_tap_linux.cinSHELL_SRCS, guarded by#ifdef __linux__(with cleanIVORY_ERR_INVALID_ARGstubs reporting"TAP/AF_PACKET requires Linux; use --eth-user"on non-Linux hosts).
3.2 Header-Only OS & 64-Bit File Shims (emu_os.h & emu_io.h)
emu/include/emu_os.h (~65 LOC — Zero SDL Dependency)
Keeping OS threading/alignment/DLL primitives independent of SDL3 ensures non-GUI unit tests (test_loader, test_mem, test_cpu_core, test_isa_ops, test_merlin, test_snapshot_reload) remain 100% free of SDL3.dll and libwinpthread-1.dll:
- Synchronization & Threads:
- POSIX:
pthread_mutex_t,pthread_cond_t(CLOCK_MONOTONIC),pthread_t. _WIN32:SRWLOCK(InitializeSRWLock,AcquireSRWLockExclusive,ReleaseSRWLockExclusive),CONDITION_VARIABLE(SleepConditionVariableSRWtaking relativeDWORD timeout_ms = (DWORD)((wait_us + 999U) / 1000U)), and_beginthreadex/WaitForSingleObject/CloseHandle.
- POSIX:
- Aligned Allocation & Memory Locking:
emu_aligned_alloc(size_t align, size_t sz)/emu_aligned_free(void *p): wrapsposix_memalign+freeon POSIX, and_aligned_malloc(sz, align)+memset+_aligned_free(p)on_WIN32(never pass_aligned_mallocpointers to plainfree()on MSVCRT/UCRT!).emu_mlock(p, sz)/emu_munlock(p, sz):mlock/munlockon POSIX,VirtualLock/VirtualUnlockon_WIN32.
- Clocks, Paths & Dynamic Loader:
emu_mono_ns():clock_gettime(CLOCK_MONOTONIC)on POSIX;QueryPerformanceCounter/QueryPerformanceFrequencycached viaInitOnceExecuteOnceon_WIN32.emu_sleep_us(uint32_t us):nanosleepon POSIX;Sleep(us >= 1000U ? us / 1000U : 1U)on_WIN32.emu_pid():(uint32_t)getpid()vs(uint32_t)GetCurrentProcessId().emu_exe_dir(buf, cap)&emu_temp_dir(buf, cap):readlink("/proc/self/exe")+"/tmp"on Linux;GetModuleFileNameA(NULL, ...)+GetTempPathA(...)on_WIN32.emu_dlopen/emu_dlsym/emu_dlclose:dlopen(..., RTLD_NOW | RTLD_LOCAL)on POSIX;UINT old = SetErrorMode(SEM_FAILCRITICALERRORS); HMODULE h = LoadLibraryA(path); SetErrorMode(old);+GetProcAddress+FreeLibraryon_WIN32.- Update
core_loader.c,test_debug_ctl.c, andtest_snapshot_reload.cto copyIVORY_CORE_FILENAME("libivory_core.dll"on_WIN32,"libivory_core.so"on POSIX) to<temp_dir>/ivory-core-<pid>-<gen>.<ext>usingstdio/CopyFileA, ensuringFreeLibraryruns beforeDeleteFileA(active_tmp_path).
emu/include/emu_io.h (~80 LOC — 64-Bit Clean Past 2 GiB on LLP64)
Critical LLP64 Bug in Current scsi_wd33c93.c:
- Lines
296–346call POSIXpread(fileno(t->fp), ...)andpwrite(...), which do not exist on MinGW-w64. - Line
1687callsfseek(fp, 0L, SEEK_END)+long sz = ftell(fp). On Windows x64 (LLP64),longis signed 32-bit, overflowing at 2 GiB (breakingMacIvory_Virginal_9GB.img).
emu_io.h replaces all fseek/ftell/fseeko/ftello/ftruncate/pread/pwrite/rename calls in scsi_wd33c93.c, snapshot.c, fep_convert.c, and emu_script.c:
emu_fseek64(FILE *fp, uint64_t off, int whence)/int64_t emu_ftell64(FILE *fp):fseeko/ftello(_FILE_OFFSET_BITS=64) on POSIX;_fseeki64/_ftelli64on_WIN32.emu_ftruncate64(FILE *fp, uint64_t size):fflush(fp)+ftruncate(fileno(fp), (off_t)size)on POSIX;fflush(fp)+_chsize_s(_fileno(fp), (int64_t)size)on_WIN32.emu_pread(FILE *fp, void *dst, size_t len, uint64_t off)/emu_pwrite(...):pread/pwriteon POSIX; on_WIN32, synchronousReadFile/WriteFileon(HANDLE)_get_osfhandle(_fileno(fp))passingOVERLAPPED ov = { .Offset = (DWORD)off, .OffsetHigh = (DWORD)(off >> 32) }(thread-safe, stateless file-pointer semantics matchingpread/pwriteacross 64-bit offsets).emu_atomic_replace(const char *tmp_path, const char *dst_path):rename(tmp_path, dst_path)on POSIX;MoveFileExA(tmp_path, dst_path, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)on_WIN32(since Windowsrename()fails withEEXISTwhendst_pathalready exists).
3.3 Non-Blocking Local Named Pipe / AF_UNIX + IPv4/IPv6 TCP Layer (emu_ipc.{h,c})
Implement a ~140-LOC non-blocking byte-stream helper shared by debug_ctl.c and serial_host.c:
- Default Local IPC (
EmuLocalServer/EmuEndpoint):- POSIX:
AF_UNIXSOCK_STREAM(O_NONBLOCK | FD_CLOEXEC), default/tmp/ivory-xl1200-<pid>.sock. - Windows (
_WIN32): Native Win32 Named Pipe (\\.\pipe\ivory-xl1200-<pid>by default;--debug-pipe <\\.\pipe\name>or--no-debug-pipe; if user passes a bare namefoo, normalize to\\.\pipe\foo):- Create with
CreateNamedPipeA(pipe_name, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_NOWAIT, PIPE_UNLIMITED_INSTANCES, 65536, 65536, 0, NULL). - Maintain
1pre-allocated listeningHANDLEalongside active clientHANDLEs (<= DEBUG_CTL_MAX_CLIENTS). On each poll: callConnectNamedPipe(listen_h, NULL)— underPIPE_NOWAIT, it returns immediately:GetLastError() == ERROR_PIPE_CONNECTED-> promotelisten_hto an active client slot and immediatelyCreateNamedPipeAa freshlisten_hso concurrent clients never hitERROR_PIPE_BUSY.GetLastError() == ERROR_PIPE_LISTENING-> no new client yet (0µs block).
- Non-blocking read:
ReadFileunderPIPE_NOWAITreturnsFALSEwithERROR_NO_DATAwhen empty (0bytes available) andERROR_BROKEN_PIPEon client disconnect — zeroOVERLAPPEDstate machines orHANDLEevent leaks!
- Create with
- POSIX:
- Dual-Stack IPv4/IPv6 TCP (
--debug-tcp <[addr]:port>):- Address parser supports
127.0.0.1:4200,[::1]:4200,:4200/[::]:4200(dual-stack wildcard),0.0.0.0:4200,localhost:4200, and port0(ephemeral OS port for parallel tests; exposeuint16_t emu_ipc_bound_port(const EmuTcpListener *)). - Uses
getaddrinfo(host_or_null, port_str, &hints, &res)withAF_UNSPEC,SOCK_STREAM,AI_PASSIVE. When binding anAF_INET6socket with empty/wildcard host, setint v6only = 0; setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (const char *)&v6only, sizeof(v6only));beforebind()so both IPv4 and IPv6 clients connect cleanly. - Enables
SO_REUSEADDR(POSIX only — neverSO_REUSEADDRon Windows TCP listeners, where it allows port hijacking!),TCP_NODELAY, and non-blocking mode (fcntl(O_NONBLOCK)/ioctlsocket(FIONBIO)).
- Address parser supports
- Simultaneous Active Listeners:
DebugCtlServerholds bothlocal_listener(AF_UNIXon Linux,\\.\pipe\...on Windows) and optionaltcp_listener(--debug-tcp), polling both into the sharedclients[]array (DEBUG_CTL_MAX_CLIENTS = 8U).
3.4 Winsock2 Fixes in eth_slirp.c
- Under
#ifdef _WIN32, include<winsock2.h>and<ws2tcpip.h>before<slirp/libslirp.h>, and call an idempotentemu_winsock_init()(WSAStartup(MAKEWORD(2, 2), &wsa)) insideeth_slirp_create()andemu_ipc.c. - In
slirp_add_poll_cb()(eth_slirp.c:139): changeif (!b || fd < 0)toif (!b || fd == (slirp_os_socket)-1)(SOCKETis unsigneduintptr_ton_WIN64). - Critical Winsock2
WSAPollFix (eth_slirp.c:157): On Windows, passingPOLLPRI(POLLRDBANDedge conflict) inWSAPOLLFD.eventscausesWSAPoll()to fail immediately withSOCKET_ERROR(WSAEINVAL = 10022) on every call. GuardSLIRP_POLL_PRI -> POLLPRIwith#ifndef _WIN32, and callWSAPoll(b->pfds, (ULONG)b->pfds_len, 0)on_WIN32.
3.5 Strict 2-Thread Runtime & DebugCtlSink Unification (debug_ctl.c & main.c)
- Refactor
debug_ctl.cOutput toDebugCtlSink:Exposetypedef struct DebugCtlSink { bool (*write)(void *ctx, const char *buf, size_t len); void *ctx; } DebugCtlSink;bool debug_ctl_exec(DebugCtlServer *srv, const DebugCtlSink *sink, const char *line, IvoryCpu *cpu, MerlinBoard *board, IvoryMem *mem, bool sdl_opened, bool batch_mode);. - Three Mandatory
--puppetParity Updates Before DeletingPuppetContext:- Append
vram_nonzero=%zu vram_nonbg=%zu video_ctrl=0x%08Xtosend_state_reply()indebug_ctl.c(required bytest_e2e_puppet.shChecks 1–5). - Add
wait-vram <max_steps> [chunk]todebug_ctl_exec(). - In
step [N]: whenbatch_modeis true (used by--puppet*), calldebug_ctl_run_budget()instead of single-stepping 1-by-1 and do not forcesrv->paused = trueafterward; in interactive debug mode (!batch_mode), useivory_cpu_runslices whennum_breakpoints == 0 && num_watchpoints == 0and pause upon completion as today. - Delete
struct PuppetContextand all ~480 lines of duplicate puppet command parsing inmain.c:1081-1560:--puppet,--puppet-file, and--puppet-stdiosimply feed lines intodebug_ctl_exec(..., &stdout_sink, ..., /*batch_mode=*/true).
- Append
- Eliminate
dbg_thread,main_stop_pipe, anddbg_wake_pipeinmain.c:- Main Thread runs at ~60–200 Hz (
SDL_WaitEventTimeout(..., 8)when SDL is open;emu_sleep_us(5000)when--headlesscontinuous):- Acquires
rt_lock_state(&rt)briefly to pollsdl_console_poll_events(),debug_ctl_poll(..., sdl_opened),serial_host_poll(), drainpending_hooks& tick readys7tasks (emu_script_tick()), and prepare the dirty console frame; releasesstate_muand callssdl_console_flush_present().
- Acquires
emu_threadremains a pure CPU + device slice runner synchronized solely byrt.state_mu(EmuMutex) +rt.wake_cv(EmuCond) +atomic_bool stop_requested(SIGINT/SIGTERMhandler setsg_stop_requested = 1; on_WIN32,SetConsoleCtrlHandlersetsg_stop_requested = 1and callsWakeAllConditionVariable(&rt.wake_cv)).
- Main Thread runs at ~60–200 Hz (
3.6 NixOS Cross-Compilation (flake.nix) & Headless wine64 CI (emu/Makefile)
Two Verified NixOS / pkgsCross.mingwW64 Pitfalls & Solutions:
- Never pass
src = self;to Nix derivations in this repo: copying.hashesMacIvory_Virginal_9GB.img+genera-original/(>10 GiB) into/nix/store. Always scopesrc = pkgs.lib.fileset.toSource { root = ./.; fileset = ./emu; };. pkgsCross.mingwW64.libslirpevaluation fix onnixos-unstable: upstreamlibslirpsetsmeta.platforms = platforms.unix, andmingwW64.glibpulls cross-python3(marked broken onmingwW64). Overrideglibto use native build-hostpkgs.python3withwithIntrospection = false:mingwPkgs = pkgs.pkgsCross.mingwW64; glibWin = (mingwPkgs.glib.override { python3 = pkgs.python3; python3Packages = pkgs.python3Packages; withIntrospection = false; }).overrideAttrs { outputs = [ "bin" "out" "dev" ]; postFixup = ""; }; slirpWin = (mingwPkgs.libslirp.override { glib = glibWin; }).overrideAttrs (old: { separateDebugInfo = false; meta = old.meta // { platforms = pkgs.lib.platforms.all; }; }); sdl3Win = mingwPkgs.sdl3;
flake.nixOutputs:packages.default: native Linuxivory-xl1200+libivory_core.so+ivory-fep-convert.packages.windows: cross-compiled self-contained Windows distribution (ivory-xl1200.exe,libivory_core.dll,ivory-fep-convert.exe, runtime.dlls, samplexl1200.scm).devShells.mingw: extends default shell withmingwPkgs.stdenv.cc,mingwPkgs.windows.pthreads(headers unused ifemu_os.huses native Win32, but available for toolchain),sdl3Win,slirpWin, andpkgs.wineWow64Packages.minimal(wine64+wineserver).
emu/MakefileTargets (TARGET_OS ?= native):TARGET_OS=windowssetsBUILD_DIR := build-win,CC := x86_64-w64-mingw32-gcc,EXE_EXT := .exe,DLL_EXT := .dll,CORE_SO := $(BUILD_DIR)/libivory_core.dll, omits-fPIC/-fvisibility=hidden/-ldl/-pthread, adds-DIVORY_BUILDING_CORE_DLL=1toCORE_CFLAGS, and appends-lws2_32 -liphlpapito shellLDFLAGS.make -C emu dist-win: buildsTARGET_OS=windows alland populatesbuild-win/dist/by recursively resolving non-system DLL imports viax86_64-w64-mingw32-objdump -pagainstSDL3/libslirp/GCC runtime search paths (excluding Windows OS DLLs likeKERNEL32.dll,USER32.dll,WS2_32.dll,ADVAPI32.dll,UCRTBASE.dll,MSVCRT.dll,GDI32.dll,SHELL32.dll,OLE32.dll,IMM32.dll,WINMM.dll,SETUPAPI.dll,VERSION.dll,IPHLPAPI.dll).make -C emu test-win&test-e2e-win(PersistentwineserverRunner):CAUTIONNever wrap
wine64inprlimit --as=1GB(RLIMIT_AS):wine64-preloaderreserves 3–6 GiB ofPROT_NONE | MAP_NORESERVEvirtual address space beforemain()(~25 MiB actual RSS) and immediately aborts underRLIMIT_AS=1GB.UsingWINEPREFIX="$(mktemp -d /tmp/ivory-wine-XXXXXX)" \ WINEDEBUG=-all DISPLAY= \ SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \ WINEPATH="$(wine_dll_search_path);$(pwd)/build-win" \ bash -c ' trap "wineserver -k 2>/dev/null || true; rm -rf \"$WINEPREFIX\"" EXIT wineserver -p1 for t in build-win/test_*.exe; do echo "=== [Wine] $t ===" wine64 "$t" || exit 1 done 'wineserver -p1keeps one backgroundwineserveralive across all.exebinaries, cutting total Wine test runtime from ~45s to ~2.5s.
4. Phase 2: s7 Configuration, Convenience Macros, call/cc Workbench & Portable E2E
4.1 Vendoring & Compiling s7 (emu/vendor/s7/)
- Vendor upstream CCRMA
s7.hands7.c(0-BSD license; document upstream revision & license inemu/vendor/s7/README.md). - Compile as a dedicated object
$(OBJ_DIR)/vendor/s7.owith:S7_CFLAGS := -std=c11 -O2 -g -DWITH_MAIN=0 -DWITH_C_LOADER=0 -DDISABLE_DEPRECATED=1-DWITH_C_LOADER=0disablesdlopen-based runtime C compilation insides7(eliminating<dlfcn.h>on MinGW-w64).- Compiling
s7.owithout-Wall -Wextra -Werrorisolates upstream compiler warnings while keeping-Wall -Wextra -Werrorstrictly enforced onemu/src/emu_script.cand all project files.
- Strict Thread-Ownership Rule:
s7_scheme *scis created, evaluated, and destroyed exclusively on the Main Thread.emu_threadnever calls anys7_*function.
4.2 Hybrid Declarative (define-machine ...) + Non-Destructive Save Config
Declarative Profile Form
(define-machine &key ...) populates EmuMachineConfig in C (paths inside (define-machine ...) resolve relative to the directory containing the .scm config file unless absolute):
;;; xl1200.scm — Machine Configuration & Custom Lisp Workbench
(define-machine
:name "XL1200 — Genera 8.3"
;; Hardware Identity (Main Board #o777400040 + IO0 #o10400260000 + MK48T02 NVRAM + 82586)
:serial 12042 ; 32-bit Main Board s/n (si:machine-model)
:mfg-days 3650 ; Days since 1982-01-01
:io-serial 12042 ; 32-bit I/O Board #0 s/n (rom[7..10])
:io-part 170082 ; Part number (rom[3..6])
:io-rev '(1 1 0) ; (mfg-rev func-rev minor-rev)
:monitor :philips ; :philips (0) | :sony (1)
:mac "08:00:05:12:34:56" ; Symbolics IEEE OUI 08:00:05
:nvram "disks/xl1200.nvram" ; Loaded on boot/power-reset; saved on clean exit
:rtc-offset 0 ; Seconds offset from host UTC (or (emu/rtc-year 1993))
;; Memory, Firmware & Pacing
:ram-mw 8 ; Default 8 MW
:rom "../ivory-fep-roms/fep330/rom.dump"
:kernel #f ; Optional IFEP-Kernel path
:snapshot #f ; Optional .snap file to load after boot init
:clock :realtime ; :realtime | :deterministic
:idle-yield #t
:overscan :trim ; :trim (1084x812) | :full (1152x896)
:keymap :xl1200
:mouse-mode :capture ; :capture | :relative
;; SCSI Targets 0..6
:scsi '((0 :disk "disks/genera83.raw" :mode :overlay :overlay "disks/genera83.ovl")
(4 :cdrom "../macivory/macivory_cdrom.iso")
(5 :tape "disks/backup.tap" :mode :rw))
;; Networking & Serial Host Backends
:net '(:mode :user :cidr "10.0.2.0/24"
:hostfwd ("tcp:127.0.0.1:2323-:23"))
:serial-a '(:mode :none)
:serial-b '(:mode :tcp-listen :addr "[::1]:4210")
;; External Debug IPC & Checkpoints
:debug-local #t ; Auto AF_UNIX / \\.\pipe\ivory-xl1200-<pid>
:debug-tcp #f ; Optional e.g. "[::1]:4200"
:ckpt '(:interval 0 :max 16 :ttl 0))
Startup Precedence & Zero-Argument GUI Launch
- Initialize
EmuMachineConfigdefaults (serial = 1200,mac = 08:00:05:00:00:01,ram_mw = 8,keymap = xl1200,overscan = trim). - If
--config <file.scm>is passed, evaluate<file.scm>ins7. - Otherwise, if
argc == 1(zero CLI flags — e.g. double-clickingivory-xl1200.exe):- Check
<exe_dir>/xl1200.scm, then./xl1200.scm. If found, setactive_config_pathand evaluate it. - If neither exists and
!cfg.headless: enter Unconfigured Paused GUI Mode (dbg.paused = true,rt.unconfigured = true,ui.machine_setup_open = true) so the user can configure or load a machine from themicrouiMachine menu and click Save & Power On (in--headlessmode with no args and no default config, print usage and exit1).
- Check
- Apply any explicit CLI flags (
--rom,--disk*,--eth-*,--debug-*,--headless,--steps, etc.) on top of(define-machine ...)so CLI overrides always win. - Apply
--script <file.scm>and repeatable--eval <expr>after machine initialization. - Persistent NVRAM Lifecycle: If
:nvram(or--nvram <path>) is configured:- If
<path>exists on disk, load viaapi->nvram_mk48t02_load_file(&board->nvram, path)(and if:macwas explicitly set, synchronizenvram[0x20..0x25]to match:macso NVRAM andio0_id_romnever disagree); if<path>does not exist yet, initialize fresh NVRAM with:macand create<path>vianvram_mk48t02_save_fileon clean shutdown (and on(emu/nvram-save)/ GUI Save NVRAM). Also reload<path>insidedebug_ctl_power_reset().
- If
Non-Destructive Byte-Span Splice for GUI Save Config (~40 LOC)
When saving from the GUI to an existing .scm file, never overwrite user code outside (define-machine ...):
- Format the canonical
(define-machine ...)S-expression string from the currentEmuMachineConfig. - Scan the existing file bytes at top level (skipping
;...\nline comments, nested#|...|#block comments, and"..."string literals with\"escapes) to locate the first top-level list whose head symbol isdefine-machine, recording[span_start, span_end). - Write
[0 .. span_start) + formatted_define_machine + [span_end .. EOF)(or prependformatted_define_machine + "\n\n"if nodefine-machineform exists) to<path>.tmpand commit atomically viaemu_atomic_replace().
4.3 s7 Primitives, Convenience Macros & call/cc Cooperative Scheduler
Cycle-Exact script_step_ceiling Coordination with emu_thread
At 150–250 MIPS (cpu-acceleration-plan.md), a single 16.6 ms GUI frame executes ~3–4M guest instructions. To make (emu/wait-steps N) and key-edge pacing cycle-accurate in both 60 FPS GUI mode and headless batch mode:
- Add
uint64_t script_step_ceiling(UINT64_MAXwhen no step-boundeds7task is waiting) anduint32_t pending_hooks(EMU_HOOK_BOOT | EMU_HOOK_HALT | EMU_HOOK_BREAK | EMU_HOOK_WATCH) toEmuRuntime. - In
emu_thread_main()(main.c:1943-1950):- If
cpu->instr_count >= rt->script_step_ceiling,emu_threadwakes Main Thread and waits onrt->wake_cv(until Main Thread tickss7and raises or clearsscript_step_ceiling). - Otherwise, clamp
slice = min(slice, rt->script_step_ceiling - cpu->instr_count)identically tockpts->next_auto_instr!
- If
Pure-Scheme call/cc Scheduler Prelude (Zero C s7_gc_protect Bookkeeping)
Keeping *emu-tasks*, *emu-actions*, and *emu-hooks* in top-level s7 globals ensures s7's garbage collector traces every live continuation and closure automatically, and call/cc never crosses a C stack frame:
(define *emu-tasks* '()) ; list of (id label resume-thunk ready?-thunk ceiling-thunk)
(define *emu-actions* '()) ; alist of registered GUI/hotkey custom actions
(define *emu-hooks* (make-hash-table 8))
(define *emu-next-task-id* 1)
(define *emu-yield-esc* #f)
(define (emu/spawn label thunk)
(let ((id *emu-next-task-id*))
(set! *emu-next-task-id* (+ id 1))
(set! *emu-tasks*
(append *emu-tasks*
(list (list id label thunk (lambda () #t) (lambda () 0)))))
(emu/%recompute-ceiling!)
id))
(define (emu/cancel-task! id-or-all)
(set! *emu-tasks*
(if (eq? id-or-all #t)
'()
(let loop ((xs *emu-tasks*) (acc '()))
(cond ((null? xs) (reverse acc))
((= (caar xs) id-or-all) (loop (cdr xs) acc))
(else (loop (cdr xs) (cons (car xs) acc)))))))
(emu/%recompute-ceiling!))
(define (emu/yield-until label ready? ceiling-fn)
(if *emu-yield-esc*
(call/cc
(lambda (k)
(let ((id *emu-next-task-id*))
(set! *emu-next-task-id* (+ id 1))
(set! *emu-tasks*
(append *emu-tasks*
(list (list id label (lambda () (k #t)) ready? ceiling-fn))))
(emu/%recompute-ceiling!)
(*emu-yield-esc* 'yielded))))
;; Synchronous batch fallback (--script headless runner): drive slices directly
(emu/%run-sync-until! ready? ceiling-fn)))
Core C Primitives & Convenience Macro Library
| Category | s7 Binding / Macro | Behavior |
|---|---|---|
Universal debug_ctl Bridge | (emu/cmd str) | Executes any debug_ctl command string via in-memory DebugCtlSink; returns trimmed reply string (or signals 'emu-error on ERR ...). |
| Fast State & Memory | (emu/state) / (emu/instr-count) / (emu/pc) / (emu/reg sym) | Zero-parse plist/value accessors (:pc, :phase, :sp, :fp, :lp, :instr, :leds, :halted, :paused, :vram-hash, :vram-nonbg, :scsi-act, :eth-rx, :eth-tx). |
| 40-Bit Tagged Words | (emu/vma addr [count]) / (emu/pma addr [count]) / (emu/word dtp ptr [cdr]) | Reads/constructs 40-bit IvoryWords using s7's native 64-bit s7_int (#o octal & #x hex literals work natively: (emu/vma #o370001011000) -> '(:dtp 0 :cdr 0 :ptr #x... :raw #x...)). |
| Execution & Reset | (emu/pause) / (emu/resume) / (emu/nmi) / (emu/warm-reset) / (emu/power-reset [unpause?]) / (with-paused-cpu body ...) | Direct lifecycle control; with-paused-cpu uses dynamic-wind to pause during body and restore prior run state on exit. |
| Cooperative Waits | (emu/wait-steps N)(emu/wait-until pred? :max-steps M :slice S)(emu/wait-pc vma :max-steps M)(emu/wait-leds mask val :max-steps M)(emu/wait-vram-change :max-steps M)(emu/wait-vram-stable :quiet-steps Q :max-steps M)(emu/wait-genera-idle :quiet-steps Q :max-steps M) | Built on emu/yield-until + script_step_ceiling. Note: emu/wait-genera-idle checks scsi_act stability + Merlin run-light (zero? (logand leds #x02)) so Genera's animated who-line clock never causes false non-idle timeouts! |
| Console Input Helpers | (emu/key name) / (emu/type-line str :gap 50000) / (emu/send-keys item ...) / (emu/mouse dx dy [buttons]) | Pushes SLB key/chord/ASCII packets and yields :gap (50,000) guest instructions between edges so DUSCC/8237 RX DMA never overruns; records events into IvoryCheckpointStore for deterministic time-travel replay. |
| Custom GUI Actions | (define-action sym (:label "..." :menu "..." :hotkey "Ctrl+F5") body ...) | Registers sym in *emu-actions*; microui automatically populates the Actions menu and dispatches :hotkey (when mouse is uncaptured) by spawning body via emu/spawn. |
| Event Hooks | (emu/on-boot fn) / (emu/on-halt fn) / (emu/on-break vma fn) / (emu/on-watch kind addr fn) | Registers hardware breakpoints/watchpoints via IvoryCoreApi and invokes fn on the Main Thread when pending_hooks fires. |
| RTC Date Helper | (emu/rtc-year year [month day hour min sec]) | Computes :rtc-offset relative to host UTC (e.g. (emu/rtc-year 1993) satisfies unpatched Genera 8.3's pre-Y2K RTC check automatically!). |
4.4 Portable s7 Hardware E2E Suite (emu/tests/e2e_suite.scm)
Port all checks from emu/tests/test_e2e_puppet.sh into emu/tests/e2e_suite.scm (invoked via ivory-xl1200(.exe) --headless --rom ../ivory-fep-roms/fep330/rom.dump --script tests/e2e_suite.scm):
- Unattended 45M-step boot past ESDI init (
halted == #f,leds == #x04,vram-nonbg > 2000). - Interactive Device PROM menu via SLB + 8237 RX DMA (
Space,emu/wait-vram-change). - COW checkpoint capture, state mutation, deterministic
rewind, and sparse.snapsave/load round-trip. - CD-ROM (
macivory_cdrom.isowhen present) SCSI target 4 attach + Device PROMIFEP Kernelload verification. - Panel PPM / VRAM PBM export verification (
1084×840trim /1152×924full).
5. Phase 3: Integrated Disk Management (fep_convert) & Portable Serial Backends
5.1 Embedded Disk & FEPFS Toolkit (emu/include/ivory_fep_tools.h)
- Compile
fep_convert.cwith-DFEP_CONVERT_NO_MAINintoSHELL_SRCS(while keeping the standaloneivory-fep-convert(.exe)binary target). - Replace
fseeko/ftelloinfep_convert.cwithemu_fseek64/emu_ftell64. - Expose structured C functions (writing human-readable errors to
char *err_buf, size_t err_caprather thanstderrwhen called from GUI/s7):typedef enum FepImageFormat { FEP_IMG_UNKNOWN = 0, FEP_IMG_XL1200_FEPFS = 1, /* 'LABL' little-endian 1280B/block */ FEP_IMG_MACIVORY_FEPFS= 2, /* 'LBAL' big-endian (+ optional 0x400 prefix) */ FEP_IMG_SIMH_TAP = 3, /* SIMH .tap sequential tape */ FEP_IMG_BLANK_1280B = 4 /* Unformatted 1280B-aligned raw disk */ } FepImageFormat; typedef struct FepDirEntryInfo { char name[36]; char type[8]; uint32_t version; uint32_t byte_length; uint32_t first_dpn; uint32_t page_count; } FepDirEntryInfo; typedef struct FepImageInfo { FepImageFormat format; uint64_t file_bytes; uint64_t total_pages; uint32_t cylinders; uint32_t heads; uint32_t pages_per_track; uint32_t root_dir_dpn; uint32_t fep_dpn; size_t num_entries; FepDirEntryInfo entries[64]; } FepImageInfo; IvoryStatus fep_tools_probe(const char *path, FepImageInfo *out, char *err, size_t err_cap); IvoryStatus fep_tools_create_fepfs(const char *path, uint64_t size_mb, char *err, size_t err_cap); IvoryStatus fep_tools_create_blank(const char *path, uint64_t size_mb, char *err, size_t err_cap); IvoryStatus fep_tools_create_tape(const char *path, char *err, size_t err_cap); IvoryStatus fep_tools_convert_macivory(const char *src_path, const char *dst_path, char *err, size_t err_cap); - Host-Shell COW Overlay Commit & Reset (
scsi_overlay_commit_to_base/scsi_overlay_reset):- Reset/Discard Overlay: calls existing
api->scsi_wd33c93_import_overlay(&board->scsi, target_id, NULL, 0U)(already truncates.ovland clears RAM hash table inscsi_wd33c93.c:1960-2026). - Commit Overlay to Base Image: exports dirty blocks via
api->scsi_wd33c93_export_overlay, detachestarget_id, opensbase_pathr+b, writes eachScsiOverlayBlockatlba * block_sizeviaemu_pwrite,fflush+fclose, re-attachesscsi_wd33c93_attach_disk_overlay, and clears the overlay viaimport_overlay(..., NULL, 0U)(~25 LOC in shell, zeroIvoryCoreApigrowth).
- Reset/Discard Overlay: calls existing
- Expose matching
debug_ctlsubcommands (scsi commit <id>,scsi reset-overlay <id>,disk create-fepfs <path> <mb>,disk info <path>) ands7wrappers (emu/overlay-commit,emu/overlay-reset,emu/fep-create,emu/fep-info).
5.2 Portable Serial Channel A & Channel B Host Backends (serial_host.{h,c})
Wire api->console_hw_set_serial_callbacks(&board->console, &cb) to a 2-channel host adapter (ch 0 = Console/Diagnostic Ch.A, ch 1 = Bulkhead RS-232 Ch.B):
- Each channel uses two
4096-byte SPSC rings (tx_ringwritten byemu_threadinon_tx_byte, drained by Main Thread inserial_host_poll;rx_ringfilled by Main Thread fromEmuEndpoint, popped byemu_threadinpoll_rx_byte) plus anatomic_uint_fast8_t modem_bits(DCD | CTS | DSRasserted whenever a TCP/pipe peer is connected,0when disconnected). - Supported backend specs (
--serial-a <spec>,--serial-b <spec>,:serial-a/:serial-bindefine-machine, and live switching inmicroui/debug_ctl serial <a|b> <spec>):none(default)tcp-listen:<[addr]:port>(dual-stack IPv4/IPv6 single-client listener viaemu_ipc.c)tcp:<[addr]:port>(non-blocking outbound TCP client viaemu_ipc.c)pipe:<name_or_path>(\\.\pipe\<name>on Windows;AF_UNIXstream socket on POSIX)file:<path>(append-only TX capture file for boot/diagnostic logs)
6. Phase 4: microui Top Menu Bar & Floating Workbenches (ui_workbench.c)
6.1 Vendoring microui & Window-Space SDL_Renderer Composition
- Vendor
rxi/microui(emu/vendor/microui/{microui.c,microui.h}, MIT license) compiled as$(OBJ_DIR)/vendor/microui.o. - Clean Layer Separation in
sdl_console.c:state->pixels/state->texture(sdl_console_compose_frame) renders only the1084×812(trim) or1152×896(full) 1bpp VRAM + the passive 28px hardware LED bezel (1084×840or1152×924total).- Delete Legacy Pixel Popovers (~500+ LOC removed): remove
SdlPopoverMenu,PopoverLayout,BadgeHitboxes, clickablePAUSE/OFF/NMI/RST/KM/CD/TAPEhitboxes, andsdl_console_set_popover_for_testfromsdl_console.c. Keep the passive status LEDs (PWR,RUN,HLT,PAU,CAP,KMtag,SCSI 0..6,ETH RX/TX/CD) intact. - Window Viewport & Top Menu Bar:
- Define
#define XL1200_TOP_MENUBAR_HEIGHT 22. - Default window creation height increases by
+22px (total_h + XL1200_TOP_MENUBAR_HEIGHT) so the console starts at 1:1 pixel scale with zero vertical squeeze. - On each
sdl_console_flush_present():bool is_fullscreen = (SDL_GetWindowFlags(state->window) & SDL_WINDOW_FULLSCREEN) != 0U; int top_h = is_fullscreen ? 0 : XL1200_TOP_MENUBAR_HEIGHT; /* Letterbox console texture strictly inside (0, top_h, out_w, out_h - top_h) */ compute_letterbox_rect_offset(0.0f, (float)top_h, (float)out_w, (float)(out_h - top_h), state->width, state->height, &dst_rect); SDL_RenderClear(state->renderer); SDL_RenderTexture(state->renderer, state->texture, NULL, &dst_rect); ui_workbench_render(state->renderer, out_w, out_h, is_fullscreen); SDL_RenderPresent(state->renderer); - Because
microuidraws directly inSDL_Rendererwindow coordinates viaSDL_RenderFillRect,SDL_SetRenderClipRect, and oneSDL_SCALEMODE_NEARESTembedded8×14ASCII monospace bitmap font + icon texture, UI text stays razor-sharp at any window size whiledump-panelPPMs and.y4mrecordings remain 100% pure hardware captures!
- Define
6.2 Input Routing, Mouse Capture & SDL3 TextInput Rules
- Captured Mode (
con->mouse_captured == true):- All keyboard and mouse events go exclusively to the Symbolics console (
ivory_keymap+ hardware mouse).microuireceives zero input events. - Tapping
Right-Ctrlalone releases mouse capture (displayed on the right side of the 22px menu bar:[Mouse Captured — Right-Ctrl to release]).
- All keyboard and mouse events go exclusively to the Symbolics console (
- Uncaptured Mode (
con->mouse_captured == false):- Feed mouse motion/buttons/wheel and keyboard navigation/editing keys (
Backspace,Return,Tab, arrows,Ctrl+C/Ctrl+VviaSDL_GetClipboardText/SDL_SetClipboardText) tomu_Context. - SDL3 Text Input Gate: SDL3 suppresses
SDL_EVENT_TEXT_INPUTunless explicitly enabled. Aftermu_end(ctx)each frame:- If
!con->mouse_captured && ctx->focus != 0and!text_input_active: callSDL_StartTextInput(window). - If
(con->mouse_captured || ctx->focus == 0)andtext_input_active: callSDL_StopTextInput(window).
- If
- Action Hotkeys: When
ctx->focus == 0and no dropdown is open, check registered(define-action ... :hotkey ...)bindings (plusF11fullscreen toggle) before forwarding uncaptured keys. - Entering Mouse Capture: Left-clicking inside
dst_rect(VRAM area) entersSDL_SetWindowRelativeMouseMode(window, true)only when!con->cpu_paused && !rt->unconfigured && ctx->hover_root == NULL && !ui_menubar_open().
- Feed mouse motion/buttons/wheel and keyboard navigation/editing keys (
6.3 Top Menu Bar & Floating Workbench Specification
22px Top Menu Bar Layout
- Left menus:
Machine|Media|Net & Serial|Actions|Debug|View - Right inline status/quick-controls: active
s7task spinner +[Stop Task](when*emu-tasks*is non-empty),[Pause/Resume], keymap indicator[KM: XL1200], and mouse capture hint.
Floating Windows (microui Resizable/Draggable Containers)
- Machine Setup (
Machine -> Configure Machine..., auto-opened on unconfigured zero-arg launch):- Profile bar: current
.scmpath, Open.scm..., Save, Save As..., Save & Cold Boot (applies staged config + runsdebug_ctl_power_reset(..., unpause=true)). - Identity & NVRAM Tab: Main Board Serial (
uint32), Main Mfg Days, I/O Board #0 Serial, Part #, Revs, Monitor (Philips/Sony), MAC address (08:00:05:xx:xx:xxvalidator + Generate Symbolics MAC button),.nvramfile picker + Save NVRAM Now, RTC mode (Host UTCvsHistorical Year 1993/ custom offset). - Firmware & Memory Tab: Boot PROM path (
Browse...), optional IFEP Kernel path (Browse...), RAM size (8 MWdefault), Clock mode (Realtime/Deterministic), Idle Yield checkbox. - Control Actions (
Machinemenu):Pause / Resume,Send NMI (Drop to FEP),Warm VME Reset,Cold Power Reset,Quit.
- Profile bar: current
- Disk & Media Manager (
Media -> SCSI & Disk Manager...+ quick CD/Tape eject/attach inMediamenu):- SCSI Bus Table (Targets
0..6, showing FEP unit7 + id): kind (Disk/CD-ROM/Tape/Empty), path basename, size/geometry, mode (RO/RW/COW Overlaywith live dirty-block count), Attach..., Detach, and (whenoverlay_enabled) Commit to Base & Reset Overlay (with two-click confirmation). - FEPFS & Image Creation Tool:
- Create Initialized XL1200 FEPFS Disk (
256 MiB,512 MiB,1024 MiB, or custom MiB ->SDL_ShowSaveFileDialog->fep_tools_create_fepfs, with option to immediately attach on Target 0). - Create Blank SIMH
.tapTape / Create Blank Raw Disk. - Convert MacIvory Disk to XL1200 (
src->dst). - Inspect Image (
fep_tools_probedisplayingLABLgeometry,fep_dpn, and rootFEPDdirectory files).
- Create Initialized XL1200 FEPFS Disk (
- SCSI Bus Table (Targets
- Network & Serial Window (
Net & Serial -> Configure...):- Ethernet backend status (
User NAT (libslirp)/Linux TAP/Off), subnet CIDR, liveTX/RX/CDcounters, andhostfwdtable (Add/Removerules, applied on reset or slirp recreate). - Serial Ch.A & Ch.B live backend selectors (
None,TCP Listen,TCP Connect,Named Pipe / Socket,Log to File), address/path textbox, Apply, liveDTR/RTS/DCD/CTSindicators, and TX/RX byte counters.
- Ethernet backend status (
- Actions Menu & Custom Workflows:
- Dynamically lists every
(define-action ...)grouped by:menuwith its:hotkeylabel; clicking spawns the action on*emu-tasks*. IncludesLoad Script (.scm)...andCancel Running Actions.
- Dynamically lists every
- Debug, Snapshots &
s7REPL Windows (Debugmenu):- Snapshots & Time-Travel Checkpoints: Save
.snap..., Load.snap..., Take Checkpoint (with optional label + Pin checkbox), scrollable checkpoint list (ID,Instr,Label,Pinned, Rewind, Pin, Delete), unique COW pages / KiB meter, and auto-checkpoint interval controls. - CPU & Capture Tools: live
PC/SP/FP/LP/LEDsreadout, Breakpoint (0..7) & Watchpoint (0..3) add/clear controls,.y4mvideo recording Start/Stop, PBM/PPM screenshot save, and Hot-Reload Core (libivory_core) button. s7Lisp REPL Window: scrollable output transcript + single-line S-expression input (Enterevaluates ins7on Main Thread;Up/Downrecalls history; output of(display ...)/(format #t ...)captured vias7_open_output_stringport and appended to transcript).
- Snapshots & Time-Travel Checkpoints: Save
7. Implementation Phasing, /swarm Ownership Map & Verification Gates
Running with /swarm in This Jujutsu (JJ_Git) Repository:
Per workspace orchestration rules, use workspace: "inherit" with strictly disjoint per-worker file ownership within each phase, run per-worker gcc -fsyntax-only checks during parallel authoring, and serialize full make + Linux/Wine test gates through a single @verifier.
| Phase | New / Modified Files | Disjoint Worker Split (Optional /swarm) | Mandatory Verification Gates |
|---|---|---|---|
| Phase 1: Portable I/O, 2-Thread Runtime, MinGW-w64 & Wine CI | • emu/include/{ivory_emu.h,ivory_core_api.h,emu_os.h,emu_io.h,emu_ipc.h}• emu/src/{merlin.c,mem.c,core_api.c,eth_82586.c,eth_tap_linux.c,scsi_wd33c93.c,snapshot.c,core_loader.c,eth_slirp.c,emu_ipc.c,debug_ctl.c,main.c,sdl_console.c}• emu/tests/{test_debug_ctl.c,test_snapshot_reload.c,test_merlin.c}• flake.nix, emu/Makefile | • Worker A (Core & Shims): emu_os.h, emu_io.h, ivory_emu.h, ivory_core_api.h, merlin.c, mem.c, core_api.c, eth_82586.c, eth_tap_linux.c, scsi_wd33c93.c, snapshot.c• Worker B (Shell IPC & 2-Thread Loop): emu_ipc.{h,c}, core_loader.c, eth_slirp.c, debug_ctl.c, main.c, sdl_console.c (pthread->emu_os.h)• Worker C (Build & Wine Tests): flake.nix, emu/Makefile, test_debug_ctl.c, test_snapshot_reload.c, test_merlin.c | 1. nix develop --command make -C emu clean all test test-e2e2. readelf -WS emu/build/obj/core/*.o -> 0 bytes writable .data/.bss3. nix build .#windows & make -C emu dist-win4. x86_64-w64-mingw32-objdump -p emu/build-win/libivory_core.dll -> exports only ivory_core_get_api5. make -C emu test-win passes all 11 .exe unit suites under wine64 (verifying \\.\pipe\ivory-xl1200-*, IPv4 127.0.0.1 + IPv6 [::1] TCP, and live .dll reload). |
Phase 2: s7 Config, Macros, call/cc Workbench & Portable E2E | • emu/vendor/s7/{s7.c,s7.h,README.md}• emu/include/ivory_script.h• emu/src/emu_script.c• emu/src/main.c (--config, --script, --eval, script_step_ceiling, pending_hooks, .nvram lifecycle)• emu/tests/{test_s7_config.c,e2e_suite.scm}, emu/Makefile | • Worker A (s7 Engine & Prelude): emu/vendor/s7/*, ivory_script.h, emu_script.c• Worker B ( main.c Wiring & Suites): main.c, Makefile, test_s7_config.c, e2e_suite.scm | 1. test_s7_config (Linux) & test_s7_config.exe (wine64) verify (define-machine ...) serial/MAC/NVRAM survival across power-reset, CLI override precedence, byte-span Save Config preserving user define-actions, and cycle-exact call/cc script_step_ceiling.2. Native ./emu/build/ivory-xl1200 --headless --rom ivory-fep-roms/fep330/rom.dump --script emu/tests/e2e_suite.scm and make -C emu test-e2e-win (wine64) pass all authentic Boot PROM + SLB DMA + COW checkpoint + CD-ROM checks. |
Phase 3: Disk Toolkit (fep_convert) & Portable Serial Host | • emu/include/{ivory_fep_tools.h,ivory_serial_host.h}• emu/src/{fep_convert.c,serial_host.c}• emu/src/{debug_ctl.c,emu_script.c,main.c}• emu/tests/{test_fep_convert.c,test_serial_host.c}, emu/Makefile | • Worker A (FEPFS & Overlay Commit): ivory_fep_tools.h, fep_convert.c, test_fep_convert.c• Worker B (Serial Host & Bindings): ivory_serial_host.h, serial_host.c, debug_ctl.c, emu_script.c, main.c, test_serial_host.c, Makefile | 1. test_fep_convert(.exe) verifies in-process fep_tools_create_fepfs, fep_tools_probe (LABL/FEPD), MacIvory conversion, and COW .ovl commit-to-base & reset.2. test_serial_host(.exe) verifies Ch.A/Ch.B TX/RX + DCD/CTS status across IPv4/IPv6 TCP, Named Pipe/AF_UNIX, and file capture on both Linux and wine64. |
Phase 4: microui Top Menu Bar & Floating Workbenches | • emu/vendor/microui/{microui.c,microui.h,README.md}• emu/include/ivory_ui.h• emu/src/{ui_workbench.c,sdl_console.c,main.c}• emu/tests/{test_console.c,test_ui_workbench.c}, emu/Makefile | • Worker A (microui Atlas & Workbenches): emu/vendor/microui/*, ivory_ui.h, ui_workbench.c• Worker B ( sdl_console.c Popover Removal & Tests): sdl_console.c, main.c (zero-arg GUI launch), test_console.c, test_ui_workbench.c, Makefile | 1. test_console(.exe) & test_ui_workbench(.exe) (SDL_VIDEODRIVER=dummy) verify 1084×840 / 1152×924 .y4m & dump-panel dimensions are unchanged, 22px menu bar never overlaps VRAM, fullscreen auto-hides menu bar, mouse-capture click-through guard holds, SDL_StartTextInput toggles with mu_ctx->focus, and zero-arg launch opens paused Machine Setup.2. Full gate: make -C emu clean all test test-e2e dist-win test-win test-e2e-win exits 0. |
- Intel 8237A —
intel_8237A_dmac.pdf - Intel 82586 —
intel_82586_lan_coprocessor.pdf(mirror) - Intel 82586 —
intel_82586_reference_manual_1983.pdf(mirror) - Signetics SCN68562 / SCN26562 —
signetics_1991_IC019_data_comm_SCN68562.pdf(mirror) - Mostek MK48T02 / ST M48T02 —
st_M48T02_MK48T02_timekeeper.pdf