aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit 7b24ddff03b0bc6265965c1addde29cd3c59bda8
parent 7272065a25febbfedb2d7ef9b86a77153887d646
Author: anon <anon@example.com>
Date:   Fri, 16 Oct 2026 11:42:10 +0000

Complete Linux audio adapters and validate Debian handoff

Diffstat:
MREADME.md | 7++++++-
Mdocs/README.md | 1+
Adocs/audio-audit.md | 138+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocs/linux-import-coverage.json | 6+++---
Mdocs/portable-assets.md | 11++++++++---
Msrc/Makefile.linux | 4++++
Msrc/runtime/linux_audio.c | 71++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Msrc/tests/audio.c | 83++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Asrc/tests/audio_decode.c | 115+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mtools/README.md | 5+++++
Atools/client/audit_audio_assets.py | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/audit_audio_imports.py | 37+++++++++++++++++++++++++++++++++++++
Mtools/client/linux_game_smoke.gdb.py | 6+++++-
Atools/client/test_portable_audio_decode.py | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mtools/client/verify_linux_game.py | 3++-
15 files changed, 637 insertions(+), 17 deletions(-)

diff --git a/README.md b/README.md @@ -106,7 +106,9 @@ source files. Python and the Windows virtual environment are not needed for ordinary builds. Debian 13 supplies the [SDL2 development package](https://packages.debian.org/trixie/libsdl2-dev) -and [Go 1.24](https://packages.debian.org/trixie/golang). +and [Go 1.24](https://packages.debian.org/trixie/golang). Its +[libsndfile 1.2.2 package](https://packages.debian.org/trixie/libsndfile1-dev) +also includes the MPEG decoder dependencies used by the Linux audio adapter. The server may need network access on its first build to download Go modules. ## Repository layout @@ -150,6 +152,9 @@ comes before WASM; Linux only needs windowed mode. Read [src/README.md](src/READ - Linux file access resolves the game's mixed-case names through `src/runtime/linux_path.c`. Test on a case-sensitive filesystem: running from `/mnt/c` alone can hide filename-case bugs that will fail on native Linux. +- Linux audio uses SDL2/libsndfile instead of Windows Miles plug-ins. The + [audio audit](docs/audio-audit.md) records asset coverage, tested API behavior + and the limits of the reverb investigation. - Hand editing or simplifying C is welcome when backed by evidence. Use focused contract tests and compare with Windows where possible; do not claim full equivalence from one successful screenshot. Keep changes small and avoid diff --git a/docs/README.md b/docs/README.md @@ -16,6 +16,7 @@ current feature status. Read the source for implementation details and the | Document | Contents | | --- | --- | | [portable-assets.md](portable-assets.md) | Asset-only Linux runtime, file-access auditing and native filesystem checks. | +| [audio-audit.md](audio-audit.md) | Complete sound-format audit, Miles replacements, differential checks and reverb investigation. | | [reconstruction-14.9.1.md](reconstruction-14.9.1.md) | Current generated-C baseline, runtime fix, BB capture, font comparison and rebuild workflow. | | [binary-inventory-14.9.1.md](binary-inventory-14.9.1.md) | Selected target's module hashes, scope and dependencies. | | [versions-and-patches.md](versions-and-patches.md) | Provisional 13.24 target, historical cutoff evidence, city-layout uncertainty, recovered patch inventory, and upgrade handoff checks. | diff --git a/docs/audio-audit.md b/docs/audio-audit.md @@ -0,0 +1,138 @@ +# Native Linux audio audit + +Checked the 14.9.1 assets and original sound-module imports on 2026-10-16. +The portable client uses SDL2 and libsndfile; Windows Miles DLLs and plug-ins +are neither needed nor loaded by Linux. + +## Shipped sounds + +The audit fully decoded every WAV using the same Linux libsndfile 1.2.2 library +linked by the game. Of 3,268 WAVs, 3,267 contain decodable audio and one is +intentionally empty. There were no open, decode or close failures. All use +one or two channels at 11,025, 22,050 or 44,100 Hz. + +| Group | Formats | +| --- | --- | +| Music | 771 MPEG layer III streams in WAV containers, 6 PCM samples | +| Effects | 2,423 IMA ADPCM WAVs, 25 PCM WAVs | +| Voices | 43 IMA ADPCM WAVs | + +The empty file, `sfx/env/nosound.wav`, is a valid 60-byte IMA WAV with zero +sample count and zero audio payload. The two SBF banks, SWS music project and +SFK editor file were inventoried separately, not passed to a sound decoder. +Successful decoding proves format coverage, not that every game event selects +and plays the correct sound. + +The MPEG "Illegal Audio-MPEG-Header" diagnostics occur at the end of the RIFF +audio payload, where metadata or padding starts. All 563 warning offsets were +checked. Three whole-file versus extracted-payload comparisons produced +identical decoded PCM hashes and frame counts. These warnings do not indicate +missing audio in those comparisons. Decoder frame estimates exceed readable +frames for the MPEG files; the adapter uses the actual returned frame count. + +## Calls and effects + +The import/string audit covers all 34 original game modules. Only `mmr.dll` +(effects) and `pr.dll` (music) import Miles. Neither imports LoadLibrary or +GetProcAddress. No game module imports DirectSound, and no reverb, filter, +3D-provider or panning control was found in the Miles imports. The two audio +modules open ordinary stereo wave-output drivers. + +REA/Ghidra traced `mmr.dll`'s environment-sound entry through its sound-selection +and layering logic. This is maintained game C and remains active on Linux. +There is no established call path to the bundled `.flt` or `.m3d` plug-ins. +Do not add global reverb just because the redistributable contains reverb +filters: that would change every sound without evidence of how AO selects it. +Dungeon reverberation may be recorded into assets or produced by game layering; +this audit does not establish which. No dungeon listening comparison has been +performed, and bounded static searches cannot exclude every dynamic behavior. + +## Implemented gaps + +- `AIL_decompress_ASI`: native MPEG layer III decoding into an owned PCM16 RIFF + buffer, including the optional output-size pointer and Miles-compatible + extension selection. Original `mmr.dll` at `0x10008430` (maintained + `sub_3A008430`) calls this only for file type 13, with no callback and no + size output. The original codec accepts `.mp3` and rejects `.wav` for this + API, even when the latter contains MPEG audio. This is distinct from music + streaming, which accepts the shipped WAV containers. The shipped effects and + voices themselves use PCM/IMA, so this import was a latent unsupported branch, + not evidence that all compressed music had been missing. +- Empty WAV handling: the original library rejects an empty sample without + crashing, but accepts an empty stream that completes without playing frames. + The adapter now matches that behavior instead of aborting on zero frames. +- `AIL_quick_shutdown`: preserves manually opened drivers. Miles only tears + down handles owned by `AIL_quick_startup`; AO never imports that initializer + and calls quick shutdown after ordinary device-open failure. This is a + verified no-operation in AO's usage, not a blanket success stub. + +Non-null ASI progress callbacks remain explicitly unsupported; AO's only call +passes null. The replacement mixer does not promise bit-identical Miles +resampling or volume quantization. Spatial audio, VOC and DSP filters have not +been added without a demonstrated game call path. + +The rebuilt resolver now binds all 32 unique Miles imports. Across all platform +libraries there are 286 implemented imports and 310 remaining unsupported +imports; API presence does not imply complete argument coverage. + +## Reproduction and evidence + +From the repository root on Linux: + +```sh +python3 tools/client/audit_audio_assets.py 2> local/client/audio-assets-audit.stderr.log +``` + +On Windows with the local reference client, compiler and WSL: + +```powershell +.\venv\Scripts\python.exe tools/client/audit_audio_imports.py +.\venv\Scripts\python.exe tools/client/test_portable_audio.py +.\venv\Scripts\python.exe tools/client/test_portable_audio_decode.py +``` + +The ordinary audio fixture compares sample/stream state, loops, rates, volume, +empty sounds and shutdown with Windows Miles, and checks mixed PCM through the +Linux SDL callback. The decompression fixture compares three music assets and +one extracted raw MPEG stream: formats and frame counts match exactly, with +RMS differences of 0.47-1.19 PCM16 integer steps and maxima of 36-61 steps. +It also checks output ownership, optional size, rejected inputs and guest ABI. +These are decoder comparisons, not a human listening assessment. +All 61 native regression programs passed. The audio and MPEG-decompression +fixtures also passed AddressSanitizer and UndefinedBehaviorSanitizer with SDL's +dummy output backend. Logs are `local/client/audio-regression.log`, +`audio-sanitized.log` and `audio-decode-sanitized.log`. + +The first real-game validation reached screenshot capture but timed out inside +debugger-injected GPU readback. The capture harness now permits Mesa worker +threads during that call. File tracing is disabled during debugger-injected +calls, including those readbacks; its report must not be described as exhaustive +over those intervals. The original failure log is +`local/client/audio-capture-timeout.log`. + +The repeated game run passed 700 frames, inventory/map opening and closing, and +server-confirmed movement from `[960, 16.375, 510]` to +`[954.5, 16.375, 504.5]`. All six captures were inspected. The client decoded +music without an audio fault and ran from the 4,042-file portable asset bundle; +the traced file accesses did not open other repository files. Evidence is in +`local/client/linux-game-smoke/` and `audio-game-verification.log`. The harness +stopped its client/server and restored preferences and the isolated character. + +Complete local reports are under `local/client/`: `audio-assets-audit.json`, +`audio-imports.json`, `audio-metadata-warnings.json`, `audio-metadata-check.json`, +`portable-audio-decode/report.json`, `audio-miles-rea.json` and `audio-game-rea.json`. +Proprietary audio and reference decoder outputs remain ignored. + +REA evidence: `ev_0c2f35b090c7208e04c039f61353507fbdaf1885b11215fb7c250e0076eb4db6` +is the game decompression caller; +`ev_ce9bdf90b4d5a4f3b0f225812d7bc04b661be3037b15e9f47c9bdb6b3398a568` +is Miles decompression; +`ev_4733328d64981bdf9c51eea4cbfe1a7e7b61d3e4fcc8a3b5d452bdbaf8947b4e` +is quick-shutdown ownership; +`ev_2789e481774ed87ed5eddce63f16ad1fda5c66d84395c66769c6e2f6ed1dfbbd` +is the game's stereo initialization; +`ev_53ca44d9da8cd295f86bae1139112d51e5f46de8630b27c2d57e6b38c80dae04` +and `ev_0e3d55e7ebdf4d027d9746a171896aab956f7c16a874f7a533cf8aebf88f22fb` +cover environment-sound dispatch and layering. Decompiler types are inferred; +the decompression call arguments were also checked in the maintained instruction +translation and exercised against the original DLL. diff --git a/docs/linux-import-coverage.json b/docs/linux-import-coverage.json @@ -1,5 +1,5 @@ { - "executable_sha256": "b7750b38af6c04cb4eb7eec1bfc26c5ae36d1d942971360df219df6facfd7286", + "executable_sha256": "148fa384aacd3eb041cf4ae02cc908f7c32a6537861c0d690f13e5b1d098cb49", "imports": [ { "dll": "KERNEL32.dll", @@ -2171,7 +2171,7 @@ "dll": "mss32.dll", "name": "_AIL_decompress_ASI@24", "ordinal": 0, - "adapter_found": false + "adapter_found": true }, { "dll": "mss32.dll", @@ -2219,7 +2219,7 @@ "dll": "mss32.dll", "name": "_AIL_quick_shutdown@0", "ordinal": 0, - "adapter_found": false + "adapter_found": true }, { "dll": "mss32.dll", diff --git a/docs/portable-assets.md b/docs/portable-assets.md @@ -36,9 +36,10 @@ movement/inventory/map input and captures six completed game frames. The wrapper rejects Windows binary files in the asset directory and repository reads outside that directory or the built executable. Inspect the recorded system paths too; the repository-path assertion is not a general filesystem sandbox. -Tracing pauses only around debugger-injected SDL/memory/framebuffer helper -calls, with other game threads held stopped. Normal game execution is traced; -those diagnostic host calls are not part of the recorded file-access set. +Tracing pauses around debugger-injected SDL/memory/framebuffer helper calls. +Other threads are held stopped except during GPU readback, when Mesa workers +must be allowed to run. File accesses during those helper calls are outside the +recorded set; the trace is not exhaustive over those intervals. Captures read the backbuffer that was just copied to the primary surface, before desktop clipping. The harness verifies that the copy's destination is @@ -116,3 +117,7 @@ creation, CRT file writing, locale and the portable runtime/linecrypt cases. The refreshed import audit remains 596 bound symbols: 284 adapters and 312 unimplemented symbols. This does not establish coverage of all possible game actions. Native Debian hardware, macOS and WASM have not been tested here. + +The subsequent [audio audit](audio-audit.md) records the newer Linux build, +another successful 700-frame test, and the updated import coverage. The Windows +executable is unchanged from the checkpoint above. diff --git a/src/Makefile.linux b/src/Makefile.linux @@ -293,6 +293,10 @@ build/linux/audio: tests/audio.c runtime/linux_audio.c runtime/guest_heap.c runt test: build/linux/audio +build/linux/audio-decode: tests/audio_decode.c runtime/linux_audio.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c runtime/linux_audio.h runtime/guest_heap.h runtime/guest_memory.h runtime/recomp_types.h runtime/linux_path.c runtime/linux_path.h + mkdir -p $(@D) + $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -pthread -lSDL2 -lsndfile -lm -o $@ + build/linux/strncmp: tests/strncmp.c runtime/guest_crt.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_crt.h runtime/guest_heap.h runtime/guest_memory.h mkdir -p $(@D) $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -lm -o $@ diff --git a/src/runtime/linux_audio.c b/src/runtime/linux_audio.c @@ -267,6 +267,13 @@ static void miles_shutdown(void) g_esp += 4; } +static void quick_shutdown(void) +{ + /* Mss32.dll FUN_21120b70 only releases AIL_quick_startup-owned handles. + AO uses waveOutOpen directly, so this must leave ordinary drivers alone. */ + g_esp += 4; +} + static void digital_latency(void) { uint32_t handle = MEM32(g_esp + 4); @@ -300,12 +307,12 @@ static void open_stream(void) SF_INFO info = {0}; SNDFILE *file = sf_open(path, SFM_READ, &info); if (file) { - if (info.frames <= 0 || info.channels < 1 || info.channels > 2 || + if (info.frames < 0 || info.channels < 1 || info.channels > 2 || info.frames > INT_MAX / (int)sizeof(float) / info.channels) abort(); - float *decoded = malloc(info.frames * info.channels * sizeof(float)); + float *decoded = malloc(info.frames ? info.frames * info.channels * sizeof(float) : 1); if (!decoded) abort(); sf_count_t frames = sf_readf_float(file, decoded, info.frames); - if (frames <= 0 || sf_error(file)) abort(); + if (frames < 0 || sf_error(file)) abort(); if (sf_close(file)) abort(); SDL_AudioStream *conversion = SDL_NewAudioStream(AUDIO_F32SYS, info.channels, info.samplerate, AUDIO_F32SYS, driver->format.channels, driver->format.freq); @@ -313,10 +320,10 @@ static void open_stream(void) SDL_AudioStreamFlush(conversion)) abort(); free(decoded); int size = SDL_AudioStreamAvailable(conversion); - if (size <= 0 || size % (sizeof(float) * driver->format.channels)) abort(); + if (size < 0 || size % (sizeof(float) * driver->format.channels)) abort(); struct audio_stream *stream = calloc(1, sizeof(*stream)); if (!stream || next_stream >= 0xf7000000u) abort(); - stream->samples = malloc(size); + stream->samples = malloc(size ? size : 1); if (!stream->samples || SDL_AudioStreamGet(conversion, stream->samples, size) != size) abort(); SDL_FreeAudioStream(conversion); stream->handle = next_stream++; @@ -437,6 +444,54 @@ static sf_count_t audio_read(void *output, sf_count_t count, void *context) return count; } +static void decompress_asi(void) +{ + uint32_t data = MEM32(g_esp + 4), size = MEM32(g_esp + 8), filename = MEM32(g_esp + 12); + uint32_t output = MEM32(g_esp + 16), output_size = MEM32(g_esp + 20), callback = MEM32(g_esp + 24); + g_esp += 28; + g_eax = 0; + if (!data || !size || !filename || !output) return; + if (callback) { fprintf(stderr, "Miles decompression callbacks are not implemented\n"); abort(); } + + /* mmr.dll sub_3A008430 requests MPEG layer III, with no callback. + Miles selects this codec by extension; a .wav filename is not accepted. */ + const char *extension = strrchr((const char *)ADDR(filename), '.'); + if (!extension || strcasecmp(extension, ".mp3")) return; + struct audio_memory memory = {(const unsigned char *)ADDR(data), size, 0}; + SF_VIRTUAL_IO io = {audio_length, audio_seek, audio_read, NULL, audio_tell}; + SF_INFO info = {0}; + SNDFILE *file = sf_open_virtual(&io, SFM_READ, &info, &memory); + if (!file) return; + if ((info.format & SF_FORMAT_SUBMASK) != SF_FORMAT_MPEG_LAYER_III || info.frames <= 0 || + info.channels < 1 || info.channels > 2 || info.frames > (INT_MAX - 44) / (2 * info.channels)) { + sf_close(file); + return; + } + + /* Return an owned PCM16 RIFF buffer, released by AIL_mem_free_lock. */ + uint32_t wave = guest_malloc(44 + info.frames * info.channels * 2); + if (!wave) { sf_close(file); return; } + sf_count_t frames = sf_readf_short(file, (short *)ADDR(wave + 44), info.frames); + int error = sf_error(file); + if (sf_close(file) || error || frames <= 0) { guest_free(wave); return; } + uint32_t bytes = frames * info.channels * 2; + memcpy((void *)ADDR(wave), "RIFF", 4); + MEM32(wave + 4) = bytes + 36; + memcpy((void *)ADDR(wave + 8), "WAVEfmt ", 8); + MEM32(wave + 16) = 16; + MEM16(wave + 20) = 1; + MEM16(wave + 22) = info.channels; + MEM32(wave + 24) = info.samplerate; + MEM32(wave + 28) = info.samplerate * info.channels * 2; + MEM16(wave + 32) = info.channels * 2; + MEM16(wave + 34) = 16; + memcpy((void *)ADDR(wave + 36), "data", 4); + MEM32(wave + 40) = bytes; + MEM32(output) = wave; + if (output_size) MEM32(output_size) = bytes + 44; + g_eax = 1; +} + static void init_sample_locked(struct audio_sample *sample) { free(sample->samples); @@ -519,9 +574,9 @@ static void sample_control(enum sample_operation operation, unsigned arguments) SF_INFO info = {0}; SNDFILE *file = sf_open_virtual(&io, SFM_READ, &info, &memory); if (file) { - if (info.frames <= 0 || info.channels < 1 || info.channels > 2 || + if (info.frames < 0 || info.channels < 1 || info.channels > 2 || info.frames > INT_MAX / (int)sizeof(float) / info.channels) abort(); - float *decoded = malloc(info.frames * info.channels * sizeof(float)); + float *decoded = malloc(info.frames ? info.frames * info.channels * sizeof(float) : 1); if (!decoded) abort(); sf_count_t frames = sf_readf_float(file, decoded, info.frames); if (frames > 0 && !sf_error(file)) { @@ -636,10 +691,12 @@ recomp_func_t linux_audio_lookup(const char *dll, const char *name) {"_AIL_waveOutClose@4", wave_out_close}, {"_AIL_set_digital_master_volume@8", set_digital_master_volume}, {"_AIL_shutdown@0", miles_shutdown}, + {"_AIL_quick_shutdown@0", quick_shutdown}, {"_AIL_digital_latency@4", digital_latency}, {"_AIL_open_stream@12", open_stream}, {"_AIL_file_read@8", file_read}, {"_AIL_file_type@8", file_type}, + {"_AIL_decompress_ASI@24", decompress_asi}, {"_AIL_allocate_sample_handle@4", allocate_sample_handle}, {"_AIL_init_sample@4", init_sample}, {"_AIL_release_sample_handle@4", release_sample_handle}, diff --git a/src/tests/audio.c b/src/tests/audio.c @@ -236,6 +236,78 @@ static void rejected_formats(uint32_t scratch) } } +static void quick_shutdown(uint32_t scratch) +{ + uint16_t format[] = {1, 2, 44100, 0, 45328, 2, 4, 16}; + memcpy(POINTER(scratch + 16), format, sizeof(format)); + uint32_t open[] = {scratch, 0, UINT32_MAX, scratch + 16}; + assert(!call("_AIL_waveOutOpen@16", 4, open)); + uint32_t driver = *(uint32_t *)POINTER(scratch); + uint32_t latency = call("_AIL_digital_latency@4", 1, &driver); + + call("_AIL_quick_shutdown@0", 0, NULL); + + assert(call("_AIL_startup@0", 0, NULL) == 0); + assert(call("_AIL_digital_latency@4", 1, &driver) == latency); + uint32_t sample = call("_AIL_allocate_sample_handle@4", 1, &driver); + assert(sample && call("_AIL_sample_status@4", 1, &sample) == 2); + call("_AIL_release_sample_handle@4", 1, &sample); + call("_AIL_waveOutClose@4", 1, &driver); + puts("audio quick shutdown: preserves manually opened driver and startup state"); +} + +static void empty_wave(uint32_t scratch) +{ + const unsigned char wave[] = { + 'R','I','F','F', 52,0,0,0, 'W','A','V','E', + 'f','m','t',' ', 20,0,0,0, 17,0,1,0, 0x44,0xac,0,0, + 0x6d,0x56,0,0, 0,4,4,0, 2,0,0xf9,7, + 'f','a','c','t', 4,0,0,0, 0,0,0,0, 'd','a','t','a', 0,0,0,0 + }; + memcpy(POINTER(scratch + 64), wave, sizeof(wave)); + uint16_t format[] = {1, 2, 44100, 0, 45328, 2, 4, 16}; + memcpy(POINTER(scratch + 16), format, sizeof(format)); + uint32_t open[] = {scratch, 0, UINT32_MAX, scratch + 16}; + assert(!call("_AIL_waveOutOpen@16", 4, open)); + uint32_t driver = *(uint32_t *)POINTER(scratch); + uint32_t sample = call("_AIL_allocate_sample_handle@4", 1, &driver); + assert(sample); + uint32_t load[] = {sample, scratch + 64, 1}; + + uint32_t loaded = call("_AIL_set_sample_file@12", 3, load); + + assert(!loaded); + assert(call("_AIL_sample_status@4", 1, &sample) == 2); + assert(call("_AIL_sample_playback_rate@4", 1, &sample) == 11025); + call("_AIL_start_sample@4", 1, &sample); + assert(call("_AIL_sample_status@4", 1, &sample) == 2); + call("_AIL_release_sample_handle@4", 1, &sample); + + FILE *file = fopen("miles-empty-test.wav", "wb"); + assert(file); + assert(fwrite(wave, 1, sizeof(wave), file) == sizeof(wave)); + assert(!fclose(file)); + strcpy(POINTER(scratch + 64), "miles-empty-test.wav"); + uint32_t stream_open[] = {driver, scratch + 64, 0}; + + uint32_t stream = call("_AIL_open_stream@12", 3, stream_open); + + assert(stream && call("_AIL_stream_status@4", 1, &stream) == 2); + call("_AIL_start_stream@4", 1, &stream); + for (unsigned i = 0; call("_AIL_stream_status@4", 1, &stream) == 4 && i < 1000; ++i) { +#ifdef _WIN32 + Sleep(1); +#else + SDL_Delay(1); +#endif + } + assert(call("_AIL_stream_status@4", 1, &stream) == 2); + call("_AIL_close_stream@4", 1, &stream); + call("_AIL_waveOutClose@4", 1, &driver); + assert(!remove("miles-empty-test.wav")); + puts("audio empty IMA WAV: sample remains uninitialized; stream opens and completes"); +} + static void sample_handles(uint32_t scratch) { uint32_t preference[] = {1, 4}; @@ -535,9 +607,18 @@ int main(int argc, char **argv) fprintf(stderr, "Windows reports no wave output device; device opening is not compared.\n"); call("_AIL_shutdown@0", 0, NULL); assert(call("_AIL_startup@0", 0, NULL) == 1); - } else { driver_lifetime(address); sample_handles(address); adpcm_sample(address); stream_seek(address); } + } else { + driver_lifetime(address); + quick_shutdown(address); + empty_wave(address); + sample_handles(address); + adpcm_sample(address); + stream_seek(address); + } #else driver_lifetime(address); + quick_shutdown(address); + empty_wave(address); sample_handles(address); adpcm_sample(address); stream_seek(address); diff --git a/src/tests/audio_decode.c b/src/tests/audio_decode.c @@ -0,0 +1,115 @@ +#include <assert.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#include <windows.h> +static HMODULE miles; +#define POINTER(p) ((void *)(uintptr_t)(p)) +static uint32_t allocate(unsigned size) { return (uint32_t)(uintptr_t)malloc(size); } +static void release(uint32_t data) { free(POINTER(data)); } +#else +#include "linux_audio.h" +#include "guest_heap.h" +#include "guest_memory.h" +#define POINTER(p) ((void *)ADDR(p)) +static uint32_t allocate(unsigned size) { return guest_malloc(size); } +static void release(uint32_t data) { guest_free(data); } +#endif + +static uint32_t call(const char *name, unsigned count, const uint32_t *args) +{ +#ifdef _WIN32 + FARPROC function = GetProcAddress(miles, name); + assert(function); + switch (count) { + case 0: return ((uint32_t (__stdcall *)(void))function)(); + case 1: return ((uint32_t (__stdcall *)(uint32_t))function)(args[0]); + case 6: return ((uint32_t (__stdcall *)(uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t))function) + (args[0], args[1], args[2], args[3], args[4], args[5]); + default: abort(); + } +#else + g_esp = 0x5000ff00; + g_ebp = 0x11223344; g_ebx = 0x22334455; + g_esi = 0x33445566; g_edi = 0x44556677; + MEM32(g_esp) = RECOMP_RETADDR; + for (unsigned i = 0; i < count; ++i) MEM32(g_esp + 4 + i * 4) = args[i]; + recomp_func_t function = linux_audio_lookup("mss32.dll", name); + assert(function); + function(); + assert(g_esp == 0x5000ff04 + count * 4); + assert(g_ebp == 0x11223344 && g_ebx == 0x22334455); + assert(g_esi == 0x33445566 && g_edi == 0x44556677); + return g_eax; +#endif +} + +int main(int argc, char **argv) +{ +#ifdef _WIN32 + assert(argc == 5); + miles = LoadLibraryA(argv[3]); + assert(miles); + uint32_t directory = (uint32_t)(uintptr_t)argv[4]; + call("_AIL_set_redist_directory@4", 1, &directory); +#else + assert(argc == 3); + assert(guest_map("audio decode test", 0x50000000, 0x10000)); +#endif + assert(call("_AIL_startup@0", 0, NULL)); + FILE *file = fopen(argv[1], "rb"); + assert(file && !fseek(file, 0, SEEK_END)); + long size = ftell(file); + assert(size > 0 && size < INT32_MAX && !fseek(file, 0, SEEK_SET)); + uint32_t input = allocate(size), scratch = allocate(128); + assert(input && scratch); + assert(fread(POINTER(input), 1, size, file) == (size_t)size); + assert(!fclose(file)); + + strcpy(POINTER(scratch), "fixture.MP3"); + uint32_t args[] = {input, size, scratch, scratch + 64, scratch + 68, 0}; + uint32_t *outputs = POINTER(scratch + 64); + outputs[-1] = outputs[2] = 0xa5a5a5a5; + outputs[0] = outputs[1] = 0; + + assert(call("_AIL_decompress_ASI@24", 6, args)); + + assert(outputs[-1] == 0xa5a5a5a5 && outputs[2] == 0xa5a5a5a5); + uint32_t wave = outputs[0], length = outputs[1]; + assert(wave && length > 44); + unsigned char *bytes = POINTER(wave); + assert(!memcmp(bytes, "RIFF", 4) && !memcmp(bytes + 8, "WAVEfmt ", 8)); + assert(*(uint32_t *)(bytes + 4) == length - 8); + assert(*(uint32_t *)(bytes + 16) == 16 && *(uint16_t *)(bytes + 20) == 1); + assert(*(uint16_t *)(bytes + 34) == 16 && !memcmp(bytes + 36, "data", 4)); + assert(*(uint32_t *)(bytes + 40) == length - 44); + file = fopen(argv[2], "wb"); + assert(file && fwrite(bytes, 1, length, file) == length && !fclose(file)); + + /* The game's actual call leaves the output-size argument null. */ + args[4] = 0; + outputs[0] = 0; + assert(call("_AIL_decompress_ASI@24", 6, args)); + assert(outputs[0] && !memcmp(POINTER(outputs[0]), bytes, length)); + call("_AIL_mem_free_lock@4", 1, outputs); + call("_AIL_mem_free_lock@4", 1, &wave); + + strcpy(POINTER(scratch), "fixture.wav"); + args[4] = scratch + 68; + outputs[0] = 0x11223344; outputs[1] = 0x55667788; + + uint32_t rejected = call("_AIL_decompress_ASI@24", 6, args); + + assert(!rejected && outputs[0] == 0x11223344 && outputs[1] == 0x55667788); + strcpy(POINTER(scratch), "fixture.mp3"); + args[1] = 0; + assert(!call("_AIL_decompress_ASI@24", 6, args)); + assert(outputs[0] == 0x11223344 && outputs[1] == 0x55667788); + release(input); + release(scratch); + call("_AIL_shutdown@0", 0, NULL); + puts("audio decode: PCM16 WAV, optional size, buffer ownership and rejected inputs passed"); +} diff --git a/tools/README.md b/tools/README.md @@ -17,6 +17,8 @@ and the C toolchain; normal server builds need Go. fixture users and checks the report. It runs from `anarchy-assets-14.9.1/`, rejects Windows executable content and records successful and failed file opens. The wrapper requires GDB inside WSL. + GPU readback permits worker threads to run; file tracing is paused during + debugger-injected calls, so the file report has that bounded coverage gap. - `client/prepare_portable_assets.py`: creates `anarchy-assets-14.9.1/` from an explicit list of data/configuration paths in the local Windows runtime. It refuses an existing destination and rejects executable content before @@ -24,6 +26,9 @@ and the C toolchain; normal server builds need Go. - `client/audit_linux_imports.gdb.py`: queries the compiled resolver to refresh `docs/linux-import-coverage.json`. An adapter being present does not imply every possible argument is implemented. +- `client/audit_audio_assets.py`: fully decodes the shipped WAVs using Linux + libsndfile. `client/audit_audio_imports.py` inventories the original modules' + audio imports. See [audio audit](../docs/audio-audit.md) for findings and checks. - `client/build_game.py`, `export_*.py`, `generate_*.py`, `link_game.py` and their support files: reconstruction/provenance tools, not the normal build pipeline. They depend on local upstream checkouts and saved analysis in `local/client/`. diff --git a/tools/client/audit_audio_assets.py b/tools/client/audit_audio_assets.py @@ -0,0 +1,102 @@ +"""Fully decode the shipped WAV files using the Linux host's libsndfile.""" +import collections +import ctypes +import hashlib +import json +import pathlib +import struct +import sys + + +class SoundInfo(ctypes.Structure): + _fields_ = [('frames', ctypes.c_longlong), ('samplerate', ctypes.c_int), + ('channels', ctypes.c_int), ('format', ctypes.c_int), + ('sections', ctypes.c_int), ('seekable', ctypes.c_int)] + + +# Use exactly the decoder shared library linked by the Linux audio adapter. +decoder = ctypes.CDLL('libsndfile.so.1') +decoder.sf_version_string.restype = ctypes.c_char_p +decoder.sf_open.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.POINTER(SoundInfo)] +decoder.sf_open.restype = ctypes.c_void_p +decoder.sf_readf_float.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_float), ctypes.c_longlong] +decoder.sf_readf_float.restype = ctypes.c_longlong +decoder.sf_error.argtypes = [ctypes.c_void_p] +decoder.sf_strerror.argtypes = [ctypes.c_void_p] +decoder.sf_strerror.restype = ctypes.c_char_p +decoder.sf_close.argtypes = [ctypes.c_void_p] + +root = pathlib.Path(__file__).resolve().parents[2] +source = root / 'anarchy-assets-14.9.1/cd_image/sound' +report_path = root / 'local/client/audio-assets-audit.json' +records = [] +for path in sorted(source.rglob('*')): + if not path.is_file(): + continue + data = path.read_bytes() + record = {'path': path.relative_to(source).as_posix(), 'bytes': len(data), + 'sha256': hashlib.sha256(data).hexdigest()} + records.append(record) + if path.suffix.lower() != '.wav': + record['status'] = 'non-wav-data' + record['magic'] = data[:16].hex() + continue + + # Retain RIFF chunk boundaries to distinguish audio payload from metadata. + if data[:4] == b'RIFF' and data[8:12] == b'WAVE': + record['riff_bytes'] = struct.unpack_from('<I', data, 4)[0] + 8 + chunks = [] + offset = 12 + while offset + 8 <= len(data): + name = data[offset:offset + 4].decode('ascii', errors='backslashreplace') + size = struct.unpack_from('<I', data, offset + 4)[0] + chunks.append({'name': name, 'offset': offset, 'bytes': size}) + if name == 'fmt ' and size >= 16 and offset + 24 <= len(data): + record['wave_tag'] = struct.unpack_from('<H', data, offset + 8)[0] + offset += 8 + size + (size & 1) + record['chunks'] = chunks + record['riff_unparsed_bytes'] = len(data) - offset + + # Read every frame, including data beyond the header's estimated length. + print(record['path'], file=sys.stderr, flush=True) + info = SoundInfo() + handle = decoder.sf_open(str(path).encode(), 0x10, ctypes.byref(info)) + if not handle: + record.update(status='open-failed', error=decoder.sf_strerror(None).decode()) + continue + record.update(header_frames=info.frames, rate=info.samplerate, + channels=info.channels, format=hex(info.format)) + buffer = (ctypes.c_float * (16384 * info.channels))() + frames = 0 + while True: + count = decoder.sf_readf_float(handle, buffer, 16384) + frames += count + if count < 16384: + break + error = decoder.sf_error(handle) + record['decoded_frames'] = frames + record['seconds'] = frames / info.samplerate + record['status'] = 'decode-failed' if error else 'decoded' if frames else 'empty' + if error: + record['error'] = decoder.sf_strerror(handle).decode() + record['close_error'] = decoder.sf_close(handle) + +# Keep complete per-file evidence and a compact machine-readable summary. +report = {'decoder': decoder.sf_version_string().decode(), + 'source': source.relative_to(root).as_posix(), + 'file_count': len(records), 'bytes': sum(row['bytes'] for row in records), + 'statuses': dict(collections.Counter(row['status'] for row in records)), + 'wave_tags': dict(collections.Counter(str(row.get('wave_tag')) for row in records + if row['path'].lower().endswith('.wav'))), + 'formats': dict(collections.Counter(row['format'] for row in records if 'format' in row)), + 'decoded_frames': sum(row.get('decoded_frames', 0) for row in records), + 'decoded_seconds': sum(row.get('seconds', 0) for row in records), + 'header_frame_mismatches': sum(row['decoded_frames'] != row['header_frames'] + for row in records if 'decoded_frames' in row), + 'records': records} +report_path.parent.mkdir(parents=True, exist_ok=True) +report_path.write_text(json.dumps(report, indent=2) + '\n') +print(json.dumps({key: value for key, value in report.items() if key != 'records'}, indent=2)) +print('Report: ' + str(report_path)) +if any(row['status'] in ('open-failed', 'decode-failed') or row.get('close_error', 0) for row in records): + sys.exit(1) diff --git a/tools/client/audit_audio_imports.py b/tools/client/audit_audio_imports.py @@ -0,0 +1,37 @@ +"""Record audio imports and plug-in/loader strings in the original game modules.""" +import hashlib +import json +import pathlib +import re + +import pefile + +root = pathlib.Path(__file__).resolve().parents[2] +rows = [] +for source in sorted((root / 'src/game').iterdir()): + if not source.is_dir(): + continue + path = root / 'anarchy-vanilla-14.9.1' / source.name + data = path.read_bytes() + pe = pefile.PE(data=data) + audio = [] + loaders = [] + for entry in pe.DIRECTORY_ENTRY_IMPORT: + for symbol in entry.imports: + name = symbol.name.decode() if symbol.name else str(symbol.ordinal) + item = {'dll': entry.dll.decode(), 'name': name, 'address': hex(symbol.address)} + if entry.dll.lower() in (b'mss32.dll', b'dsound.dll', b'winmm.dll'): + audio.append(item) + if name in ('GetProcAddress', 'LoadLibraryA', 'LoadLibraryExA', 'LoadLibraryW', 'LoadLibraryExW'): + loaders.append(item) + strings = [m.group().decode() for m in re.finditer(rb'[ -~]{5,}', data)] + matches = [s for s in strings if re.search(r'reverb|\beax[12]?\b|\.m3d|\.flt|\.asi|\b_?AIL_|DirectSound|dsound', s, re.I)] + rows.append({'module': path.name, 'sha256': hashlib.sha256(data).hexdigest(), + 'audio_imports': audio, 'loader_imports': loaders, 'audio_strings': matches}) + pe.close() + +output = root / 'local/client/audio-imports.json' +output.parent.mkdir(parents=True, exist_ok=True) +output.write_text(json.dumps(rows, indent=2) + '\n') +print('Scanned %d original modules; report: %s' % (len(rows), output)) +print('Static imports and printable strings do not establish runtime reachability.') diff --git a/tools/client/linux_game_smoke.gdb.py b/tools/client/linux_game_smoke.gdb.py @@ -62,7 +62,11 @@ def capture(label): width, height = struct.unpack('<II', inferior.read_memory(target, 8)) assert width > 0 and height > 0 pixels = int(gdb.parse_and_eval('(void*)malloc(%d)' % (width * height * 4))) + # Mesa may need its worker threads to complete synchronous GPU readback. + # File tracing stays disabled during this debugger-injected call. + gdb.execute('set scheduler-locking off') gdb.execute('call ((void (*)(void*, void*))gl_target_read)((void*)%d, (void*)%d)' % (target, pixels), to_string=True) + gdb.execute('set scheduler-locking on') data = bytes(inferior.read_memory(pixels, width * height * 4)) gdb.execute('call (void)free((void*)%d)' % pixels, to_string=True) (output / (label + '.rgba')).write_bytes(data) @@ -79,7 +83,7 @@ def on_present(): events = {510: ('i', True), 511: ('i', False), 540: ('i', True), 541: ('i', False), 570: ('p', True), 571: ('p', False), 600: ('p', True), 601: ('p', False), 630: ('w', True), 660: ('w', False)} - # Do not trace debugger-injected host calls; all other game threads stay stopped. + # Do not trace debugger-injected host calls; readback alone permits workers. if frame == 30 or frame in captures or frame in events: file_trace.enabled = False gdb.execute('set scheduler-locking on') diff --git a/tools/client/test_portable_audio_decode.py b/tools/client/test_portable_audio_decode.py @@ -0,0 +1,65 @@ +"""Compare the imported MPEG decompression path with Windows Miles.""" +import array +import json +import math +import pathlib +import struct +import subprocess +import wave + +root = pathlib.Path(__file__).resolve().parents[2] +work = root / 'local/client/portable-audio-decode' +work.mkdir(parents=True, exist_ok=True) +reference = work / 'reference.exe' +subprocess.run([ + str(root / 'toolchains/llvm-mingw-20261006-ucrt-x86_64/bin/i686-w64-mingw32-clang.exe'), + '-O2', 'src/tests/audio_decode.c', '-o', str(reference), +], cwd=root, check=True) +wsl_root = '/mnt/' + root.drive[0].lower() + root.as_posix()[2:] +wsl = ['wsl', '-d', 'Ubuntu-26.04', '--cd', wsl_root, '--exec'] +subprocess.run(wsl + ['make', '-s', '-C', 'src', '-f', 'Makefile.linux', 'build/linux/audio-decode'], check=True) + +# Exercise odd/even RIFF metadata boundaries and a raw MPEG stream. +fixtures = [root / 'anarchy-assets-14.9.1/cd_image/sound/music' / name for name in [ + 'env/battle/ClanDeath/ClanDeath01.WAV', + 'env/omni/day/OCD_01.wav', + 'env/mountain/night/mn03.wav', +]] +data = fixtures[0].read_bytes() +offset = 12 +while data[offset:offset + 4] != b'data': + size = struct.unpack_from('<I', data, offset + 4)[0] + offset += 8 + size + (size & 1) +size = struct.unpack_from('<I', data, offset + 4)[0] +raw = work / 'raw.mp3' +raw.write_bytes(data[offset + 8:offset + 8 + size]) +fixtures.append(raw) + +results = [] +for index, fixture in enumerate(fixtures): + expected = work / ('windows-%d.wav' % index) + actual = work / ('linux-%d.wav' % index) + windows = subprocess.check_output([ + str(reference), str(fixture), str(expected), + str(root / 'anarchy-runtime-14.9.1/Mss32.dll'), + str(root / 'anarchy-runtime-14.9.1/cd_image/sound/redist/win32'), + ], text=True, timeout=30) + linux = subprocess.check_output(wsl + [ + 'src/build/linux/audio-decode', fixture.relative_to(root).as_posix(), + actual.relative_to(root).as_posix(), + ], text=True, timeout=30) + assert windows == linux, (windows, linux) + with wave.open(str(expected)) as first, wave.open(str(actual)) as second: + assert first.getparams() == second.getparams(), (first.getparams(), second.getparams()) + left = array.array('h', first.readframes(first.getnframes())) + right = array.array('h', second.readframes(second.getnframes())) + errors = [abs(a - b) for a, b in zip(left, right)] + rms = math.sqrt(sum(error * error for error in errors) / len(errors)) + # Different MPEG decoders round differently; one PCM step is 1/32768 full scale. + assert rms < 2 and max(errors) < 128, (fixture, rms, max(errors)) + results.append({'file': fixture.relative_to(root).as_posix(), 'samples': len(left), + 'rms_pcm_error': rms, 'maximum_pcm_error': max(errors)}) + +(work / 'report.json').write_text(json.dumps(results, indent=2) + '\n') +print(json.dumps(results, indent=2)) +print('Windows/Linux decode contracts and PCM comparison passed.') diff --git a/tools/client/verify_linux_game.py b/tools/client/verify_linux_game.py @@ -61,7 +61,7 @@ def run_linux(): and not pathlib.Path(name).is_relative_to(client) and pathlib.Path(name) != root / 'src/build/linux/game'] assert not outside_assets, outside_assets - print('Asset audit: %d files, no Windows binaries; no other repository files opened.' % len(assets), flush=True) + print('Asset audit: %d files, no Windows binaries; no other repository files opened during traced execution.' % len(assets), flush=True) finally: if server.poll() is None: server.terminate() @@ -129,6 +129,7 @@ def run_windows(): 'frames': 700, 'movement_start': starts[0], 'movement_stop': stops[-1], 'executable_sha256': executable_hash, 'visual_review_required': True, + 'file_audit_excludes_debugger_calls': True, } (output / 'report.json').write_text(json.dumps(report, indent=2)) print(json.dumps(report, indent=2))