Table of Contents

Hooking Game Functions

IFunctionHooks redirects a whole game function to a plugin's method, at a virtual method table entry, a call instruction, or the function's entry. ICodePatcher changes code inside a function, and through an InstructionHook runs a handler at one instruction.

Install hooks and patches in a plugin's Start, where most functions are not running. A patch writes over code that no thread may execute meanwhile, and the game can call a replaced table entry before the replacement has the original's address. A hook or patch remains until the process exits.

A hook on a table entry, call, or function entry that an earlier hook replaced is chained to that hook: calling the address it displaces runs the earlier hook, so the hook installed last runs first. The earlier hook can be another plugin's, or another SKSE plugin's. Instruction hooks at one address share one jump and run newest first. Any other overlap throws, naming the plugin that owns the other hook or patch. SkyrimForge.Runtime.log lists each one's owner and address.

Replacing a Virtual Method Table Entry

This plugin replaces two entries, reports each call, and calls the original:

using SkyrimForge.Game;
using SkyrimForge.Hooks;
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

using unsafe ActivateFunction = delegate* unmanaged[Thiscall]<SkyrimForge.Game.ActorBase, SkyrimForge.Game.ObjectReference, SkyrimForge.Game.ObjectReference, byte, SkyrimForge.Game.TESBoundObject, int, byte>;
using unsafe ProcessMessageFunction = delegate* unmanaged[Thiscall]<SkyrimForge.Game.StatsMenu, SkyrimForge.Game.UIMessage, SkyrimForge.Game.UI_MESSAGE_RESULTS>;

namespace SkyrimForge.ExamplePlugins;

/// <summary>Replaces the virtual table entries of StatsMenu::ProcessMessage and TESNPC::Activate, logs calls other than menu updates, and calls the original.</summary>
/// <remarks>The pointer parameters are declared as view types, which are one address each, so they match the game's own parameters.</remarks>
public sealed class VirtualFunctionPlugin(IFunctionHooks functionHooks, ILog log) : IPlugin
{
    private const int processMessageVTableIndex = 0x04;

    private const int activateVTableIndex = 0x37;

    private static ILog? replacementLog;
    private static nint originalProcessMessage;
    private static nint originalActivate;
    private static int updateCount;

    /// <inheritdoc/>
    public unsafe void Start()
    {
        replacementLog = log;
        ProcessMessageFunction processMessage = &OnProcessMessage;
        originalProcessMessage = functionHooks.ReplaceVirtualTableEntry("StatsMenu", processMessageVTableIndex, (nint)processMessage);
        ActivateFunction activate = &OnActivate;
        originalActivate = functionHooks.ReplaceVirtualTableEntry("TESNPC", activateVTableIndex, (nint)activate);
        log.Write("Replaced StatsMenu::ProcessMessage and TESNPC::Activate. Open the skills screen or talk to a character.");
    }

    // An exception must not escape into the game's code.
    [UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
    private static unsafe UI_MESSAGE_RESULTS OnProcessMessage(StatsMenu self, UIMessage message)
    {
        try
        {
            if (!message.Exists)
            {
                replacementLog?.Write("StatsMenu::ProcessMessage ran for no message.");
            }
            else if (message.Type == UI_MESSAGE_TYPE.kUpdate)
            {
                updateCount++;
            }
            else if (message.Type == UI_MESSAGE_TYPE.kHide)
            {
                replacementLog?.Write($"StatsMenu::ProcessMessage ran for {UI_MESSAGE_TYPE.kHide}, after {updateCount} updates.");
                updateCount = 0;
            }
            else
            {
                replacementLog?.Write($"StatsMenu::ProcessMessage ran for {message.Type}.");
            }
        }
        catch (Exception)
        {
        }
        return ((ProcessMessageFunction)originalProcessMessage)(self, message);
    }

    [UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
    private static unsafe byte OnActivate(ActorBase self, ObjectReference target, ObjectReference activator, byte arg3, TESBoundObject @object, int count)
    {
        byte result = ((ActivateFunction)originalActivate)(self, target, activator, arg3, @object, count);
        try
        {
            replacementLog?.Write($"TESNPC::Activate ran, {(@object.Exists ? "with an object" : "with no object")}, count {count}. It returned {result != 0}.");
        }
        catch (Exception)
        {
        }
        return result;
    }
}
  • A replacement is a static method marked UnmanagedCallersOnly, whose parameters and calling convention match the game function's. A parameter of a view type addresses nothing if the game passes null, and Exists tests for that.
  • An exception that reaches game code ends the process, so catch every exception in a replacement.
  • Call the displaced function at most once on any path. Avoid allocating in a replacement on a function the game calls often, since a garbage collection there stalls the game.
  • The game calls a replacement on any thread, so queue work that calls a member documented for the game's thread through ITaskQueue.
  • Only calls through that type's table, on objects of exactly that type, reach the replacement.

Running a Handler at an Instruction

This plugin logs each skill experience gain from an instruction inside the function that awards it:

using SkyrimForge.Game;
using SkyrimForge.Hooks;

namespace SkyrimForge.ExamplePlugins;

/// <summary>Logs each skill experience gain the player makes, from an instruction hook inside PlayerCharacter::AddSkillExperience.</summary>
/// <remarks>
/// The hook is after the function's test that the amount is positive, so it logs only applied gains, and it leaves the function's entry free for other mods' detours.
/// At the hooked instruction, edx is the skill and xmm2 the experience.
/// </remarks>
public sealed class SkillExperiencePlugin(ICodePatcher codePatcher, ILog log) : IPlugin
{
    private static readonly GameFunction addSkillExperience = new(39413, 40488);

    // mov eax, [rsp+70h] and mov rcx, [rcx+disp32]. The displacement differs by edition.
    private static readonly BytePattern expected = new("8B 44 24 70 48 8B 89 ?? ?? ?? ??");

    /// <inheritdoc/>
    public void Start()
    {
        nint site = AddressLibrary.Resolve(addSkillExperience, new GameOffset(0xC, 0xC));
        codePatcher.Apply(new InstructionHook(site, expected, context => log.Write($"Player gained {context.Xmm2.Single} experience in {(ActorValue)(int)context.Rdx}.")));
    }
}
  • AddressLibrary.Resolve finds the instruction from the function's address library identifiers and its offset on each edition.
  • Apply compares the code with the expected bytes before writing, and throws if they differ, so it writes only over the bytes the plugin expects.
  • The handler runs before the instruction, and reads the registers as they stand there through its context.