Navigation
Browse the developer docs

FH2 Modding Guide · Chapter 15

Debugging and finding your own hooks

You need a hook the guide doesn't list, or one misbehaves. Also how to load the game symbols.

By Trinculo54 · from the FH2 Modding Guide · CC BY 4.0 · copied 4 Dec 2026 · read the original, which may be newer

On this page

This chapter is for the moment the hook reference chapters run out: you need a place in the game nobody has documented yet, or a hook that should work doesn't. It covers what makes debugging FH2 under Azimuth unusual, debuggers and memory tools, crash reports and dumps, probe mods, offline test harnesses, practical static reverse engineering with small scripts, and a worked example that goes from a class name to a byte-checked hook. It ends with a checklist for a misbehaving hook.

All addresses are for forza_durango_release_final.exe of 24 Nov 2015 (TimeDateStamp 0x565501ED, SizeOfImage 0x3A18000), image base 0x140000000; see chapter 1. Everything marked "general approach, not tried here" is standard Windows practice that nobody has reported trying on FH2 yet.

15.1 What is different about FH2 under Azimuth

One process, and the game is not a module

Azimuth maps the Xbox One exe into its own process, azimuth.exe, by hand (chapter 1). For a debugger that has consequences:

What you expectWhat you get
a process called forza_durango_release_final.exeazimuth.exe, holding Azimuth, the game, Extra Options, the platform and every mod
the game in the module listit isn't there. GetModuleHandle(NULL) is azimuth.exe, and debuggers list only real DLLs and azimuth.exe
azimuth.exe at 0x140000000it prefers that base too, so it is loaded elsewhere to make room (a minidump showed it at 0x7FF73D150000)
symbols for the gamenone shipped. The exe exports about 700 names, almost all FMOD's. This guide's symbols folder builds a PDB with about 417,000 names and every function's size (15.3)
the game mapped when the process startsit is mapped only when the player presses Play (or picks FH2 in a multi-game Azimuth folder)

The game's code bytes are the same as on disk, apart from Extra Options' patches and other mods' hooks. Its unwind data is registered with Windows at run time: the platform's crash reports walk the stack through game frames with RtlLookupFunctionEntry, which only works if it is.

Finding the game's base

FromHow
A platform modapi->game_base() (NULL until the game is mapped, and NULL for good if Azimuth runs another game), or the return value of wait_for_code
An Extra Options pluginctx->game_image in FH2PluginInitialize's context; check ctx->game_image_size == 0x3A18000 first
A crash reportnot needed: game addresses are already written as game+0x...
A debugger or memory toollook for an allocation whose PE header has TimeDateStamp 0x565501ED and SizeOfImage 0x3A18000. On Windows it has always been at 0x140000000

The platform finds the game exactly that way: it walks the address space with VirtualQuery, and for each committed region that starts an allocation it copies the DOS and NT headers through an SEH-guarded copy and compares the machine, TimeDateStamp and SizeOfImage. The platform doesn't write the base to platform.log (2.9.2), so log it yourself once, as Director Mode does:

char line[96];
std::snprintf(line, sizeof line, "The game's code is ready at %p.", static_cast<void*>(game));
g_api->log(g_mod, line);

Relocation under Wine and Proton

Under Proton the exe has been seen at 0x14690000, 0x18940000 and 0x19D40000, with its absolute pointers relocated. RVAs and code bytes don't change, but:

  • every absolute address in a log, a debugger or a Cheat Engine table is only right for that session;
  • vtable pointers and globals that hold addresses differ from the disk copy by the load delta, so a check of a vtable slot against the exe on disk must subtract it (chapter 5);
  • write game+0xRVA in your logs, not the absolute address, so a log from a Proton player matches yours.

The game is ended, not closed

Azimuth ends the game with TerminateProcess. No DLL_PROCESS_DETACH, no destructors, no final log line. For debugging this means:

  • flush your log after every line, or the last lines before a hang or exit are lost;
  • a debugger sees the process vanish without any of your shutdown code running, and platform-session.json never says "ended";
  • a process that disappears with no crash report and no crashed state was either closed by Azimuth or died in a way that skips unhandled-exception filters (a stack overflow can, and so does __fastfail). General approach, not tried here: break on TerminateProcess and RtlFailFast in a debugger to tell them apart.

15.2 Debuggers and memory tools

Nobody in the FH2 community has written up attaching x64dbg, WinDbg or Cheat Engine to Azimuth, so most of this section is the general method, marked as such. What is known comes first.

What is known

  • Crash reports are the first tool. They need nothing attached and already speak game+0x... (15.3).
  • An in-process debugger works. FH2MP's research build of its client mod (never shipped) runs a small debugger inside the game on a localhost port: memory reads and writes, breakpoints, hardware watchpoints, a thread list and an event log. Its breakpoints are an int3 written over the first byte of an instruction plus a vectored exception handler; its watchpoints set the debug registers (Dr0-Dr3, Dr7) on every thread with SetThreadContext. It is the proof that both mechanisms work inside Azimuth's process on Windows.
  • Under Wine and Proton, hardware watchpoints may not fire. The same debugger falls back to page-guard watchpoints there, because the debug-register exceptions aren't delivered.
  • Pausing the process is visible. FH2MP's client logs "the whole process stood still" when its own thread misses its wake-up by seconds, and names a debugger as one cause. Online, a paused game is a disconnected game: only debug offline.

Attaching a debugger (general approach, not tried here)

  1. Start Azimuth and press Play. Attach x64dbg or WinDbg to azimuth.exe after the game has started, ideally once platform.log shows your hooks going in.
  2. Compute addresses from the base: 0x140000000 + RVA on Windows. In x64dbg, check the Memory Map for the region at 0x140000000 that starts with MZ. In WinDbg, .imgscan lists PE images found in memory; with the exe's folder in the image path, .reload /f forza_durango_release_final.exe=0x140000000,0x3A18000 should give it a module entry so u and ln work.
  3. Load your own mod's symbols (build with -gcodeview -Wl,--pdb=, 15.3). For the game, put the PDB from symbols in the symbol path (.sympath+) before the .reload above, so the module entry gets its names. Name what it doesn't know with RTTI (15.6), and add it to the folder's names.txt.

Things to expect, from what is known about the process:

  • Software breakpoints change code bytes. An int3 is a 0xCC in the game's code. Extra Options checks every one of its sites once, just after the game is mapped, and refuses all its patches on a single difference; the platform compares hook sites with the exe on disk ("game code doesn't match"); released mods check their sites in memory. A breakpoint in place when any of these look turns features off. Set software breakpoints only after the hooks are in, or use hardware breakpoints (four at most), which change no bytes.
  • A hooked function starts with a jump. On a site the platform hooked, the first five bytes are E9 into the hook chain. Break in your detour, or after the bytes the hook replaced, not on the function's first byte.
  • First-chance access violations are normal. Every guarded read (the platform's safe_copy, a mod's read_ok, ReadProcessMemory on its own process) that meets a freed or bad pointer raises one and recovers. Let first-chance access violations pass and stop on second-chance ones. The game also uses MSVC C++ exceptions (0xE06D7363) through msvcr110.dll/msvcp110.dll; whether it throws and catches any in normal play isn't established.
  • No crash report while a debugger is attached. The platform's report comes from an unhandled-exception filter (SetUnhandledExceptionFilter), and Windows doesn't call that filter for a process being debugged; the debugger gets the second-chance exception instead.
  • Don't sit in a breakpoint inside fh2mod_init for long. With several games in one Azimuth folder, the platform holds Azimuth at the game's start until every mod's fh2mod_init returns, but gives up after two minutes.
  • Under Wine or Proton, use winedbg or a Windows debugger inside the same prefix; expect hardware breakpoints to be unreliable (see above).

Memory tools such as Cheat Engine (general approach, not tried here)

  • Attach to azimuth.exe. The game's image is private memory, not a module, so scan settings that only look at module memory miss its globals. Scan all memory, or add the region at 0x140000000 by hand.
  • Heap objects move every session and are freed as the world streams. Build pointer paths from the globals in chapter 11 (for example CForza* at game+0x34ABA60), check each object's vtable, and expect a path through streamed objects to break when you drive away.
  • Many game heap objects sit at addresses like 0x00000600... (seen in probe logs); stack and Azimuth allocations are elsewhere.
  • Writing a value with a memory tool is the same as a mod writing it: fine for data, but never write game code before Extra Options has checked it, and never change a save.

A memory tool is good for finding where a value lives. Once you know, a probe mod (15.4) that reads it through a known path and logs it is quicker to repeat and works for players who send you logs.

15.3 Crash reports and dumps

Chapter 13 explains the report's lines. This section is about getting the most out of them.

What the platform writes

FileWhat
fh2-mods\crashes\crash-<date>-<time>.txtexception, faulting address, call stack as game+0x... / MyMod.dll+0x..., the mod it came from, every hook (* = on), PDB ids
crash-<date>-<time>.dmpa small minidump: threads, stacks, the memory they point at, and the writable data of every DLL the platform loaded
crash-<date>-<time>-full.dmpinstead, while fh2-mods\platform-dump.txt contains the word full: the whole process (several GB; only the newest kept)
platform.log"crash report saved in fh2-mods\crashes, with a small minidump (the data of N of the mods' DLLs, and M range(s) mods added)"
platform-session.jsonstate: crashed with the report's name

The ten newest reports are kept. Azimuth also keeps its own log and dumps in <Azimuth folder>\data\logs\.

A report where the game faulted but a mod was involved (trimmed, names changed):

CRASH: access violation (0xC0000005) at game+0x12E0DE0, thread 20556
platform: FH2 Mod Platform 2.8.0
  reading address 0xAB7B800000
call stack:
   0  game+0x12E0DE0
   1  game+0x12E1146
   2  game+0x12D2047
   ...
no mod was on the walked call stack; mod code referenced on the stack: MyMod.dll
hooks (* = on):
  * MyMod: function game+0x384C00 (CWorldCollObjMan::Update)
PDBs of the mods' DLLs (for symbols):
  MyMod.dll: MyMod.pdb {...} age 1

"Referenced on the stack" means a return address into your DLL was found below the faulting frame, past where the walk stopped: your detour called into the game, and the game crashed further down. Look at what your detour passed in. A crash in a DLL the platform didn't load (an Extra Options plugin, for example) is still named as ThatPlugin.dll+0x..., found through GetModuleHandleEx.

Put your own state in the dump

  • From platform 2.8.0 your DLL's globals are in every small dump.
  • State on the heap needs add_dump_memory (API 9): call it once for each table you want to see after a crash.
if (api->api_version >= 9)
    api->add_dump_memory(mod, g_tracked, sizeof g_tracked);   // 1 B to 64 MB; 64 ranges across all mods
  • When you are chasing one crash on your own machine, put full in fh2-mods\platform-dump.txt until you have it.

Symbols for your mod

llvm-mingw release builds are stripped. A stripped DLL still carries a build id, so the report lists it with an empty PDB name; there are no symbols to find for it. For a build you hand out to testers:

  • build with -gcodeview -Wl,--pdb= and keep the PDB of every build you hand out, next to a copy of the DLL;
  • tell builds apart by hash, since test builds often keep a version number.

To turn MyMod.dll+0x1A2B into a line (general approach, not tried here with a PDB): llvm-mingw's DLLs default to image base 0x180000000 (check with llvm-objdump -p MyMod.dll | grep ImageBase), so

llvm-symbolizer --obj=MyMod.dll 0x180001A2B

with the PDB beside the DLL. Visual Studio and WinDbg do the same when you open the .dmp with the PDB's folder in the symbol path.

Reading a minidump with lldb (tried on a platform dump)

llvm-mingw ships lldb, which opens the platform's dumps directly (output trimmed):

$ lldb --batch -c crash-...dmp -o "thread list" -o "thread select 48" -o "bt 6"
* thread #48: tid = 0x8b74, KERNELBASE.dll`RaiseException + 138, stop reason = Exception 0xe06d7363 ...
  * frame #0: 0x00007ffd177b569a KERNELBASE.dll`RaiseException + 138
    frame #1: 0x00007ffc2464e980 msvcr110.dll`_CxxThrowException + 212
    frame #2: 0x00007ffc4586fdde msvcp110.dll`void std::_Xlength_error(char const *) + 54
    frame #3: 0x0000000140229c13
    frame #4: 0x00000602540574d8
    frame #5: 0x000000e9a19fed38

What this shows:

  • The crashing thread is the one with a stop reason. Game frames are bare addresses (0x140229c13 is game+0x229C13), because the game isn't a module.

  • lldb can't unwind through game frames in a small dump. Frames 4 and 5 above are a heap and a stack address, not code. Use the report's call stack for game frames: the platform walked them live.

  • memory read works for memory the dump holds. The bytes round a frame's return address are there, and match the exe on disk:

    (lldb) memory read --size 1 --count 8 0x140229C0E
    0x140229c0e: 15 6d 6a ba 01 cc 48 8b
    
  • image list lists azimuth.exe, the platform, Extra Options and every mod with its load address, so MyMod.dll+0x... from the report can be checked against the dump.

That crash, decoded with the exe (15.6): game+0x229BF0 is a small MSVC STL helper that compares a length with -2, loads the string "string too long" and calls std::_Xlength_error in msvcp110.dll. Something asked a game string to grow past its limit, which points at a bad length passed in from further up the stack.

Symbols for the game (tried on a platform dump)

The game ships without a PDB, so this guide's symbols folder builds one: gen.py writes a PDB with the exe's own GUID and age ({F535A6BF-9F04-4208-8C98-F60AC12E04A9}, age 1), so tools accept it as the real one. It holds names and function sizes only, no types or source lines. The names come from the exe's exports, RTTI, the methods and properties the game registers with its own reflection system, constructors and destructors told by the vtables they store, the strings the game logs, the addresses in this guide and in open mods, and names.txt. A virtual function named in one class gives its name to the same slot of every related class. Every other function is sub_<address>. The pieces split off a function are Function$chunkN, and its catch blocks and unwind actions, which the linker puts far away from it, are Function$catch$N and Function$dtor$N.

Two kinds of name need reading with care:

  • A name ending in ? is a guess (AVUI::Object::IsType?, States::AdvanceIE::Enter?). Nothing in the exe gives that name; it comes from reading what the code does, and each one has its reason beside it in the folder's names-guess.txt or slots-guess.txt. Treat it as a hint about what the function is for, and check the code before you build on it.
  • A name starting with stub_ says what a shared one-line function does, not whose it is: stub_do_nothing, stub_return_0, stub_get_qword_at_18. The linker folded thousands of identical functions into one address, so no class name would be right for it.

Because the game isn't a module, give it one, then look addresses up. In lldb, with the exe and the PDB in the current folder:

$ lldb --batch -c crash-...dmp -o "target modules add forza_durango_release_final.exe" \
       -o "target modules load --file forza_durango_release_final.exe --slide 0" \
       -o "image lookup -a 0x1412CC7A0"
      Summary: forza_durango_release_final.exe`CollisionWorld::GetPolys + 112

image lookup -v adds the function's range, and image lookup -n Name finds a name. Under Wine or Proton, use the game's real base as the slide (--slide 0x... is the base minus 0x140000000).

Without any debugger, the folder's lookup.py reads game+0x... addresses straight from a crash report:

$ python lookup.py <pdb folder> forza_durango_release_final.exe 0x1412CC7A0
0x1412CC7A0: CollisionWorld::GetPolys+0x70 (size 0x4e0)

In Ghidra (tried with 12.2, headless, through the same PDB analyser the menus use), the exe is an ordinary file, so no module trick is needed. Import forza_durango_release_final.exe, then either put the PDB beside the exe before the first auto-analysis, or use File > Load PDB File afterwards. The PDB Universal analyser takes about 20 seconds. It creates all 170,286 functions, so every function start is known before Ghidra's own analysis runs, and names them from the PDB. Function bodies come from Ghidra's own disassembly. Where it follows the code, they match the PDB's sizes, for example 0x4E0 for CollisionWorld::GetPolys. Ghidra writes spaces in names as _ (std::_Median<int_*>), and warns about a few dozen C++/CX vtable names it can't parse; both are harmless.

In x64dbg (tried, attached to azimuth.exe with the game running), give the game a module entry first, then load the PDB for it. In the command box:

virtualmod forza_durango_release_final.exe, 140000000, 3A18000
symload forza_durango_release_final.exe, C:\path\to\forza_durango_release_final.pdb

If symload reports a mismatch, add , 1 to force it. The disassembly then labels functions (CollisionWorld::GetPolys at 1412CC730), and the address bar reads forza_durango_release_final.exe:$12CC730 <CollisionWorld::GetPolys>. A function another mod has hooked keeps its name, but starts with that mod's jmp, and the bytes after it decode as nonsense, because the jump overwrote the start of the original code. Leave with Debug > Detach: stopping the debugger ends the game.

The PDB is also offered ready-made as a release download.

lookup.py and lldb were tried on a platform dump, Ghidra on the exe, and x64dbg on the running game. WinDbg, Visual Studio and IDA are untested; WinDbg should work through the .reload line in 15.2.

15.4 Probe mods

A probe mod is a small, private test mod that answers questions about the game in one session: it hooks what you want to understand, logs what it sees in plain sentences, and offers hotkeys that dump state or try one change at a time. Much of what this guide documents about cameras, the HUD, achievements' events and car ghosting was settled this way, by a camera probe, a HUD probe, an achievements probe and the probe CCBR started as. A probe run answers in minutes what can take days of static reading, and its log is evidence you can check later.

Design the run before the code

  1. Write the questions first. Number them (P1, P2, ...) and give each one the log line that answers it and what counts as a pass. "Does the camera override hold 1:1 with the game's frames, running and paused?" becomes "count ticks and overrides; pass if every tick has exactly one override, in both states".
  2. Split what the log can answer from what only a person can see or hear. The log can't see the screen or hear the speakers. The tester notes only those things; everything else is in the log.
  3. Plan a session as numbered steps with the key to press and what to do in the game, short enough to play in 10-20 minutes. Put the riskiest or most important question first.

Build it so it can't hurt

  • Read only, or put everything back. Every test undoes what it changed when it ends, and one "put everything back" key undoes all of them at any time. Never touch saves; mark the probe offline_only (API 9).
  • Byte-check every site at start-up and log one summary line ("byte checks: car chain ok, packet builder ok, ..."). Split hooks into essential and optional: an optional hook that fails turns off only its own test, and the log says which.
  • Do game-thread work on a game thread. A dump that calls the game's own getters runs inside a hook the game called (an instruction hook on a per-frame site is ideal: the platform catches a crash in the callback and switches that hook off). Hotkey callbacks only set a flag.
  • Set every flag before enable_hooks. Hooks go live one by one inside the call, so a detour can run before it returns. One probe's start-up step raced its own hooks exactly like this.
  • Keys that don't clash. Extra Options and other mods take some F-keys; Ctrl plus the number row (one test per number, Shift for a second action) has worked well. With API 9 hotkeys the tester can rebind them on the Mods page. Handle one key press per frame, and refuse a key that can't run now with a cue rather than ignoring it.
  • Give the tester cues. A short sound and a blink for "started", "stopped", "done" and "refused" lets the tester keep their eyes on the game. Play them through the game's audio or PlaySoundW: on one test PC the Windows system sounds were muted, so every MessageBeep cue was silent.

Log lines that answer questions

  • One line per event, a full sentence, with the time and the frame: [ 52.773 f5532 ] stacks: c0-c7 [car control 8D4D37FF: C0]. The frame counter (from your per-frame hook) lets you tell "same frame" from "next frame".
  • Rate-limit noisy events: the first 40 of each kind, then every 100th, with a running count.
  • Log a value in every plausible type while you don't know it yet: = 16 (f 2.24208e-44, raw 10, type 3) shows at a glance that it's an integer.
  • Write game+0xRVA for anything inside the image, and the vtable's RTTI name for an object ("controller manager at 0x24949D01650 (vtable checked)").
  • Summaries on demand. A "report" key that writes counts and the state of every test makes the end of a session easy to judge.
  • Flush after every line (15.1).

Judge the run from the logs

  • Copy the logs straight after the run (they're rewritten every launch), with the tester's notes.
  • Give every question a verdict: pass, pass with notes, partial, fail, not exercised or unknown, each with the log lines that prove it.
  • If the session was recorded on video, find one event visible in both (a menu opening, a cue's blink) and note the offset once: "clip time = log time - 22:34:35.34". Every log line can then be found in the clip.
  • Anything surprising becomes a question for the next run, not a guess in the design.

Probes found things no static reading would have: the game pauses itself when its window loses focus; placing the car at a route locator makes a second camera update in the same frame with dt 0; the free-roam replay buffer holds only 16-22 seconds; a replay controller rewrites the game speed every frame after the update, so a speed set earlier is lost; and a start-up race where another mod's hook on the same function sometimes won.

Platform features that help

FeatureAPIUse in a probe
log1your lines in platform.log, prefixed with your mod's name
session_log_path(mod, L"MyProbe", keep)9a log file per session in <Azimuth folder>\MyProbe\logs\, older ones pruned
session_id()9tie your log to platform.log (line 3) and to the crash report
add_hotkey9test keys and pad chords the tester can rebind
add_command + fh2mod.exe9ask the running game from a terminal: fh2mod MyProbe dump cars
request_save_snapshot(mod, reason, keep)9from fh2mod_init: a copy of the save folder before the session, for safety
add_dump_memory9the probe's tables in any crash dump
hook_instruction7read registers mid-function without writing a stub; crashes in your callback are caught

Details of each call are in chapter 2. A command is often better than a hotkey for a probe: it doesn't need the game window focused, takes arguments, and its reply (up to 16 KB) comes straight back to your terminal. Extra Options plugins have none of these; log to your own file and poll GetAsyncKeyState.

15.5 Offline testing: a harness that maps the real exe

Most mistakes in a hook (a wrong RVA, a byte check that fails, a feature that turns itself off for the wrong reason, a guard that doesn't guard) can be caught without starting the game. The community's mods do it with a harness: a small program that maps the real exe from disk and runs the mod against it. Two public examples are CCBR's tests/harness.cpp and Director Mode's tests/exe_harness.cpp.

Two shapes

ShapeHowCatches
Fake platformcompile your mod's source into the test (or load the DLL) and hand it an FH2ModApi whose hook_function, log and wait_for_code are your own functions that record what was askedwhich hooks the mod asks for, at which RVAs, and what it logs when a check fails
Real platformname the harness azimuth.exe, lay a folder out like an install (d3dcompiler_47.dll, fh2-mods\MyMod.dll, FH2\Mount\forza_durango_release_final.exe), map the exe and let the platform load your modthe whole start-up: wait_for_code, the platform's own disk checks, chaining, refusals, your log lines in platform.log

Mapping the exe

// Map the game as Azimuth does on Windows: at its preferred base, sections copied, protections set.
// None of the game runs; imports are not resolved.
static char* map_game(const wchar_t* path) {
    std::ifstream in{path, std::ios::binary};
    std::vector<char> file((std::istreambuf_iterator<char>(in)), {});
    auto* nt   = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() +
                 reinterpret_cast<IMAGE_DOS_HEADER*>(file.data())->e_lfanew);
    auto* base = static_cast<char*>(VirtualAlloc(reinterpret_cast<void*>(nt->OptionalHeader.ImageBase),
                 nt->OptionalHeader.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
    if (!base) return nullptr;
    std::memcpy(base, file.data(), nt->OptionalHeader.SizeOfHeaders);
    auto* sec = IMAGE_FIRST_SECTION(nt);
    for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i)
        std::memcpy(base + sec[i].VirtualAddress, file.data() + sec[i].PointerToRawData,
                    std::min(sec[i].SizeOfRawData, sec[i].Misc.VirtualSize ? sec[i].Misc.VirtualSize
                                                                           : sec[i].SizeOfRawData));
    for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i) {
        DWORD c = sec[i].Characteristics, old;
        DWORD prot = c & IMAGE_SCN_MEM_EXECUTE ? PAGE_EXECUTE_READ
                   : c & IMAGE_SCN_MEM_WRITE   ? PAGE_READWRITE : PAGE_READONLY;
        VirtualProtect(base + sec[i].VirtualAddress,
                       std::max(sec[i].Misc.VirtualSize, sec[i].SizeOfRawData), prot, &old);
    }
    // Register the unwind data, so a fault in game code reaches your mod's __except.
    const auto& pd = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION];
    RtlAddFunctionTable(reinterpret_cast<PRUNTIME_FUNCTION>(base + pd.VirtualAddress),
                        pd.Size / sizeof(RUNTIME_FUNCTION), reinterpret_cast<DWORD64>(base));
    return base;
}
  • Link the harness somewhere else. llvm-mingw links an exe at 0x140000000 too, so the harness would sit where the game must go. Link it with -Wl,--image-base=0x10000000.
  • Copy the exe into the test folder; never point a test at the game's own folder.
  • Test a moved base too. Director Mode's harness can map the exe at another address and apply its relocations, as Azimuth does under Proton, to check that every pointer comparison allows for the delta.

What a harness can check

  • Every byte check against the real code, in a table the mod and the test share. A wrong RVA fails here.

  • Other mods' hooks. Write an E9 jump over a site, as MinHook would, and check that your mod accepts it after confirming the disk bytes (the rule in chapter 5). Do the same with no exe on disk, and with a wrong byte that matches neither, which must turn off only that feature.

  • Running your per-frame code with no game. Patch a ret (C3) into the hooked function just past the bytes the hook relocates, then call it in a loop: your detour runs and returns, nothing of the game does. For CControllerManager::Update (game+0x1075490, 0x141075490) the first instruction boundary past the five bytes is game+0x1075497:

    141075490: 48 8b c4                 mov  rax, rsp
    141075493: 48 89 48 08              mov  qword ptr [rax + 0x8], rcx
    141075497: 55                       push rbp            <- write C3 here in the harness's copy
    
  • Every key with no game state. With every global still zero, each test must say it can't run, not crash, and the put-back key must say there is nothing to put back.

  • Small self-contained game functions. A getter such as the ForzaCar kind (mov eax, [rcx+0x4D08]; ret at game+0xF62280) can be called on a fake object. Anything that touches the game's globals, its allocator or its imports can't: nothing has set them up.

  • Online and offline. Lay the folder out as FH2MP's launcher would and check an offline_only mod stays out.

  • Exit non-zero on any failure and print one line per check, so the harness can run in CI.

Checking SEH guards offline

With clang, __try only protects calls made inside it (chapter 5). A guard that looks right in source can be empty in the build. Two ways to check it:

  1. A no-access test. Commit a page with PAGE_NOACCESS and read it through each guarded helper, one per process, built at your real optimisation level. "Caught" or "died" tells you which shapes work. Run it at -O2 and -O3: at -O3, argument promotion moved loads out of noinline helpers and lambdas, and only a copy through a volatile function pointer (or ReadProcessMemory) survived both.
  2. Read the scope tables. Each function with a __try has __C_specific_handler in its unwind info, followed by a table of protected address ranges. Disassemble the function and check that the risky load lies inside a range. You can do it on the assembly (-S, ranges between the LabelStart/LabelEnd pairs after .seh_handlerdata) or on the built DLL's .pdata/.xdata. An audit of 55 guards across the platform and three mods this way found four that didn't protect the read they were written for, which the source gave no hint of.

15.6 Static reverse engineering in practice

Chapter 1 lists the tools, and chapter 11 the RTTI layout. This section is the working method, with scripts small enough to read in one go. They need only Python 3 and read the exe on disk.

Disassembling with llvm-objdump

llvm-objdump -d -M intel --start-address=0x140FE61C0 --stop-address=0x140FE6200 forza_durango_release_final.exe
  • Addresses are absolute at 0x140000000. Start at a function's first byte (from .pdata, below): starting mid-instruction gives nonsense until it falls back into step.
  • --no-show-raw-insn hides the bytes; leave them in when you're copying a byte check.
  • Ignore the labels. <SurroundGainGetDSPDescription+0xdd53b0> only means "the nearest export before this", and the exports are FMOD's. It says nothing about the function.
  • Disassembling the whole .text takes minutes and gigabytes of text. Work on ranges.

The scripts

One file, fh2re.py. Each part below was run on the exe; outputs are in 15.7.

Sections and RVA to file offset. The file isn't laid out like memory: each section has its own file offset.

import re, struct, sys

BASE = 0x140000000

class Exe:
    def __init__(self, path):
        self.d = d = open(path, 'rb').read()
        pe = struct.unpack_from('<I', d, 0x3C)[0]
        nsec, = struct.unpack_from('<H', d, pe + 6)
        optsz, = struct.unpack_from('<H', d, pe + 20)
        opt = pe + 24
        tds, = struct.unpack_from('<I', d, pe + 8)
        size, = struct.unpack_from('<I', d, opt + 56)
        assert (tds, size) == (0x565501ED, 0x3A18000), 'not the 24 Nov 2015 FH2 build'
        self.pdata, self.pdata_size = struct.unpack_from('<II', d, opt + 112 + 3 * 8)  # directory 3
        self.secs = {}
        for i in range(nsec):
            s = opt + optsz + i * 40
            name = d[s:s + 8].rstrip(b'\0').decode()
            vsize, va, rsize, roff = struct.unpack_from('<IIII', d, s + 8)
            self.secs[name] = (va, vsize, roff, rsize)

    def off(self, rva):                       # RVA -> file offset
        for va, vsize, roff, rsize in self.secs.values():
            if va <= rva < va + rsize:
                return roff + rva - va
        return None                           # not in the file (header, or zero-filled .data tail)

    def rva(self, off):                       # file offset -> RVA
        for va, vsize, roff, rsize in self.secs.values():
            if roff <= off < roff + rsize:
                return va + off - roff
        return None

    def u32(self, rva): return struct.unpack_from('<I', self.d, self.off(rva))[0]
    def u64(self, rva): return struct.unpack_from('<Q', self.d, self.off(rva))[0]
    def cstr(self, rva):
        o = self.off(rva)
        return self.d[o:self.d.index(b'\0', o)].decode('latin-1')

The sections worth knowing:

SectionRVAWhat is there
.text0x1000code
.rdata0x1DD0000imports, constants, strings, RTTI CompleteObjectLocators
.data0x2C47000globals, vtables and RTTI type descriptors (writable)
.pdata0x373A000function table (unwind entries)

Vtables sit in .data in this build, not .rdata, so a vtable slot is a plain writable pointer.

RTTI: the class name of a vtable. vtable[-1] holds a pointer to the CompleteObjectLocator (COL). Its fields are 32-bit RVAs: signature (1 on x64) at +0, offset of this vtable's sub-object at +4, the TypeDescriptor at +12, the class hierarchy at +16, and the COL's own RVA at +20. The name starts 16 bytes into the TypeDescriptor.

    def rtti_name(self, vtable):
        col = self.u64(vtable - 8) - BASE         # absolute pointer, as stored on disk
        if self.off(col) is None or self.u32(col) != 1:
            return None                           # x64 COLs have signature 1
        return self.cstr(self.u32(col + 12) + 16) # TypeDescriptor RVA at +12, name at +16

Reading a name: .?AV is a class, .?AU a struct, then the names innermost first, each ended by @, and a final @. .?AVCMultiCam@Camera@@ is class Camera::CMultiCam; .?AVForzaCar@@ is class ForzaCar.

Class name to vtable. The reverse: find the name, step back to its TypeDescriptor, find COLs that point at it, then find the pointers to those COLs, each followed by a vtable. A class with several bases has one vtable per sub-object; the COL's +4 says where that sub-object sits in the object.

    def vtables(self, cls):
        pat = rb'\.\?A[VU]' + re.escape(cls.encode()) + rb'@(?:\w+@)*@\0'   # any namespace
        out = []
        for m in re.finditer(pat, self.d):
            td = self.rva(m.start()) - 16
            for c in re.finditer(re.escape(struct.pack('<I', td)), self.d):
                col = self.rva(c.start()) - 12
                if col is None or self.off(col) is None: continue
                if self.u32(col) != 1 or self.u32(col + 20) != col: continue   # COL points at itself
                for v in re.finditer(re.escape(struct.pack('<Q', BASE + col)), self.d):
                    out.append((self.rva(v.start()) + 8, self.u32(col + 4)))   # (vtable, offset in object)
        return out

It searches the file for absolute pointers as they are on disk (at 0x140000000). In memory under Proton they are relocated; at run time, compare vtable[-1] with game + COL RVA instead.

Function bounds from .pdata. Each entry is three RVAs: begin, end, unwind info. MSVC splits a function into several entries: later parts carry UNW_FLAG_CHAININFO (flags are the unwind info's first byte shifted right by 3; chained is 4) and point back at the earlier part. CMultiCam::PostUpdate's first entry covers only its first 0x21 bytes; the whole function is five entries. Follow the chains, or you'll think functions are much shorter than they are.

    def entry(self, i):
        return struct.unpack_from('<III', self.d, self.off(self.pdata) + 12 * i)

    def find_entry(self, rva):                # binary search: entries are sorted by begin
        lo, hi = 0, self.pdata_size // 12 - 1
        while lo <= hi:
            mid = (lo + hi) // 2
            b, e, _ = self.entry(mid)
            if rva < b: hi = mid - 1
            elif rva >= e: lo = mid + 1
            else: return mid
        return None

    def root(self, ent):                      # follow UNW_FLAG_CHAININFO back to the start
        b, e, u = ent
        while self.d[self.off(u)] >> 3 & 4:
            n = self.d[self.off(u) + 2]       # count of unwind codes
            b, e, u = struct.unpack_from('<III', self.d, self.off(u) + 4 + 2 * ((n + 1) & ~1))
        return b

    def func(self, rva):
        i = self.find_entry(rva)
        if i is None: return None             # a leaf function (no stack frame), or not code
        start = self.root(self.entry(i))
        i = self.find_entry(start)
        while i + 1 < self.pdata_size // 12 and self.root(self.entry(i + 1)) == start:
            i += 1
        return start, self.entry(i)[1]

A function with no .pdata entry at all is a leaf: it calls nothing and touches no stack, like the near-clip forwarder at game+0xFE2F60 (mov rcx,[rcx+0x208]; mov rax,[rcx]; jmp [rax+0x140]). Its bounds come from the disassembly; it ends at its jmp or ret, and CC padding follows.

Who uses a string. Code loads a string's address with lea reg, [rip+disp32] (48/4C 8D plus a ModRM byte with mod 00 and r/m 101); the pattern also takes mov (8B) loads from the same place. Scan .text for that pattern and keep the hits whose target is the string. It may find a few false positives in data mixed into .text; check each in the disassembly.

    def strrefs(self, text):
        targets = {self.rva(m.start()) for m in re.finditer(re.escape(text.encode() + b'\0'), self.d)}
        va, _, roff, rsize = self.secs['.text']
        t = self.d[roff:roff + rsize]
        for m in re.finditer(rb'[\x48\x4C][\x8D\x8B][\x05\x0D\x15\x1D\x25\x2D\x35\x3D]', t):
            i = m.start()
            if va + i + 7 + struct.unpack_from('<i', t, i + 3)[0] in targets:
                yield va + i

Strings are UTF-8 or ASCII; a few are UTF-16 and need text.encode('utf-16-le'). Error and log formats are the best start: "string too long" leads to the STL's length checks, and a system's log text leads to that system.

Direct callers. E8 (call) and E9 (jmp) take a 32-bit offset from the next instruction. Scanning for every E8/E9 byte whose target is your function finds its direct callers and tail jumps. It does not find virtual calls (call [rax+0x20]); for those, find the vtables that hold the function and look for calls through that slot's offset.

    def callers(self, target):
        va, _, roff, rsize = self.secs['.text']
        t = self.d[roff:roff + rsize]
        for m in re.finditer(rb'[\xE8\xE9]', t):
            i = m.start()
            if i + 5 <= len(t) and va + i + 5 + struct.unpack_from('<i', t, i + 1)[0] == target:
                yield va + i, 'call' if t[i] == 0xE8 else 'jmp'

A small command-line wrapper finishes the file:

def main():
    x, cmd, a = Exe(sys.argv[1]), sys.argv[2], sys.argv[3:]
    h = lambda s: int(s, 16)
    where = lambda r: 'game+0x%X' % x.func(r)[0] if x.func(r) else 'no .pdata entry'
    if cmd == 'rtti':
        print(x.rtti_name(h(a[0])))
    elif cmd == 'vtables':
        for vt, at in x.vtables(a[0]):
            print('vtable game+0x%X (0x%X), sub-object at +0x%X: %s' % (vt, BASE + vt, at, x.rtti_name(vt)))
    elif cmd == 'slot':
        f = x.u64(h(a[0]) + 8 * int(a[1])) - BASE
        print('slot %s -> game+0x%X (0x%X)' % (a[1], f, BASE + f))
    elif cmd == 'func':
        r = x.func(h(a[0]))
        print('game+0x%X .. game+0x%X' % r if r else 'no .pdata entry: a leaf function, or not code')
    elif cmd == 'strrefs':
        for r in x.strrefs(a[0]):
            print('game+0x%X, in function %s' % (r, where(r)))
    elif cmd == 'callers':
        for r, kind in x.callers(h(a[0])):
            print('%s at game+0x%X, in function %s' % (kind, r, where(r)))
    elif cmd == 'bytes':
        o = x.off(h(a[0]))
        print(' '.join('%02X' % b for b in x.d[o:o + int(a[1])]))

if __name__ == '__main__':
    main()

Each command takes under a second or two on the 58 MB exe.

Following a vtable slot

A virtual call is mov rax, [rcx] (the vtable) then call [rax+N]: the slot is N / 8. So call [rax+0x20] is slot 4, and jmp [rax+0x140] is slot 40. Read the slot from the vtable (python fh2re.py <exe> slot <vtable> 4) and you have the function. A vtable ends where the next one's COL pointer begins: the first entry that points into .rdata rather than .text.

At run time, inside a mod, the same RTTI walk names any object you are handed. Read through a guarded copy (chapter 5):

// The RTTI name of a game object (".?AVForzaCar@@"), or nullptr. `game` is the game's base.
static const char* game_class(const char* game, const void* obj) {
    const char* vt = nullptr;
    const char* col = nullptr;
    uint32_t sig = 0, td = 0;
    const char* end = game + 0x3A18000;
    if (!read_ok(&vt, obj, 8) || vt < game || vt >= end) return nullptr;
    if (!read_ok(&col, vt - 8, 8) || col < game || col >= end) return nullptr;
    if (!read_ok(&sig, col, 4) || sig != 1 || !read_ok(&td, col + 12, 4) || td >= 0x3A18000) return nullptr;
    return game + td + 16;      // inside the image: stays valid for the session
}

How the exe was built

All of this is read from the exe: its Rich header (the linker's record of the tools that made each object in it), its imports and its code. The Rich header's product numbers were checked by building a small test exe with a compiler and linker of the same build and reading its header back.

CompilerVisual C++ 2012 family (cl 17.00), build 65501. No public Visual Studio 2012 update has that build (they run from 50727 to 61030): it is the Xbox One toolchain's
Linker11.00, build 65501
C++ objects717 compiled one file at a time (702 by build 65501), and 136 with whole-program optimisation (/GL, linked with /LTCG)
C objects101 (70 by build 65501)
Other objectsa few from the assembler, import libraries and older tools (builds 65500, 50522, 41118, and 30729, which is Visual C++ 2008 SP1): libraries the game links in
C runtimethe DLL runtime (/MD): MSVCR110.dll, MSVCP110.dll for the STL, and vccorlib110.dll, the C++/CX runtime, for the parts written against WinRT
Image/DYNAMICBASE, /HIGHENTROPYVA and /NXCOMPAT set; OS and subsystem version 6.0

What the code shows about the flags:

FlagEvidence
/arch:AVXVEX encodings everywhere, even for plain scalar float work
/GRRTTI is intact for every polymorphic class
C++ exceptions (/EH)functions with destructors to run have __CxxFrameHandler3 unwind data
/GSabout 1,800 functions (those with local arrays) load __security_cookie in the prologue and call __security_check_cookie (game+0xF182E0) before returning
/O2standard library code compiled with /O2 /arch:AVX matches the game byte for byte (below)
Per-library flagsthe C libraries linked in kept their own: zlib 1.2.7 matches built with /O1, and SQLite 3.6.19 built with /Od (no optimisation) and SQLITE_THREADSAFE=0
/OPT:ICFidentical functions were folded into one, so one body often answers to many names: the stub_..., vfshared_... and "or N other" names in the game symbols

What follows from it:

  • Library code can be named by matching bytes. Code compiled with the same compiler build and flags comes out the same as in the game, apart from the addresses the linker fills in. The symbols' libmatch.py compiles nothing itself: give it objects or libraries built with a compiler of build 65501 and it names every game function whose bytes match in no more than three places (names-lib.txt). Most hits are STL members and C runtime functions, which you can then skip while reading game code.
  • You can test a guess at the source. Write the C++ you think a function was, compile it with the same build and flags, and compare. The STL layouts in 11.10 were measured this way.
  • Expect inlining across files. With whole-program optimisation, a small helper from another file may exist only inlined into its callers. If you can't find a function to hook, hook its caller or the call site.
  • One body, many names. Because of /OPT:ICF, a tiny function (return 0;, an empty destructor) is shared by unrelated classes. Hooking it hooks all of them: check the caller in your detour, or hook the call site instead.

Recognising MSVC 2012 code

The game was built with Visual C++ 2012 (it imports MSVCR110.dll and MSVCP110.dll) for the Xbox One's AVX CPU. Patterns you'll meet:

You seeIt is
this in rcx; integer arguments in rcx, rdx, r8, r9; a float as argument n in xmmn (dt in xmm1 for a method)the Microsoft x64 calling convention, by position
mov [rsp+0x18], rbp / push rsi ... sub rsp, 0x90 / vmovaps [rsp+0x80], xmm6a prologue: home-space save, pushes, frame, then the non-volatile xmm6-xmm15 saved
vmovaps, vandps, vcvttss2si everywhereAVX (VEX) encodings even for plain SSE work; normal for this build
mov rax, [rcx] then call [rax+N]a virtual call, slot N/8
in vtable slot 0: call / test bl, 1 / je / call (the free) / mov rax, rdi / reta scalar deleting destructor: it runs the destructor it calls first, then frees the object when bit 0 of edx is set
lea rax, [vtable] / mov [rcx], rax at the very startusually a destructor, resetting the object's vtable to its own class's before it tears down (a constructor does the same, but after calling its base class's constructor)
an epilogue (add rsp, pop) followed by jmp to another functiona tail call: the function hands over to another one
call [rip+disp]a call through an import slot in .rdata (msvcp110, kernelx, EtwPlus and others)
cmp rdx, -2 ... lea rcx, "string too long" ... call [__imp_?_Xlength_error] ... int3an inlined std::string length check
runs of CC between functionspadding; the next function starts after them
a tiny function that passes a name string to one call and stores the result in a global, with no direct callersa static initialiser, run from a table at start-up
mov [rip+disp], rcxthis (or another value) stored in a global; a good place to find a singleton

STL layouts (std::string, vector, list, deque, shared_ptr) are in chapter 11.

15.7 Worked example: from a class name to a byte-checked hook

The goal: a hook that runs once per frame after the game has filled the camera cache, starting from nothing but the name CMultiCam. Chapter 8 documents the answer (CMultiCam::PostUpdate, game+0xFE61C0); here is how to find and check it yourself. Every output below is from the 24 Nov 2015 exe.

StepAddress
CMultiCam vtablegame+0x2E70080 (0x142E70080)
slot 4, CMultiCam::Updategame+0xFE6020 (0x140FE6020)tail-jumps to PostUpdate
CMultiCam::PostUpdategame+0xFE61C0 (0x140FE61C0)the hook
the last CMultiCam updatedgame+0x365AE10 (0x14365AE10)global written by Update

Step 1: find the vtables from the name

$ python fh2re.py forza_durango_release_final.exe vtables CMultiCam
vtable game+0x2E70080 (0x142E70080), sub-object at +0x0: .?AVCMultiCam@Camera@@
vtable game+0x2E70348 (0x142E70348), sub-object at +0x180: .?AVCMultiCam@Camera@@

The class is Camera::CMultiCam. The second vtable belongs to a sub-object at +0x180 (the IMultiCam interface, as the class hierarchy says). The main one, at +0x0, is the one an object's first eight bytes point at. Its RTTI, followed by hand:

vtable[-1] at game+0x2E70078 = 0x1426203B0 -> COL game+0x26203B0
COL: signature 1, offset 0x0, TypeDescriptor rva 0x2F99B30, ClassHierarchy rva 0x23A0DD8, self rva 0x26203B0
hierarchy: 4 base classes: CMultiCam@Camera +0x0, ICamera@Camera +0x0, ISystemEventSubscriber@Core +0x0,
           IMultiCam@Camera +0x180

Step 2: read the update slot

Chapter 8 says the running path calls the director from SimulationView slot 2 at game+0xFDC2C8. Disassembling there shows a virtual call:

140fdc2b3:  mov    rax, qword ptr [rcx]
...
140fdc2c4:  vmovaps xmm1, xmm6
140fdc2c8:  call   qword ptr [rax + 0x20]

0x20 / 8 is slot 4. Read it from CMultiCam's vtable:

$ python fh2re.py forza_durango_release_final.exe slot 0x2E70080 4
slot 4 -> game+0xFE6020 (0x140FE6020)
$ python fh2re.py forza_durango_release_final.exe func 0xFE6020
game+0xFE6020 .. game+0xFE6158

Step 3: follow it to the real work

$ llvm-objdump -d -M intel --no-show-raw-insn --start-address=0x140FE6020 --stop-address=0x140FE6158 ...
140fe6020:  push   rbx
140fe6022:  push   rsi
140fe6023:  sub    rsp, 0x58
140fe6027:  vmovaps xmmword ptr [rsp + 0x30], xmm7
140fe602d:  mov    qword ptr [rsp + 0x80], rbp
140fe6035:  mov    qword ptr [rip + 0x2674dd4], rcx      # 0x14365ae10
...
140fe60f6:  call   qword ptr [rax + 0x20]                # each active camera's own update
...
140fe614d:  add    rsp, 0x58
140fe6151:  pop    rsi
140fe6152:  pop    rbx
140fe6153:  jmp    0x140fe61c0

Update stores this in the global game+0x365AE10, updates the cameras, then tears down its frame and jumps to game+0xFE61C0: a tail call. That is where the cache gets filled. Check who else reaches it directly:

$ python fh2re.py forza_durango_release_final.exe callers 0xFE61C0
call at game+0xFE27F8, in function game+0xFE26F0
jmp at game+0xFE6153, in function game+0xFE6020

Two paths: the tail jump from Update (running) and a call from game+0xFE26F0, which is CMultiCam slot 5, the paused path. Hooking game+0xFE61C0 itself catches both; hooking slot 4 would miss the paused one.

Step 4: confirm the function and take the byte check

$ python fh2re.py forza_durango_release_final.exe func 0xFE61C0
game+0xFE61C0 .. game+0xFE6435
$ python fh2re.py forza_durango_release_final.exe bytes 0xFE61BA 6
CC CC CC CC CC CC

.pdata says a function starts exactly at game+0xFE61C0 (five chained entries up to game+0xFE6435), and CC padding sits before it. The prologue:

140fe61c0: 48 89 6c 24 18              mov     qword ptr [rsp + 0x18], rbp
140fe61c5: 56                          push    rsi
140fe61c6: 41 54                       push    r12
140fe61c8: 41 55                       push    r13
140fe61ca: 41 56                       push    r14
140fe61cc: 41 57                       push    r15
140fe61ce: 48 81 ec 90 00 00 00        sub     rsp, 0x90
140fe61d5: c5 f8 29 b4 24 80 00 00 00  vmovaps xmmword ptr [rsp + 0x80], xmm6
140fe61de: 48 8b f1                    mov     rsi, rcx
140fe61e1: c5 f8 29 7c 24 70           vmovaps xmmword ptr [rsp + 0x70], xmm7
140fe61e7: 48 8d 54 24 30              lea     rdx, [rsp + 0x30]
140fe61ec: 45 0f b6 e0                 movzx   r12d, r8b
140fe61f0: c5 f8 28 f1                 vmovaps xmm6, xmm1
140fe61f4: c5 f8 28 b9 20 02 00 00     vmovaps xmm7, xmmword ptr [rcx + 0x220]

What it tells you:

  • rcx is this (kept in rsi), xmm1 a float (dt, kept in xmm6), r8b a byte flag (kept in r12d): the signature void PostUpdate(CMultiCam*, float dt, uint8_t flag).
  • [rcx + 0x220] is read at once: the camera cache at +0x220.
  • The first 5 bytes, the part a hook replaces, are one whole instruction. The check below takes the first 24 bytes (through the start of the vmovaps at +0x15) and the 8 bytes at +0x34 that read +0x220, so it fails if the function or its use of the cache differs.
$ python fh2re.py forza_durango_release_final.exe bytes 0xFE61C0 24
48 89 6C 24 18 56 41 54 41 55 41 56 41 57 48 81 EC 90 00 00 00 C5 F8 29
$ python fh2re.py forza_durango_release_final.exe bytes 0xFE61F4 8
C5 F8 28 B9 20 02 00 00

These are the same bytes chapter 8 gives, found from the name alone.

Step 5: the hook

// CMultiCam::PostUpdate, game+0xFE61C0 (0x140FE61C0): fills the camera cache at +0x220 each frame.
constexpr uintptr_t RVA_POSTUPDATE = 0xFE61C0;
static const uint8_t kPostUpdatePrologue[] = {          // game+0xFE61C0, 24 bytes
    0x48, 0x89, 0x6C, 0x24, 0x18, 0x56, 0x41, 0x54, 0x41, 0x55, 0x41, 0x56,
    0x41, 0x57, 0x48, 0x81, 0xEC, 0x90, 0x00, 0x00, 0x00, 0xC5, 0xF8, 0x29};
static const uint8_t kPostUpdateCacheRead[] = {         // game+0xFE61F4: vmovaps xmm7, [rcx+0x220]
    0xC5, 0xF8, 0x28, 0xB9, 0x20, 0x02, 0x00, 0x00};

using PostUpdateFn = void (*)(void* mc, float dt, uint8_t flag);
static PostUpdateFn o_post_update;

static void d_post_update(void* mc, float dt, uint8_t flag) {
    o_post_update(mc, dt, flag);                        // the game fills the cache first
    // ... read or write the cache here; chapter 8 says which director is view 0's ...
}

// On your own thread, after wait_for_code:
static bool hook_post_update(char* game) {
    if (!site_matches(game, RVA_POSTUPDATE, kPostUpdatePrologue, sizeof kPostUpdatePrologue) ||
        !site_matches(game, RVA_POSTUPDATE + 0x34, kPostUpdateCacheRead, sizeof kPostUpdateCacheRead)) {
        g_api->log(g_mod, "camera: game code doesn't match at game+0xFE61C0, camera feature off");
        return false;
    }
    return g_api->hook_function(g_mod, "CMultiCam::PostUpdate", game + RVA_POSTUPDATE,
                                reinterpret_cast<void*>(&d_post_update),
                                reinterpret_cast<void**>(&o_post_update)) != nullptr;
}

site_matches is the check from chapter 5: memory first, then the exe on disk (api->game_dir), accepting another mod's E9 jump over the prologue. That matters here, because Director Mode and an on-foot mod already hook this function. Call enable_hooks once every hook and all your state is ready. In an Extra Options plugin the same check and MinHook's MH_CreateHook do the job, without chaining (chapter 3).

Then prove it in game with a probe: log the frame count, how often the hook runs per frame, which mc it sees (compare with view 0's director) and dt, running and paused. Earlier probes measured exactly one override per frame for view 0, running and paused, on the same thread as CControllerManager::Update, and a second call with dt 0 when the car is placed at a route locator.

If the site is useful to others, propose it for the platform's include/fh2game.h with its bytes and the mod that uses it, so every mod checks it the same way.

15.8 Checklist: when a hook misbehaves

It never runs

  • platform.log has your "hooked function game+0x..." line, and nothing saying "game code doesn't match" or "refused" for it. Extra Options' line 2 isn't REFUSED: because you hooked too early.
  • You called enable_hooks after making the hook, and it returned non-zero.
  • The function is really called: check with callers (direct) and the vtables that hold it (virtual). A slot hook only catches calls through that vtable; a tail jump into the function bypasses a hook on the caller.
  • The path you are testing actually runs: paused and running often take different paths (15.7).
  • You aren't on another game: wait_for_code returned NULL, or game_base() is NULL.

It runs, but at the wrong time or too often

  • Count calls per frame and log the thread id once. Many functions run for every view, car or camera, not just the player's; filter on the object you want (RTTI name, a known root such as view 0).
  • Your flags were set before enable_hooks: the hook can run before the call returns.

The values are wrong

  • Re-read the prologue: which register holds which argument, and is a float in xmm1 because it's the second argument?
  • The object's RTTI name is the class you expect, and the field's offset comes from the code that writes it, not a guess.
  • The pointer is re-read from a stable root each time; streamed objects are freed and reused.
  • Under Proton, absolute pointers you compare with the disk have the load delta taken off.

It crashes

  • Read the report: is the frame in your DLL, in the game below your detour ("referenced on the stack"), or in a trampoline ("the crash was in ...")?
  • You call the original with exactly the arguments you received, and preserve return values.
  • Every read of game memory goes through a guarded copy that the build really protects (15.5).
  • No game allocation off a game thread, and no game calls from UI or hotkey callbacks.
  • Build with -gcodeview -Wl,--pdb=, keep the PDB, add add_dump_memory for your tables, and reproduce with full in platform-dump.txt.

It works alone but not with other mods

  • Your byte check accepts another mod's jump after checking the disk.
  • The crash report's hook list shows who else is on the same site; chapter 5's shared sites lists the known meeting points.
  • Test with Extra Options, Achievements, WreckingBall and FH2MP's client installed, then reorder by renaming DLLs (mods load alphabetically) to shake out start-up races.

Before you call it fixed

  • The offline harness passes, including the "another mod hooked it" and "wrong bytes" cases.
  • A probe or test run's log shows the behaviour, with the frame numbers to prove it, and you have the hash of the build that ran.

“The FH2 Modding Guide” by Trinculo54 is licensed under CC BY 4.0; its code samples are under the MIT licence. This page is an unchanged copy (links point to this site) of 15-debugging.md at commit bb10508; corrections belong in the original repository.