Navigation
Browse the developer docs

FH2 Modding Guide · Chapter 5

Hooking the game safely

Before your first hook: byte checks, chaining and turning a feature off instead of crashing.

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 about changing game code without breaking the game, Extra Options or other mods. It applies to platform mods and Extra Options plugins alike; where the two differ, both are shown. The hook reference chapters (6 and 7) tell you where to hook; this one tells you how.

All addresses are for forza_durango_release_final.exe of 24 Nov 2015 (TimeDateStamp 0x565501ED), image base 0x140000000; see chapter 1.

5.1 The short version

  1. Prefer data to code. A database row, a string or a replaced page beats a hook (chapter 4).
  2. Hook only after Extra Options has finished patching (wait_for_code on the platform).
  3. Byte-check every site before you hook it, patch it or call it. On a mismatch, log a plain sentence and turn that one feature off. Never crash, never force it.
  4. Allow for other mods' hooks: check against the exe on disk, and accept another mod's jump where it is safe.
  5. Always call the original you were given, so other mods' hooks on the same site still run.
  6. Set up all state before enabling hooks. Detours run on many game threads at once.
  7. Read game memory through SEH-guarded copies, and forget per-object notes when the game frees the object.
  8. Don't hook the platform's sites (5.9), and call shared game functions rather than hooking them.

5.2 Choose the gentlest kind of hook

From least to most invasive:

KindWhat changesPlatform APIWithout the platformUse when
Dataa database row, a file, a stringadd_sql, set_file, set_stringEO package (database.json, media, strings.json)the behaviour is data-driven
Pointerone 8-byte slot: a vtable entry, function table or importhook_pointeran atomic 8-byte write (InterlockedExchangePointer)you want one class's virtual, or one import (e.g. EtxEventWrite)
Call siteone E8 CALL rel32 or E9 JMP rel32hook_callrewrite the rel32 to a stub within 2 GByou want one caller of a shared function, not all of them
Functionthe start of a function (a 5-byte jump)hook_functionMinHook MH_CreateHookevery caller should be affected
Instructiona jump in the middle of a function; your callback sees and can change registershook_instruction (API 7)not offered; write a stub by handthe value you need lives in a register mid-function
Byte patchup to 32 bytes rewrittenpatch_bytes (API 7)WriteProcessMemory/VirtualProtect with threads pausedflipping a branch or a constant

A vtable slot hook is the cleanest when the game calls the method virtually: one atomic write, no code bytes touched, and it only affects that class. A call-site hook is next best: a shared function like the HUD notification gate is called from many places, and hooking one call leaves the others alone.

5.3 When to hook

Extra Options patches everything or nothing

Extra Options checks every one of its patch sites (352 in 0.6.0) against the bytes it expects, and applies none of them if any one differs. It does this once, just after Azimuth maps the exe. If your mod writes to any of those bytes before EO looks, EO silently turns itself off for that player, with "REFUSED: unexpected loaded bytes" in FH2_ExtraOptions.log.

So:

  • Platform mods start a thread in fh2mod_init and call wait_for_code there. It returns the game's base once EO has logged OK:, REFUSED: or DISABLED: (or 20 s after the game was mapped if EO never answers). The platform won't even create a game-code hook before that.
  • EO plugins start after EO has applied its patches (on the game's first file lookup), so they're safe on that count.
  • Anything else (your own proxy, an injector) must wait for EO's status line in FH2_ExtraOptions.log too.

Hooks into Azimuth or Windows DLLs don't need to wait.

What changes after start-up

Most data (database, string tables, most UI pages) is read once at start. A hook that changes how a file is read must be in place before the game reads it, and that's usually before wait_for_code returns. Change the data instead (the platform writes it before the game starts reading), or accept that the hook only affects files read later.

5.4 Byte checks

Every address in this guide is for one build. A byte check makes a wrong guess a missing feature instead of a crash.

What to check

You're about toCheck
hook a functionits first 10-16 bytes (the prologue)
hook a call sitethe E8 opcode, and that the rel32 reaches the function you expect
swap a vtable slotthat vtable[-1] names the class you expect (RTTI), and the slot holds the expected function
hook an instructionthe instruction bytes and the ones the 5-byte jump will cover
read a fieldthe code that writes it, or the vtable of the object holding it
call a functionits prologue, every time you resolve it

The platform names about 70 common sites with their bytes in include/fh2game.h (FH2_GAME_..._BYTES), so mods agree on them. See chapter 2.

Check the disk, then allow for other mods

A memory check fails as soon as another mod has hooked the same function first, and the player loses your feature for nothing. Two released mods hit exactly this (WreckingBall 1.3.0 against NitroSystem on game+0x384C00; Director Mode before 0.1.5 against CCBR on game+0xF62280). The rule they settled on:

  1. Compare the bytes in memory with what you expect. Match: go ahead.
  2. Otherwise read the same RVA from forza_durango_release_final.exe on disk (platform: api->game_dir). If the disk bytes don't match either, this isn't the build you know: turn the feature off.
  3. If the disk matches and memory starts with E9 jumping outside the image, followed by the rest of the expected bytes or CC padding, another mod hooked it. Accept it and chain (the platform does the chaining for you).

For a call site that another mod may have retargeted, skip the 4-byte rel32 in your check, and check the opcode and the surrounding bytes instead.

The platform's own hooks already compare game bytes with the exe on disk and refuse a site Extra Options or a self-patching mod has changed ("game code doesn't match"). If you need a site EO patches, talk to EO's author rather than fighting over the bytes.

Pointers under Wine and Proton

Code bytes don't move, but absolute pointers in the image are relocated when the exe is mapped away from 0x140000000. When you compare a pointer (a vtable slot, a global holding an address) with the disk, subtract the load delta first.

5.5 Writing a hook on the platform

#include "fh2mod.h"
#include "fh2game.h"
#include <windows.h>
#include <cstring>

static const FH2ModApi* g_api;
static FH2Mod* g_mod;

using CarKindFn = int (*)(void* car);
static CarKindFn o_car_kind;                       // the platform fills this in

static int d_car_kind(void* car) {
    int kind = o_car_kind(car);                    // always call the original
    // ... look at, or change, the result ...
    return kind;
}

static DWORD WINAPI worker(LPVOID) {
    char* game = static_cast<char*>(g_api->wait_for_code(0xFFFFFFFFu));
    if (!game) return 0;                           // another game, or no game this session
    if (std::memcmp(game + FH2_GAME_FORZACAR_KIND, FH2_GAME_FORZACAR_KIND_BYTES,
                    sizeof FH2_GAME_FORZACAR_KIND_BYTES - 1) != 0) {
        g_api->log(g_mod, "car kind: game code doesn't match, feature off");
        return 0;
    }
    if (g_api->hook_function(g_mod, "ForzaCar kind", game + FH2_GAME_FORZACAR_KIND,
                             reinterpret_cast<void*>(&d_car_kind),
                             reinterpret_cast<void**>(&o_car_kind)))
        g_api->enable_hooks(g_mod, nullptr);       // all state is ready by now
    return 0;
}

FH2MOD_EXPORT int fh2mod_init(const FH2ModApi* api) {
    g_api = api;
    FH2ModInfo info{sizeof info, "MyMod", "1.0.0", nullptr, FH2MOD_PLATFORM_VERSION, 1};
    g_mod = api->register_mod(&info);
    if (!g_mod) return 0;                          // always 0, even when the mod stands down
    if (api->api_version < 3) { api->log(g_mod, "needs a newer platform for hooks"); return 0; }
    CloseHandle(CreateThread(nullptr, 0, worker, nullptr, 0, nullptr));
    return 0;
}

What the platform does for you:

  • Hooks are created off; enable_hooks(mod, nullptr) turns all yours on with one thread pause.
  • *original is valid as soon as the call returns, and always safe to call: while your hook is off it goes straight on to the next mod or the game.
  • Several mods on one function, call or pointer chain: the most recently enabled runs first, and its original leads to the next. Partial overlaps are refused with the other mod's name in the log.
  • name appears in platform.log and in crash reports, which also say if a crash happened inside your detour.
  • disable_hooks restores the bytes when the last hook on a site goes.

Instruction hooks (hook_instruction, API 7) call fn(FH2Context*, user) before the instruction runs. You can read and change any general register and xmm0-xmm15, but not rsp. The site must be the start of an instruction, past the prologue, and nothing may jump into the bytes the 5-byte jump covers except to the site itself. Several mods can hook one instruction; a crash in your callback is caught, logged, and that hook skipped from then on.

5.6 Writing a hook without the platform (Extra Options plugin)

EO's plugin API gives you the game's base (context->game_image) and a log, but no hooking service, no chaining and no byte checks. Bring MinHook and do the checks yourself:

#include <windows.h>
#include <string.h>
#include "fh2_plugin.h"   /* from Extra Options' source */
#include "MinHook.h"

static int (*o_car_kind)(void*);
static int d_car_kind(void* car) { return o_car_kind(car); }

static const unsigned char kExpect[] = { /* the prologue bytes you read from the exe on disk */ 0 };

BOOL WINAPI FH2PluginInitialize(const FH2PluginContext* ctx) {
    if (ctx->size < sizeof *ctx || ctx->game_image_size != 0x3A18000) return FALSE;  /* not FH2 */
    unsigned char* site = (unsigned char*)ctx->game_image + 0xF62280;
    if (memcmp(site, kExpect, sizeof kExpect) != 0) {
        ctx->log_utf8("MyPlugin: car kind code doesn't match, feature off\r\n");
        return TRUE;      /* stay loaded, just without the feature */
    }
    if (MH_Initialize() != MH_OK && MH_Initialize() != MH_ERROR_ALREADY_INITIALIZED) return FALSE;
    if (MH_CreateHook(site, (void*)d_car_kind, (void**)&o_car_kind) == MH_OK) MH_EnableHook(site);
    return TRUE;
}

Things to know:

  • Under Azimuth, GetModuleHandleW(NULL) is azimuth.exe, not the game. Use ctx->game_image.
  • log_utf8 adds no newline; end lines with \r\n.
  • A platform mod that later hooks the same function is refused (the bytes no longer match the disk), and your plugin can't see a platform mod's hook except as a jump. Check before you hook and back off politely. Say in your README which sites you hook.
  • If you only need a per-frame callback for the player's car, use EO's FH2PluginVehicleUpdate rather than hooking the car update yourself.

5.7 Threads, timing and game calls

The rules below are the short form; chapter 16 explains the threads and frame order behind them.

  • Detours run on game threads, often several at once, often every frame. Keep them short and lock-free where you can; never block on your own thread from a detour.
  • Platform UI callbacks (on_change, on_slide, page and title-entry callbacks) run on the game's UI thread. Keep them short and don't call into the game from them. Hotkey on_press runs on the platform's hotkey thread.
  • Allocate game memory only on a game thread, inside a detour the game called. The game's operator new is game+0x3229C0. Your own threads may only write in place, after checking the object still exists.
  • Some game functions free their arguments. Functions that take an MSVC std::string by value (for example HUD notification Show, game+0x755330) free it themselves; build the string with the game's allocator.
  • Calling game code from your own thread is risky unless the function is known to be thread-safe. Queue the work and do it from a detour on the right thread instead (Achievements shows its pop-ups from the AchievementsModule tick, never from its worker).
  • Nothing runs at exit. Azimuth ends the game with TerminateProcess.

5.8 Reading game memory without crashing

Game objects are freed and their memory reused as the world streams. A pointer you saved a second ago may now be a different object, or unmapped.

  • Forget notes when the object goes. Hook the destructor or the load (Serialize) of the objects you track and drop what you know about that address there. WreckingBall's crash at game+0x369029 was exactly this: notes about a procedural data object outlived it, and the game put a new object at the same address.

  • Check the type before you trust a pointer. Compare its vtable, or read RTTI through vtable[-1].

  • Guard reads with SEH, the right way. With clang (llvm-mingw), __try only covers faults inside calls made in the block. Plain loads may be moved out of it, a __try with no call loses its handler, and at -O3 even a noinline helper's load can be hoisted. Copy through a pointer the compiler can't see through:

    static void* (*volatile g_copy)(void*, const void*, size_t) = std::memcpy;
    
    static bool read_ok(void* dst, const void* src, size_t n) {
        __try { g_copy(dst, src, n); return true; }
        __except (EXCEPTION_EXECUTE_HANDLER) { return false; }
    }
    

    Keep std::lock_guard and other objects with destructors out of functions that use __try; clang refuses to build them. Put the lock in a helper.

  • Don't VirtualQuery before every read. Its cost grows with the size of the memory block, and the game's blocks are huge: a per-car, per-frame check froze free roam in FH2MP. A guarded copy (or ReadProcessMemory on the own process, which fails cleanly) is cheaper and race-free; a VirtualQuery check followed by a copy can still race a free.

5.9 Sites you must not hook

The platform's own sites

The platform hooks these to run the MODS tab, pages, title entries, pop-ups and media overrides. Hooking or patching them breaks every mod's settings for the player. Since many players run the platform, EO plugins should keep clear of them too.

SiteWhat
game+0x157FF60AVUI Type::FindProperty
game+0xDC8A60 (calls 0xD9FC10, HUD tile 0xDC6C40)Settings page wiring its tiles
game+0xB3A3E0 (factory 0xB0B990)HUD options page's scene record
game+0x2DF06C0, 0x2DF07B0HUD options page vtable slots (loaded, buttons)
game+0xDC6E30 (calls 0xD9F9F0)pause menu wiring its tiles
game+0xDBD720, 0xDBDD00, 0xDBDD60, 0xDBFE40Marketplace tab tile handlers
game+0xDDACAD, 0xDDAE1F, 0xDDB2F5, 0xDDB910, 0xDDBB3Ebyte patches hiding the Marketplace tab
game+0xDBD635, 0xDBF185the Achievements tiles' calls
game+0x2E53940title screen buttons (Splash vtable slot)
game+0x2DEFE50, 0x2DEFEC0, 0x2DEF9C8free-roam HUD shown, hidden, destructor (Hud vtable)
game+0x2E6EF28the file system's resolver slot (written when EO isn't loaded)
game+0x75542C, 0x7555A5, 0x750FB1three calls of the minor-notification gate 0x754920
game+0x10768D0controller manager "release taken controls" (pad layer)
game+0xB99CA0, 0xB99D74DriveTrainConverter type checks (database guard)
game+0xDC6F29, game+0x1400030pause menu nav grid call and nav-grid cell constructor (Exit Game tile)

Shared instruction sites (several mods may hook them, through hook_instruction only): the AchievementsModule tick game+0x3FCD84, and the HUD notification constructor and destructor game+0x73E0B1 and game+0x73F046.

Functions to call, never hook

HUD notification Show (game+0x755330) and MakeDisplayString (game+0x323310) are checked byte for byte in memory by Achievements and FH2MP, with no disk fallback. Hooking them turns those mods' pop-ups off. Call them instead.

Sites other released mods check in memory

Keep new hooks clear of these, or older versions of these mods switch features off:

ModSites it checks
WreckingBall 1.0.0-1.3.0its own hooked code (0x12CC730, 0x1377B50, 0x384C00 and others) and six vtable slots; 1.3.3+ falls back to disk
CCBR 1.0.00x289320, 0x28C590, 0x28D930, 0xF5B420-0xF73080, 0x190BF90, 0x190BFD0, six lea rdx sites 0x6A2AF7-0x6B992A
FH2 Universal Radio up to 1.7.1operator new 0x3229C0, PE headers, FMOD exports; its call sites 0x1018A13/0x10221F2 only without the platform
FH2MPMakeDisplayString 0x323310 and many other places

5.10 Sites more than one mod hooks

These are known meeting points. Chain properly and they work together:

SiteWho hooks itNote
game+0x10221F2, radio getSubSound callFH2 Universal Radio, Radio Managerboth through hook_call; byte checks skip the rel32
game+0x2A9400, car per-frame updateDo A Barrel Roll, NitroSystem, FH2MP's clientuse the platform's chain; EO plugins should use FH2PluginVehicleUpdate
game+0xF62280, ForzaCar kind getterCCBR, Director Mode reads itaccept another mod's jump (5.4)
game+0x384C00, CWorldCollObjMan::UpdateWreckingBall, NitroSystemWreckingBall 1.3.3+ checks the disk
game+0x12CC730, CollisionWorld::GetPolysWreckingBall, a track modas above
game+0x1377B50, TrackPresentation11 destructorWreckingBall, a track modas above
AchievementsModule tick, notification ctor/dtorAchievements, the platform's pop-upsinstruction hooks, chained

5.11 Checklist before you ship a hook

  • The hook is made after wait_for_code (or, in an EO plugin, from FH2PluginInitialize onwards).
  • Every site, slot and called function is byte-checked, with the disk fallback and the other-mod jump allowed.
  • A failed check turns off one feature, logs a plain sentence, and the mod keeps running.
  • fh2mod_init returns 0 in every path.
  • All state is ready before enable_hooks.
  • Detours always call the original.
  • Every pointer read is guarded with a copy through a volatile function pointer; per-object notes are dropped when the object goes.
  • No game allocation off a game thread; no game calls from UI callbacks.
  • Not on a platform site; not hooking Show or MakeDisplayString.
  • The feature has a switch, and turning it off disables the hooks (disable_hooks) or undoes the data.
  • Tested alone, then with Extra Options, Achievements, WreckingBall and FH2MP's client installed.

“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 05-hooking.md at commit bb10508; corrections belong in the original repository.