ILHook
MonoMod.RuntimeDetour.ILHook lets you modify the IL (Common Intermediate Language) body of a method at runtime. You supply a manipulator, a callback that receives an ILContext for a copy of the method's IL; MonoMod compiles the result and makes the method run it. If you know Harmony, this is the equivalent of a transpiler. This page explains how ILHooks are applied, how they combine with Hooks and with each other, and the rules your manipulator must follow.
Basic Usage
using Mono.Cecil.Cil;
using MonoMod.Cil;
using MonoMod.RuntimeDetour;
var method = typeof(ILHookTest).GetMethod("DoNothing", BindingFlags.Instance | BindingFlags.NonPublic)!;
using (new ILHook(method, il =>
{
var c = new ILCursor(il); // starts before the first instruction
c.Emit(OpCodes.Ldarg_0);
c.Emit(OpCodes.Ldc_I4_0);
c.Emit(OpCodes.Stfld, typeof(ILHookTest).GetField("DidNothing", BindingFlags.NonPublic | BindingFlags.Instance)!);
}))
{
// DoNothing() now sets this.DidNothing = false before running its original body.
}
This is the TestILHooks unit test from the repository, slightly condensed.
| Property | Value |
|---|---|
| Namespace | MonoMod.RuntimeDetour |
| Manipulator type | ILContext.Manipulator (delegate void Manipulator(ILContext il), in MonoMod.Cil) |
| Applied by default | Yes |
| Default config | DetourContext.GetDefaultConfig() |
Constructors
The overloads mirror Hook:
public ILHook(MethodBase source, ILContext.Manipulator manip);
public ILHook(MethodBase source, ILContext.Manipulator manip, bool applyByDefault);
public ILHook(MethodBase source, ILContext.Manipulator manip, DetourConfig? config);
public ILHook(MethodBase source, ILContext.Manipulator manip, DetourConfig? config, bool applyByDefault);
public ILHook(MethodBase method, ILContext.Manipulator manipulator, IDetourFactory factory,
DetourConfig? config, bool applyByDefault);
Each MethodBase overload also exists with Expression<Action> and Expression sources (the expression must be a single method call).
| Property | Type | Description |
|---|---|---|
Method |
MethodBase |
The method being modified (normalized via PlatformTriple.Current.GetIdentifiable). |
Manipulator |
ILContext.Manipulator |
Your callback. |
Config |
DetourConfig? |
Ordering config. |
IsValid / IsApplied |
bool |
As for Hook. |
HookInfo |
ILHookInfo |
Introspection object. See Introspection. |
Apply(), Undo(), Dispose() and the finalizer behave exactly as for Hook: an ILHook that is garbage collected is undone.
How ILHooks Are Applied
Every hooked method has one end of chain: the method that runs after all Hooks have called orig. Without ILHooks it is a plain clone of the original. With ILHooks, MonoMod does this every time an ILHook on that method is added or removed:
- Take a fresh
DynamicMethodDefinitionof the original, unmodified IL. - Invoke every active manipulator on it, in order: first the ILHooks that have a
DetourConfig(in the order computed by the ordering graph), then the ILHooks without a config, in the order they were applied. - Generate the new method and compile it immediately (
PlatformTriple.Current.Compile), so that invalid IL throws now rather than at the next call. - Only after compilation succeeds, switch the end of chain to the new method.
- Make each manipulator's
ILContextread-only.
Two consequences matter for your code:
- Your manipulator runs many times. Adding or removing any ILHook on the same method re-runs all of them on a fresh copy. Manipulators must be repeatable and must not depend on state left over from a previous run (for example a counter that only works the first time).
- Hooks wrap ILHooks.
Hooks form the outer chain; the IL-modified body is what the lastorigcalls.
Failure and Recovery
If a manipulator throws, or the resulting IL fails to compile, the add is rolled back: the ILHook is removed from the method's lists, the end of chain is rebuilt without it, and the exception propagates out of Apply() (and therefore out of the constructor, when applyByDefault is true). The method keeps working.
The ILHookPoisonTest unit test shows this: an ILHook that emits a stray pop makes the constructor throw InvalidProgramException, the method still returns its original value, and a later valid ILHook on the same method works normally.
| Exception | Message | Cause |
|---|---|---|
InvalidProgramException (or another JIT error) |
runtime-specific | The modified IL is invalid (unbalanced stack, bad branch, wrong types). |
InvalidOperationException |
Target method cannot be ILHooked |
MonoMod could not obtain an IL copy of the method (it has no meaningful IL body). |
KeyNotFoundException |
— | Thrown by ILCursor.GotoNext/GotoPrev when the pattern is not found (from your manipulator). |
ObjectDisposedException |
— | Apply()/Undo() after Dispose(). |
Writing Manipulators
The ILCursor reference describes the cursor API in detail. The common shape is "find a pattern, then emit":
new ILHook(typeof(Player).GetMethod("TakeDamage")!, il =>
{
var c = new ILCursor(il);
// Find "ldarg.1" (the `amount` parameter) and move after it.
if (!c.TryGotoNext(MoveType.After, i => i.MatchLdarg(1)))
return; // pattern not found: leave the method unchanged
// Transform the value on the stack with a C# delegate.
c.EmitDelegate<Func<int, int>>(amount => Math.Max(0, amount - 5));
});
EmitDelegate emits a call to your delegate with normal call stack behavior: it pops the delegate's parameters and pushes its return value. A single-cast delegate whose Target is null (one created from a static method group) is emitted as a direct call to that method. Every other delegate, including C# lambdas (the compiler usually gives even non-capturing lambdas a hidden target object), is stored in a reference cell and invoked through it.
Rules of Thumb
- Keep the stack balanced. Whatever you push, something must pop.
- Respect labels. Branches that targeted the instruction you insert before will skip your code unless you use
MoveType.AfterLabel(orMoveAfterLabels()); see MoveType. - Do not keep the
ILContextorILCursorafter the manipulator returns. The context is made read-only and its references are released. - Prefer
TryGotoNextin mods, so that a game update changing the IL disables your patch instead of throwing. - Use
MatchCallOrCallvirtwhen you do not care whether a call is virtual.
ILHook vs. Hook
| Need | Use |
|---|---|
| Run code before/after a method, change arguments or the return value | Hook |
| Replace a method entirely | Hook without calling orig |
| Change something in the middle of a method (a constant, a call, a condition) | ILHook |
| Insert code at a specific point inside a loop or branch | ILHook |