HookGen (MonoMod.RuntimeDetour.HookGen)

HookGen generates a "hook helper" assembly, MMHOOK_<Assembly>.dll, for any .NET assembly. The helper exposes every hookable method as two C# events, one in an On. namespace for method hooks and one in an IL. namespace for IL manipulation, so mods can write On.Celeste.Player.Update += MyHook; instead of using reflection. Behind the events, HookGen's output calls into MonoMod.RuntimeDetour, which creates ordinary Hooks and ILHooks.

Note: The upstream documentation warns that HookGen struggles to generate assemblies for some inputs and makes hook lifetimes harder to manage. It recommends using RuntimeDetour directly for anything but the simplest use cases. In the current source tree the HookGen project is not packable (IsPackable=false, with a TODO about HookEndpointManager), so you build it from source.

Command Line

MonoMod.RuntimeDetour.HookGen [--namespace <ns>] [--namespace-il <ns>] [--orig] [--private] <input assembly> [<output>]
Option Sets Default Effect
--namespace <ns> MONOMOD_HOOKGEN_NAMESPACE On Root namespace for method-hook events.
--namespace-il <ns> MONOMOD_HOOKGEN_NAMESPACE_IL IL Root namespace for IL-hook events.
--orig MONOMOD_HOOKGEN_ORIG=1 off Also generate events for methods whose names start with orig_ (as produced by the Patcher).
--private MONOMOD_HOOKGEN_PRIVATE=1 off Also generate events for private methods and non-public types.

You can set the environment variables directly instead of passing options. Option parsing stops at the first argument that is not an option, which becomes the input. A --namespace/--namespace-il value is only consumed when at least two more arguments follow it; otherwise the option itself is taken as the input path.

  • The output defaults to MMHOOK_<input name>.dll next to the input (the extension is always changed to .dll). Any existing output file is deleted first.
  • If MONOMOD_DEPENDENCY_MISSING_THROW is not set, HookGen sets it to 0, so missing dependencies of the input are tolerated.
  • HookGen needs MonoMod.RuntimeDetour and MonoMod.Utils to be resolvable as dependencies; otherwise it throws FileNotFoundException("MonoMod.RuntimeDetour not found!") (or MonoMod.Utils not found!).

The program prints its own version and the versions of MonoMod and MonoMod.RuntimeDetour it uses.

MonoMod.RuntimeDetour.HookGen Celeste.exe
# -> MMHOOK_Celeste.dll

Ship MonoMod.RuntimeDetour.dll and MonoMod.Utils.dll (and their dependencies) along with the generated assembly, or merge it into your modding API with a tool such as il-repack.

What Gets Generated

For each type in the input, HookGen creates two static classes with the same name, one in On.<original namespace> and one in IL.<original namespace> (nested types stay nested). Types are skipped when they are generic, runtime-special, compiler-generated (name starting with <), non-public (unless --private), or when nothing in them is hookable.

For each method:

Generated member Shape
On.Ns.Type.orig_Method Delegate matching the original signature, with a self parameter first for instance methods (ref self for value types).
On.Ns.Type.hook_Method Delegate like orig_Method, with an orig_Method orig parameter inserted first.
On.Ns.Type.Method Event of type hook_Method. += creates a Hook, -= removes it.
IL.Ns.Type.Method Event of type ILContext.Manipulator. += creates an ILHook, -= removes it.

The delegate types are marked [EditorBrowsable(Never)].

Methods are skipped when they are generic, abstract, special-name (property accessors, operators, event accessors), private (unless --private), or named orig_* (unless --orig). Constructors are included, with the leading dot removed from their name (.ctor becomes ctor, .cctor becomes cctor); dots in names, for example explicit interface implementations, become underscores.

Overloads

When a type has several hookable methods with the same name, the ones with parameters get a suffix built from their parameter types, for example On.Ns.Type.Method_int_string. Built-in types use their C# keywords (int, string, bool, object, ...); other types use their name, or their full name (dots removed) when two overloads have same-named types from different namespaces. A parameterless overload keeps the plain name. If a name still collides, _1, _2, ... is appended.

Using the Generated Events

// Method hook
On.Celeste.Player.GetTrailColor += (orig, player, wasDashB) =>
{
    Color color = orig(player, wasDashB);
    return player.Facing == Facings.Left ? new Color(0xFF, color.G, color.B, color.A) : color;
};

// IL hook
IL.Celeste.Player.GetTrailColor += il =>
{
    var c = new ILCursor(il);
    c.EmitDelegate<Action>(() => Console.WriteLine("Hello from IL!"));
};

To be able to remove a hook, use a named method (a lambda creates a new delegate each time, so -= with another lambda does nothing):

On.Celeste.PlayerHair.GetHairColor += OnGetHairColor;   // add
On.Celeste.PlayerHair.GetHairColor -= OnGetHairColor;   // remove

How the Events Work: HookEndpointManager

The generated add_/remove_ accessors call MonoMod.RuntimeDetour.HookGen.HookEndpointManager, a static class kept in RuntimeDetour "for back-compat with old versions of HookGen". Its members are marked [Obsolete(..., error: true)] and hidden from IntelliSense, because they are only meant to be called by generated code.

Method Behavior
Add(MethodBase, Delegate) Creates new Hook(method, hookDelegate) and stores it keyed by (method, delegate). Adding the same delegate to the same method twice throws ArgumentException("Delegate has already been applied to this method as a hook!").
Remove(MethodBase, Delegate) Disposes and forgets the matching hook. Unknown delegates are ignored silently.
Modify(MethodBase, Delegate) / Unmodify(...) The same for ILHooks (the delegate must be an ILContext.Manipulator).
Clear() Disposes every hook created through it.

Because the Hook is created with the constructor that takes no config, it uses the ambient DetourContext. A mod loader can therefore give each mod's HookGen hooks an ID and ordering by wrapping the mod's initialization in new DetourConfigContext(new DetourConfig(modId)).Use().

The hooks are stored in static dictionaries, so they stay alive until removed, unlike Hook objects you create yourself and then drop.

See Also