--- name: port-and-verify description: Use when a byte-matched, exactly linked DOS decompilation with a working modding build is to become a native program for macOS, Linux or Windows that behaves exactly as the original - the portability layer, link stubs, the platform layer, assembly through a static recompiler and then readable C, and verification against DOS by record and replay, golden references and routine fuzzing; with the sound library for Miles AIL 2 games, the null-pointer plan, the host hazard audits (literals written through, null reads, reads past tables and frames) and the black box that records players' sessions. --- # Port and verify Paths are relative to the Exhume checkout. docs/port.md is the method and the reasons; runtime/ is the porting harness every port builds against in place, never copied (runtime/README.md); examples/uw2/ has UW2's configuration, and Underworld Exhumed's uw2/src/port and uw2/src/include have UW2's bindings, the worked example. UW2's port (then UW2Decomp) went from Milestone 1 to Milestone 6a in about 21 hours this way (docs/case-study-uw2.md, "The port"). ## Before you start - The modding build works and its layout audit is done (skills/modding-build), and the readability pass has given you the gate (skills/readability-pass): every change to a shared source must pass `tools/gate.py check`, so the DOS bytes never change. - One tree, two builds. Port-only C goes in the port's directory, never in a game source; a shared-source change is a macro or type that is the original tokens under Turbo C. Add the port's directory to `[project] exclude`. - The runtime is a library. Never copy a runtime file into the project: the tools compile runtime/ where it is (`[port] runtime`; docs/port.md, "The runtime"), and the project writes only its bindings and its game's own C. A project with build scripts of its own finds the checkout as Underworld Exhumed's uw2/tools/exhume.py does and pins the Exhume commit it was proved with: best as a git submodule, as Underworld Exhumed does (`exhume/`), whose recorded commit CI checks out. A fix you find in the runtime goes into Exhume, proved on UW2 (examples/uw2/prove-port.sh) before the project moves its pin. ## Steps 1. **Measure.** Write the port's directory's `portgame.h` with at least your `PORT_NAME` and `PORT_GAME_MAIN` (runtime/README.md, "The project's side"), and a `hookgame.h` in the shared headers (empty until step 4); include `portable.h` from a shared header every source includes (the DOS build stages the runtime's beside yours). Fill in `[port]` (docs/config.md) and run `tools/portcheck.py`: per category, per file, and the names a link still needs. 2. **Compile and link.** Fix the errors, then the warnings that matter, each change proved by the gate: near pointers in integers become `NEARPTR`; calls get prototypes (`OLDSTYLE` where callers push an int for a char); `tools/widths.py` rewrites declarations to explicit widths; `tools/layoutcheck.py` must show every file record identical ([port.layout]); `tools/intaudit.py` lists the promotion sites, and the ones that can leave 16 bits get casts; `FAR_COPY` and `FP_OFF` for the far pointer idioms. `tools/portstubs.py` writes link stubs and `tools/portbuild.py` links: the port now runs until the first stub. 3. **Platform and machine.** The runtime's platform layer, paragraph map and far heap, EMS memory, VGA, Borland's library, records, crash handler, black box and game finder link as they are; give them what `portgame.h` names (DGROUP, `_ctype`, the exit chain, the black box: `PORT_BLACKBOX` and the calls in your main, runtime/README.md; the window's title and icon; what marks the game's folder), and write the C they call: `port_load_exe` and `port_check_exe`, `port_game_nulls`, the port's main and its diagnostics. If the game uses EMS, keep its own EMS entry points over `emm_open`, `emm_map` and `emm_close`. Load the far data no source defines from the user's own EXE at start-up, by the link's offsets; never ship it. Replace the system assembly (start-up, keyboard, mouse, timer) with C on the platform API. If the game draws its own cursor from relative motion, make the mouse driver steer it to the host's pointer (docs/port.md, "The platform layer": on each host move with `absolute` set, report the motion that puts the game's cursor at the pointer; none while it is still), and offer `PlatConfig.mouse_lock` for players who want DOSBox's captured mouse. First exit test: an opening screen whose scan-out equals a DOS screenshot of the same frame, pixel for pixel (hold both builds on it with a `for (;;)` in a modding build). 4. **Replay.** Put a hook on every read of the outside world (`GAME_TIME`, `KEY`, `MOUSE`, `MBUTTONS`, `JOY_*`, `WALL_TIME`, `SRAND`, `CHECKPOINT`), with their original tokens in `hookgame.h`, write `rpgame.h` in the shared headers for runtime/replay/replay.c (which the replay DOS build and the port compile where it is), give `[replay] link` the modding link with `--add`, and fill in `[replay]`. `tools/replay.py record` a session in js-dos, replay it twice in DOS (`replay.py dos`, then `compare --same-build`): two DOS runs must agree before the port means anything. If they part, it is stack junk or an unhooked read: `UWRPTRACE` (or your trace variable) shows the call where they part; give the local `STACK_JUNK(v)`, with v read from `tools/match.py --dis` on your own build, and record again. Then replay in the port and compare; mask only what is machinery ([[replay.mask]], with why), and compare far segments as blocks ([replay.segments]). 5. **Assembly.** Modules that pass state in registers, patch themselves, discard return addresses or use divide faults as control flow go through `tools/asm2c.py` ([asm2c] spec and overrides, runtime/port/x86/asmrt with your `asmgame.h` in the port's directory and your `asm_divfault`; the overrides and `asm_divfault` are the game's code, so they live in the project, never in Exhume); commit the output and run `--check` in the gate's company. Self-modifying code is read from the code block, generated code is interpreted, a DGROUP reference needs an override: never a JIT. Then make it readable from the leaves up: a routine moves to HANDWRITTEN when its C replays every session identically, with glue for the translated callers, and keep exactly one implementation of each routine (coverage says which side the sessions reach). 6. **Sound.** For a Miles AIL 2 game, runtime/port/sound and sys/pit.c link as they are: write `ailgame.h` in the port's directory (compat.h, then the game's own declarations of the AIL API); if the game's FM drivers were built with Origin's TVFX (`OSI_ALE`), translate their ALE.INC in the project and plug it into yamaha.h's `struct AilFmExt` ([sound] extensions, `AIL_FM_EXT`); fetch Nuked OPL3 with `tools/setup-sound.sh` ([[port.vendor]]) and link libmt32emu ([[port.pkg]]): never commit them (docs/third-party.md). Mark driver reads `SND_READ` and interrupt callbacks `SLAVE_TIMER`; check every driver against the game's own `.ADV` with `tools/ailcheck.py` (`replay.py drivers`), write for write. Record sound sessions with each card. 7. **Goldens and tests.** `tools/replay.py golden all` (DOS twice, identical, in DOSBox-X when installed), commit the goldens; `tools/replay.py verify all` replays the port against them in seconds. Write fuzz targets for routines no session reaches ([fuzz], `tools/fuzzasm.py`). Install the hook: `sh tools/install-hooks.sh PROJECT "make test"` (tools/templates/Makefile has `test`, `test-full`, `verify`, `golden`, `fuzz`, `coverage`). Run `tools/test.py full` before a release. 8. **Null pointers.** Mark every dereference the static analyzer or reading finds with `NULLTRAP`/`FARNULLTRAP` (`FARNULLREC` for a struct with the host's layout); the replay DOS build logs the marked ones it meets, the dumps carry C0's checksum and the vector table, and the UBSan build (`portbuild.py --debug`, `verify --debug`) reports any the sessions reach. Decide each: DOS's bytes, a guard, or a finding with a fix as an option. Then run the audits of "Host hazards" below. 9. **Other hosts.** Build and replay on x86-64 Linux as well as on your own machine: x86-64 aligns arrays of 16 bytes or more on 16-byte boundaries, so an overflow the original makes on purpose can land elsewhere (UW2's `OpenTheBag`); divide by zero traps on x86-64 and returns 0 on arm64. Every session must verify on every platform. CI: skills/ci-bundle. ## Host hazards DOS forgives what a modern host does not: a write into a string literal, a read through a null pointer, a read past a table or a local array. The sessions find only the cases they reach, so after the port verifies, audit the whole of the game's C for each kind, mark every site with its portable.h macro (the DOS bytes stay the same, proved by the gate), and make the goldens again for the replay build's new marks (every digest the same). UW2's port met three of these as crashes in players' hands, after every session verified; the audits then found about ten more. 1. **Literals written through.** Compile every game source for the host with clang's `-Wwrite-strings`, which makes a literal `const char[]`, so that every place one reaches a `char *` warns as `-Wincompatible-pointer-types-discards-qualifiers` (portcheck.py's flags plus `-Wno-everything -Wwrite-strings -Wincompatible-pointer-types-discards-qualifiers` keeps the output to those). Each warning is a literal reaching a `char *`; read each one and follow the pointer or parameter to see whether anything writes through it (an index store, a `strcpy` or `itoa` into it, a callee that patches a letter). Every one written through is `WRITABLE_STR(s)`. UW2: 297 places, three written through (sound file names built in place, a picture name's last letter patched by the player's sex, a number's digits written into `" 0\n"`). 2. **Null pointers.** Beyond the static analyzer (step 8), list from clang's AST (`-Xclang -ast-dump=json`, or a libclang script): global and static pointers that are 0 in some state of the game (a "current" object, an open container, no target), and every dereference of them that is not under a test; results of lookups that return 0 for "none" (find an object, a slot, a square), dereferenced without a test; and a literal 0 passed across files to a callee that dereferences that parameter (UW2: a scheduled trigger set off with no one setting it off read who set it off through 0L). Mark each `NULLTRAP`, `FARNULLTRAP`, or `FARNULLREC(p, layout)` where p points to a struct with the host's layout. Look hardest at a dereference that comes before the code's own null test: clang at -O2 deletes the test, since the dereference proves the pointer is not null, so the release build crashes there even when a debug build would not (UW2: a melee miss read the armour before testing it for null). 3. **Reads past the end.** Build the port with `-fsanitize=address` and again with `-fsanitize=array-bounds`, and replay every recorded session in each (`portbuild.py` with the flags added, then `replay.py verify`). Read each report against the original's assembly: a local array the original overruns into its own frame is `FRAME_LEN` (UW2: an 85-byte description in an 80-byte buffer, a 21-byte name in 20) or `FRAME_TAIL`, one indexed below its start `FRAME_INDEX`, a table indexed past its end or before its start into the table DOS has next to it `TABLE_NEXT` or `TABLE_PREV`. Two limits: ASan does not see inside one block, so an overrun within a far data block or a struct passes; and a different data layout is itself a test, since a table overrun that the normal build passes by luck (its tables fall in DOS's order) gives other values under ASan's layout: on UW2 two sessions differed from DOS under ASan only, which is how the mode-button table reads were found. Lessons from UW2: - **Read frame offsets from the assembly, never from the C.** `FRAME_TAIL`, `FRAME_INDEX` and `FRAME_LEN` model the original's stack frame, so take each offset from its instructions (`tools/match.py --dis`): which slot sits below the array, which byte the terminator store hits. UW2's port first put a terminator one byte early; the message text then broke at other places, with the same pixels on the screen and different scratch state behind them, which only the dumps showed. - **A far pointer split that would wrap.** The paragraph map gives a far pointer the segment and offset the DOS code made when it can, else splits it by its region; a split that puts a large object high in a segment wraps its offset at 64 KB part of the way through. Where the code then walks the object by offset, re-split it at the object's own paragraph (offset below 16) before the walk (UW2: a full-screen picture drawn by a routine that walks by offset drew another block's first bytes as a band across a cutscene). - **Pace the frames as the original's machine did.** A game that moves by the time since the last frame and writes positions back in whole units drops the fraction every frame; at a host's frame rate a slow move can come to nothing (UW2: walking backwards, rc8). Wait in the project's frame routine until the original's frame time has passed (UW2: 8 ticks of the 256 Hz clock), never under replay. - **Far returns.** A translated routine that ends in `retf` must be entered with `asm_run_far`; entered near, its return pops a word too few and returns past its C caller (UW2: a hang where the view dims on the stairs, rc8). - **Record the sessions players play.** A session that skips the cutscenes never runs them; record one that plays each through. Record ordinary play as well as the tests' targeted paths: a long walk with fights, looking at things, opening containers, talking, levelling up. Each of UW2's crashes in play was on a path no session reached. - **Hunt a divergence down to the routine.** The full checkpoints bracket it. Then `UWRPCK=1` with `UWRPFULL=lo,hi` over that bracket gives a full dump every tick and finds the tick; `UWRPHOOK=lo,hi` over that tick's hook calls finds the call after which a section first differs; then add a checksum of the suspect area, written at points traced from the code, to both builds, and the first point where the two differ is in the routine (docs/port.md, "The DOS side"). - **The black box.** Wire runtime/port/sys/blackbox.c into the port's main (runtime/README.md), so that every player's session is recorded and a crash report carries a recording that replays the crash exactly; close it when `plat_run` returns too, or a session ended by closing the window loses its last chunks. Replay it in the port and in DOS from its stage, fix the port, and record a session of that path. - **The faithful port proves only what its sessions reach.** Report coverage with every claim (`tools/coverage.py`), and treat every routine no session runs as unverified, however long the port has run without a crash. ## Rules - A session that differs from its golden after a change is a bug in the change; fix the port, never the golden. Regenerate goldens only when a recording or the replay DOS build changes, in the same commit. - Phase 1 is faithful: the original's bugs are reproduced by default, each fix an option, off by default, and the replays run with every option off. - Read undefined behaviour from our own build's code (AX at a function's end, a stack slot's value, a wrap), never guess it. - The port holds no game data and no byte of the EXE that the committed sources do not already hold; it reads the user's own copy at run time and checks it by size and CRC. - Report a milestone as met only with its exit test run: screens compared pixel for pixel, sessions identical at every checkpoint, drivers write for write.