Files
BearddOddity 309bfbedfc docs: list every RECOMP_* switch in one page, and link it from the index
docs/INDEX.md stays the one index. Every page gets one navigation line under
its title that points back to it, and runtime/ gets a reference page for the
environment variables.

docs/runtime/environment-variables.md lists every RECOMP_* switch the runtime
and tools read: its default, its effect and the source file that reads it,
grouped as bring-up, kernel, pushbuffer executor, video, audio and input.
Fifty-one of them were not in the docs at all. docs/INDEX.md links it from
"Start Here".

No page is renamed, moved or rewritten, and no other index is added.

Checked: every RECOMP_* name read by getenv, env_on, apu_env_on, env_int or
xa2_env_int in src/, tools/, templates/ and include/ is on the page, and
every name on the page is in the source. All relative links in docs/ resolve
(0 broken, as at v0.16.0). The 34 existing pages change by insertion only:
68 lines added, none removed. docs/INDEX.md gains one line.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 04:59:55 -05:00

12 KiB

Lessons Learned

Part of the Documentation Index

Battle-tested advice from building the first Xbox static recompilation, based on 29 sessions of development on Burnout 3: Takedown.

Things That Worked Well

CreateFileMapping for Memory Layout

Using CreateFileMapping + MapViewOfFileEx instead of VirtualAlloc was the single most important architectural decision. The Xbox RAM mirror (addresses wrap modulo 64 MB) requires true memory aliases -- writes at address A must be visible at address B. File mapping views backed by the same section give you this for free. VirtualAlloc gives you separate physical pages and wasted us days of debugging before we switched.

// This works: mirror views alias the same physical pages
HANDLE mapping = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL,
                                     PAGE_READWRITE, 0, 64 * 1024 * 1024, NULL);
void *base = MapViewOfFileEx(mapping, FILE_MAP_ALL_ACCESS, 0, 0, size, hint);
void *mirror = MapViewOfFileEx(mapping, FILE_MAP_ALL_ACCESS, 0, 0, size, mirror_hint);
// Writing to *mirror actually modifies *base

// This does NOT work: separate physical pages
void *base = VirtualAlloc(hint, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
void *mirror = VirtualAlloc(mirror_hint, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
memcpy(mirror, base, size);  // only a snapshot, not a true alias

Global Register Model

Simple, correct, and surprisingly fast. MSVC optimizes global variable access well within basic blocks, and the register globals are always hot in L1 cache. The alternative (passing registers as function parameters to 22,000+ void(void) functions) would have been far more complex for no measurable benefit.

Bump Allocator for Xbox Heap

Xbox games allocate memory during initialization and rarely free it. A bump allocator (increment a pointer, never reclaim) works perfectly:

static uint32_t g_heap_next = XBOX_HEAP_BASE;

uint32_t xbox_HeapAlloc(uint32_t size, uint32_t alignment) {
    uint32_t result = (g_heap_next + alignment - 1) & ~(alignment - 1);
    g_heap_next = result + size;
    return result;
}

void xbox_HeapFree(uint32_t va) { /* no-op */ }

With 49 MB of heap space, this never runs out during a gameplay session. The simplicity eliminated an entire class of memory management bugs.

Binary Search Dispatch Table

22,097 entries, sorted by Xbox VA, searched via binary search. Maximum 15 comparisons per lookup. At ~120 ICALLs/second during gameplay, this is negligible overhead. We considered a hash table but the binary search is simpler, has no collision handling, and the sorted table is trivially generated by the recompiler.

Incremental Approach

We did not try to get the entire game working at once. The progression:

  1. Session 1-5: Get the XBE loaded, memory mapped, entry point called.
  2. Session 6-10: Fix crashes one at a time. Each crash reveals something about the game's architecture.
  3. Session 11-15: Stub or replace functions that depend on hardware we do not have (D3D, GPU, audio).
  4. Session 16-20: Get the game loop running with placeholder rendering.
  5. Session 21-29: Add real rendering, load game assets, iterate on visual fidelity.

Each session builds on the previous. The game "boots" from session 3 onward, even though most of it is broken. You can always see progress.

Things That Were Hard

Indirect Calls with Corrupted Vtables

By far the hardest problem. When game objects are not fully initialized (because we stubbed their constructors or the initialization depends on hardware we do not have), their vtable pointers contain garbage. Every garbage vtable pointer causes either:

  1. A crash (reading from an unmapped address).
  2. A dispatch to the wrong function (the garbage address happens to match a real function).
  3. A silent failure (the ICALL macro catches it and returns 0, but the caller expected a real return value).

We needed three layers of defense:

  • Centralized VA range check in RECOMP_ICALL (eliminates the most common garbage).
  • Per-function vtable guards for specific functions with known corrupt objects.
  • RECOMP_ICALL_SAFE for stack-safe failure recovery.

There is no silver bullet. Each new crash requires investigation to determine which object has a bad vtable and which function is calling through it.

Identifying Statically-Linked Libraries

The Burnout 3 binary has 2.73 MB of code. The game code, CRT, RenderWare engine, and XDK libraries (D3D8LTCG, DSOUND, XMV, XONLINE, etc.) are all linked into a single .text section with no symbols. Figuring out where one library ends and another begins, and which functions belong to which library, requires:

  • Pattern matching against known library signatures (FLIRT-style).
  • String reference analysis (error messages reveal library identity).
  • Call graph analysis (clusters of mutually-calling functions are usually from the same library).

This is painstaking work and we still have functions whose origin we are not sure about.

D3D8 to D3D11 Gap

Xbox D3D8's fixed-function pipeline (texture stage states, material lighting, fog) has no equivalent in D3D11. Everything must be emulated through HLSL shaders. The challenge is not writing the shaders -- it is knowing which D3D8 state combinations the game actually uses, and ensuring the shader produces matching output.

The COLOROP state alone has 25 possible values (DISABLE, SELECTARG1, SELECTARG2, MODULATE, MODULATE2X, MODULATE4X, ADD, ADDSIGNED, SUBTRACT, etc.), and there are 4 texture stages with multiple arguments each. Implementing all combinations is not practical; we implement only the combinations the game uses and add more as needed.

Reverse Engineering Game File Formats

Burnout 3 uses Criterion's proprietary file formats (.bgv for vehicles, .txd for textures, streamed.dat for tracks, PrgData.bin for progression data). No documentation exists. Every format must be reverse engineered from the binary and sample files:

  • BGV vehicles: 24-byte vertex stride with packed normals (11-11-10 bit signed), triangle strips with degenerate restart markers, pattern scanning for draw call descriptors.
  • TXD textures: RenderWare texture dictionary format with DXT-compressed data.
  • PrgData.bin: 3-level nested structure with relative offsets requiring base-address fixup.

Each format takes significant effort to understand, and subtle errors (wrong stride, wrong endianness, wrong interpretation of packed fields) produce visually wrong but not obviously broken results.

Mistakes Made

VEH Division-by-Zero Handler

We added a DIV0 handler to our Vectored Exception Handler early on, thinking it would prevent crashes from uninitialized data causing divisions by zero. It did prevent those crashes -- but it also prevented the game's own SEH recovery from working. Several game functions intentionally allow DIV0 and rely on their __except handler to take an alternate code path. Our VEH intercepted the exception first, skipped the faulting instruction, and returned a bogus result. The game continued with corrupted state.

Fix: Removed DIV0 handling from VEH entirely. Only handle exceptions that cannot possibly come from game code (like NV2A register faults at addresses we invented).

VirtualAlloc Mirror Copies

Our first memory layout used VirtualAlloc to allocate separate regions for the base and mirror addresses, then memcpy'd the base data to the mirrors. This appeared to work until the game wrote to a mirror address and the base data did not update. Debugging this took days because the writes succeeded (no crash), but the data was silently wrong.

Fix: Switched to CreateFileMapping with MapViewOfFileEx for true aliases. This was a fundamental architectural change that required rewriting the entire memory initialization.

Stack Leak from Failed ICALLs

When a RECOMP_ICALL lookup fails, the caller has already pushed a dummy return address. If the macro does not pop it, every failed ICALL leaks 4 bytes of stack space. With dozens of failed ICALLs per second (from corrupted vtables), the stack grew by several KB per second. With a 1 MB stack, the game crashed after about 4 minutes.

Fix: Pop the dummy return address on failure (g_esp += 4). Increased stack to 8 MB for additional headroom against argument leaks.

Running from Wrong Working Directory

Git Bash on Windows uses Unix-style paths (/e/burnout3), but the game looks for asset files relative to the Windows current directory. When launched from Git Bash with cd /e/burnout3 && ./bin/burnout3.exe, the CWD is set to the Unix-style path, and file loading fails.

Fix: Use cd E:/burnout3 (Windows drive-letter path) to set the correct CWD.

What We Would Do Differently

Start with File Format Reverse Engineering Earlier

We spent the first 20 sessions getting the game loop running with placeholder rendering. We should have started decoding the asset formats (.bgv, .txd, track data) in parallel. By the time we had a working renderer, we had a good understanding of the game's initialization sequence and could have been loading real assets much sooner.

Build Memory Access Tracing from Day 1

A tool that logs every MEM32 read/write with the caller's address would have saved enormous time debugging. Knowing "address 0x4D5370 was written by sub_000123AB at line 45" makes it trivial to find the source of corrupted data. We added logging incrementally and wish we had it from the start.

Invest in ICALL Diagnostics Sooner

The ICALL trace ring buffer and failure logging were added after weeks of debugging. They should have been in from the first ICALL implementation. The diagnostic tools are:

  1. Ring buffer: Last 16 ICALL targets, readable in debugger on crash.
  2. Fail log: Unknown VAs logged with _ReturnAddress() so you can look up the caller in the .map file.
  3. Rate counter: ICALLs per 2-second window, printed to stderr.

These three tools together turn a "mysterious crash" into "sub_001B4170 is calling VA 0x1C45BA68 which is a corrupted vtable in the object list" in about 2 minutes.

Better Function Classification

We should have classified all 22,097 functions early: game logic, CRT, RenderWare, XDK library, dead code. Instead, we discovered function identity reactively (when something crashed or misbehaved). A systematic approach using string references, call patterns, and library signatures would have let us stub entire libraries at once instead of one function at a time.

Key Insights

  1. The hardest 10% is indirect calls. Everything else -- memory layout, register model, direct calls, stack simulation -- is mechanical. Indirect calls require runtime dispatch with failure recovery, and corrupted vtable pointers make it adversarial.

  2. Games are more resilient than you think. Burnout 3 runs with dozens of stubbed functions, fake physics, placeholder rendering, and corrupted memory regions. The game loop keeps going. This is partly because games are designed to handle errors gracefully (frame drops, missing assets, hardware variations) and partly because Xbox games were built for a fixed platform where many edge cases simply never occur.

  3. One crash at a time. Do not try to understand the entire codebase before fixing anything. Boot the game, hit the first crash, fix it, repeat. Each crash teaches you something about the architecture. After 100 crashes, you understand the game.

  4. Log everything, but rate-limit. Logging every ICALL, kernel call, and memory access is essential for debugging but generates GB of output. Rate-limit to the first N occurrences plus every Kth after that:

    static int count = 0;
    count++;
    if (count <= 5 || (count % 1000) == 0) {
        fprintf(stderr, "[MIRROR-FAIL] #%d: addr=%p\n", count, addr);
    }
    
  5. The map file is your best friend. MSVC's linker map (burnout3.map) maps native addresses to function names. When a crash backtrace shows address 0x00007FF6A1234567, subtract the image base and look up the offset in the map to find which recompiled function is faulting. Combined with _ReturnAddress() in ICALL diagnostics, this is the primary debugging technique.