ILCursor and ILContext

MonoMod.Cil.ILContext and MonoMod.Cil.ILCursor (in MonoMod.Utils) are the tools for reading and editing a method body expressed as Mono.Cecil instructions. They are what an ILHook manipulator receives, what HookGen's IL.* events pass in, and what the Patcher's custom method attribute handlers can use. This page is a reference for both types, the MoveType and SearchTarget enums, labels, and the Match* helper methods.

ILContext

An ILContext wraps one Cecil MethodDefinition while it is being manipulated.

Member Description
delegate void Manipulator(ILContext il) The callback type used by ILHook and HookGen.
ILContext(MethodDefinition method) Creates a context.
Invoke(Manipulator manip) Runs a manipulator (see below). Throws InvalidOperationException if the context is read-only.
Method, IL, Body, Module, Instrs The Cecil method, its ILProcessor, body, module, and instruction list.
Labels Read-only list of the ILLabels defined in this context.
IsReadOnly true after MakeReadOnly() (the IL processor is gone).
MakeReadOnly() Drops the references to the method, processor and labels.
Import(Type), Import(FieldInfo), Import(MethodBase) Import reflection objects into the method's module.
DefineLabel(), DefineLabel(Instruction target) Create a label.
IndexOf(Instruction?) Index of an instruction; Instrs.Count for null.
GetIncomingLabels(Instruction?) Labels whose target is the instruction.
AddReference<T>(in T), GetReference<T>(id), SetReference<T>(id, value), GetReferenceCell(id) Store objects the generated code can load at runtime.
CreateLocal<T>(), CreateLocal(Type), CreateLocal(TypeReference) Add a local variable.
OnDispose Event raised when the context is disposed.
ToString() A textual dump of the method's IL, handy for debugging.

What Invoke Does

  1. Every branch operand that is an Instruction (or Instruction[] for switch) is replaced by an ILLabel pointing at it. Inside a manipulator, branch operands are ILLabels, which is why matching helpers such as MatchBr(out ILLabel) take labels.
  2. Your manipulator runs.
  3. Unless the context became read-only, labels are converted back to instructions, and FixShortLongOps() rewrites short branch forms that no longer fit (so you can emit br and let MonoMod pick br.s or br).

The obsolete At(int), At(ILLabel) and At(Instruction) methods still exist; use new ILCursor(il).Goto(...) instead.

Creating a Cursor and Moving It

var c = new ILCursor(il);   // positioned before the first instruction (Index 0)
var copy = c.Clone();       // or new ILCursor(c)

A cursor sits between two instructions:

Member Description
Next The instruction after the cursor (null at the end of the method).
Prev / Previous The instruction before the cursor.
Index Index of Next (equals Instrs.Count at the end).
Context, Method, IL, Body, Module, Instrs Shortcuts to the context.
IncomingLabels Labels targeting Next.
SearchTarget See Searching.
IsBefore(instr) / IsAfter(instr) Position tests.
ToString() The method, index and search target plus the surrounding instructions.

Movement methods all return the cursor, so they chain:

Method Description
Goto(Instruction? insn, MoveType moveType = Before, bool setTarget = false) Move relative to an instruction. With MoveType.After, the cursor goes after insn (never past the end).
Goto(int index, MoveType moveType = Before, bool setTarget = false) Move to an index. Negative indexes count from the end (Goto(-1) is before the last instruction).
GotoLabel(ILLabel label, MoveType moveType = AfterLabel, bool setTarget = false) Move to a label's target. Note the default is AfterLabel.
MoveAfterLabels() / MoveAfterLabels(bool intoEHRanges) Make instructions emitted next become the new target of labels (and, by default, of try/handler starts) currently pointing at Next.
MoveBeforeLabels() The default state: emitted instructions do not retarget labels.

Searching

ILCursor GotoNext(MoveType moveType = MoveType.Before, params Func<Instruction, bool>[] predicates);
bool TryGotoNext(MoveType moveType = MoveType.Before, params Func<Instruction, bool>[] predicates);
ILCursor GotoPrev(MoveType moveType = MoveType.Before, params Func<Instruction, bool>[] predicates);
bool TryGotoPrev(MoveType moveType = MoveType.Before, params Func<Instruction, bool>[] predicates);
// plus overloads without moveType

The predicates describe a consecutive sequence of instructions: the first predicate must match one instruction, the second the instruction right after it, and so on. A null predicate matches anything. On success the cursor moves before the first matched instruction (Before, AfterLabel) or after the last one (After). GotoNext/GotoPrev throw KeyNotFoundException when nothing matches; the Try versions return false and leave the cursor where it was.

Successful searches set SearchTarget, so that repeating the same search finds the next occurrence instead of matching the same place again:

SearchTarget Meaning
None No restriction (after manual moves, emits that reset it, or removals).
Next Set by a search with Before/AfterLabel. A forward search skips the current Next instruction.
Prev Set by a search with After. A backward search cannot match the instruction just before the cursor.

Loop over every match like this:

var c = new ILCursor(il);
while (c.TryGotoNext(i => i.MatchLdcI4(100)))
{
    // the compiler may have used ldc.i4.s here, so set both opcode and operand
    c.Next!.OpCode = OpCodes.Ldc_I4;
    c.Next.Operand = 200;
}

FindNext / FindPrev

FindNext(out ILCursor[] cursors, params predicates) and TryFindNext(...) match predicates with gaps allowed: each predicate is searched forward from the previous match, and you get one cursor per predicate (each positioned Before its instruction). FindPrev/TryFindPrev search backwards, matching the last predicate first. FindNext/FindPrev throw KeyNotFoundException if any predicate is not found.

MoveType and Labels

MoveType Cursor position after a move Effect on emitted code
Before Before the target instruction Branches to the target still land on the target, skipping your inserted code.
AfterLabel Before the target, "after its labels" Branches and exception-handler starts that pointed at the target are moved to your first emitted instruction, so your code runs on every path into the target.
After After the target (or after the last matched instruction) Your code runs after it.

Choosing between Before and AfterLabel matters whenever the target is a branch destination (loop heads, else blocks, the instruction after an if). AfterLabel is usually what you want when inserting code that must always run at that point.

Labels

ILLabel has a mutable Target (Instruction?) and a Branches enumeration of instructions that use it.

Method Description
DefineLabel() A new label with no target.
MarkLabel(ILLabel? label) Points label (a new one if null) at Next and keeps it "after" the cursor, so instructions you emit next become its target.
MarkLabel() Defines and marks a new label at the current position; returns it.
MarkLabel(Instruction inst) Returns a new label targeting inst.
// if (!Condition()) skip the original "TakeDamage" call
var c = new ILCursor(il);
c.GotoNext(i => i.MatchCallvirt<Player>("TakeDamage"));
ILLabel skip = c.DefineLabel();
c.EmitDelegate<Func<bool>>(() => Settings.GodMode);
c.EmitBrtrue(skip);
c.Index++;               // step over the call
c.MarkLabel(skip);       // the branch lands here

(This sketch ignores stack balance: if the skipped call consumed arguments or returned a value, you must also handle those.)

Emitting Instructions

All emit methods insert at the cursor, move the cursor after the new instruction, and return the cursor. If the cursor is "after labels", the first emitted instruction takes over those labels.

Emit(OpCode opcode, ...) overloads accept: no operand, ParameterDefinition, VariableDefinition, Instruction, Instruction[], double, float, long, sbyte, byte, int, string, FieldReference, CallSite, TypeReference, MethodReference, and the reflection types FieldInfo, MethodBase and Type (imported automatically), plus object as a catch-all. Emit<T>(OpCode opcode, string memberName) uses the first member of T named memberName (searched with all binding flags), which is ambiguous for overloaded methods.

Generated EmitXxx Methods

A source generator adds one method per opcode, named after the Cecil opcode without underscores, for example EmitLdarg0(), EmitLdcI4(int), EmitLdstr(string), EmitCall(MethodBase), EmitCallvirt(MethodReference), EmitBrtrue(ILLabel), EmitStloc(VariableDefinition), EmitNewobj(MethodBase). The generator also adds convenient overloads: Type/FieldInfo/MethodBase operands are imported, uint/ulong are converted to int/long, and Instruction targets are turned into labels. Opcodes with short forms (ldarg, ldloc, stloc, br, brtrue, beq, leave, ...) are emitted in their long form and shortened later by FixShortLongOps.

c.EmitLdarg0()
 .EmitLdfld(typeof(Player).GetField("Health")!)
 .EmitCall(typeof(Console).GetMethod("WriteLine", new[] { typeof(int) })!);

Removing Instructions

Method Description
Remove() Removes Next.
RemoveRange(int num) Removes num instructions starting at Next.

Labels and exception-handler boundaries that pointed at a removed instruction are moved to the instruction following the removed range, and the cursor stays at the same index (now before that following instruction). SearchTarget is reset to None.

// make "return true;" return false
new ILCursor(il).Remove().EmitLdcI4(0);

That exact line is used in the ILHookPoisonTest unit test on a method whose body is ldc.i4.1; ret.

Embedding Objects and Delegates

Generated IL cannot reference arbitrary runtime objects directly. These methods store an object in the context and emit code to load it:

Method Description
int AddReference<T>(in T t) Stores t, returns its ID (nothing emitted).
void EmitGetReference<T>(int id) Emits code that pushes the stored value.
int EmitReference<T>(in T? t) AddReference + EmitGetReference in one call.
int EmitDelegate<T>(T cb) where T : Delegate Emits a call to cb, with the same stack behavior as call (pops the delegate's parameters, pushes its return value). Returns the reference ID, or -1 when cb was a single-cast delegate with no target and could be called directly.

EmitDelegate uses generated fast invokers when they exist for the delegate type, and falls back to callvirt Invoke otherwise.

Instruction Matching Helpers

MonoMod.Cil.ILPatternMatchingExt provides extension methods on Instruction, mostly generated per opcode (MatchNop(), MatchLdstr(string), MatchLdfld(out FieldReference), MatchBrtrue(out ILLabel), ...). Opcodes that have short forms match both forms. Hand-written helpers worth knowing:

Helper Matches
Match(OpCode), Match<T>(OpCode, T value), Match<T>(OpCode, out T value) Any opcode, optionally with an operand.
MatchLdarg(int) / MatchLdarg(out int) ldarg, ldarg.s, ldarg.0–ldarg.3. Similar for MatchStarg, MatchLdarga, MatchLdloc, MatchStloc, MatchLdloca.
MatchLdcI4(int) / MatchLdcI4(out int) ldc.i4 in all its forms, including ldc.i4.m1, ldc.i4.0–ldc.i4.8, ldc.i4.s.
MatchCallOrCallvirt(...) call or callvirt.
MatchBranch(...) Any branch instruction.
MatchLeaveS(...) leave.s.
MatchNewobj(Type), MatchNewobj<T>(), MatchNewobj(string typeFullName) newobj of a constructor on that type.

Member-operand opcodes (call, callvirt, ldfld, stsfld, ...) also get name-based overloads: MatchCall(Type type, string name), MatchCall<T>(string name), MatchCall(string typeFullName, string name), and overloads taking a MethodBase/FieldInfo, which compare by equivalence with the Cecil reference.

Worked Example

Double every Health reduction inside Player.Update:

new ILHook(typeof(Player).GetMethod("Update")!, il =>
{
    var c = new ILCursor(il);
    // pattern: ldfld Health ; <value> ; sub ; stfld Health
    while (c.TryGotoNext(MoveType.Before,
        i => i.MatchSub(),
        i => i.MatchStfld<Player>("Health")))
    {
        // stack: health, amount  ->  health, amount * 2
        c.EmitLdcI4(2);
        c.EmitMul();
        c.Index += 2;           // skip past "sub; stfld" so the next search moves on
    }
});

See Also