Architecture
This page explains how MonoMod's runtime detouring works internally, from the Hook you create down to the bytes patched into a method's machine code. It is based on the source and on the design notes in the repository's docs/Core/ folder. You do not need it to use RuntimeDetour, but it helps when you debug unusual behavior or build your own hooking layer on MonoMod.Core.
Layers at a Glance
| Layer | Assembly | Responsibility |
|---|---|---|
Hook, ILHook, NativeHook, DetourManager |
MonoMod.RuntimeDetour | Detour chains, ordering, trampolines, synchronization, IL hook application. |
IDetourFactory (PlatformTripleDetourFactory) |
MonoMod.Core | A single method-to-method detour, kept up to date across JIT recompilations. |
PlatformTriple |
MonoMod.Core | Operations that need architecture, OS and runtime together: creating native detours, finding a method's real entry point, ABI fixups, method identification. |
IArchitecture, ISystem, IRuntime |
MonoMod.Core | Processor architecture, operating system, and .NET runtime specifics. |
DynamicMethodDefinition, ILContext, Cecil |
MonoMod.Utils | Copying and generating method bodies. |
From Hook to Machine Code
When you create and apply a Hook:
- Normalize the source.
PlatformTriple.Current.GetIdentifiable(source)turns theMethodBaseinto a canonical instance that can be used as a key. - Validate and prepare the target.
Hookchecks signatures (see target signature rules), rents a trampoline fromTrampolinePoolfor theorigdelegate, and, when needed, generates a proxy method with aDynamicMethodDefinitionthat loads the target object and theorigdelegate before calling your method. - Find the chain.
DetourManager.GetDetourState(source)returns the method's shared state, holding the ordering graph, the no-config list, and the IL hook list. - Insert into the chain. Under the method's lock, the hook is inserted into the graph (ordering algorithm) and the chain is rebuilt.
- Prepare the end of chain. The first time a method is detoured, MonoMod.Core creates a detour from the original method to a synchronization proxy (which counts active calls so chain updates can wait for them) and asks for a clone of the original (
CreateSourceCloneIfNotILClone). The clone, possibly with ILHook changes, is what the lastorigcalls. - Wire the chain. Each chain node's trampoline is detoured to the next node's entry, and the last one to the end of chain. Updates wait until no other thread is inside the method, and block new callers until done (thread safety).
MonoMod.Core
IDetourFactory
public interface IDetourFactory
{
ICoreDetour CreateDetour(CreateDetourRequest request);
ICoreNativeDetour CreateNativeDetour(CreateNativeDetourRequest request);
bool SupportsNativeDetourOrigEntrypoint { get; }
}
| Type | Members |
|---|---|
CreateDetourRequest(MethodBase Source, MethodBase Target) |
ApplyByDefault (default true), CreateSourceCloneIfNotILClone (request a callable clone of the source). |
CreateNativeDetourRequest(IntPtr Source, IntPtr Target) |
ApplyByDefault (default true). |
ICoreDetour |
Source, Target, plus IsApplied, Apply(), Undo(), Dispose() from ICoreDetourBase. |
ICoreDetourWithClone |
SourceMethodClone (MethodInfo?) and SourceMethodCloneIL (DynamicMethodDefinition?; null means the method has no meaningful IL, which RuntimeDetour treats as "cannot be ILHooked"). |
ICoreNativeDetour |
Source, Target, HasOrigEntrypoint, OrigEntrypoint (only valid when HasOrigEntrypoint). |
DetourFactory member |
Description |
|---|---|
DetourFactory.Default |
A PlatformTripleDetourFactory over PlatformTriple.Current. |
DetourFactory.Current |
The factory everyone should use. Initially the default. |
DetourFactory.SetCurrentFactory(Func<IDetourFactory, IDetourFactory> creator) |
Replaces Current with a wrapper you build around the existing one. |
factory.CreateDetour(source, target, applyByDefault = true) |
Extension shortcut. |
factory.CreateNativeDetour(source, target, applyByDefault = true) |
Extension shortcut. |
Using the core directly:
using MonoMod.Core;
using ICoreDetour d = DetourFactory.Current.CreateDetour(sourceMethod, targetMethod);
// sourceMethod now runs targetMethod. Disposed or collected: undone.
Warning: The Core README is explicit: this is "probably not the library you want". Only one core detour may exist per method. MonoMod.Core does not track which methods are already detoured and does not throw if you detour one twice, but the detours will not be cleaned up properly. There is no way to call the original or change IL at this level. Interfaces in this package may gain members in minor versions. Use RuntimeDetour (or Harmony) unless you are writing such a library.
The default factory re-creates the underlying native detour whenever the runtime recompiles the source method (tiered compilation, OSR), using the IRuntime.OnMethodCompiled event.
PlatformTriple
PlatformTriple.Current combines one IArchitecture, one ISystem and one IRuntime, created by CreateCurrentArchitecture, CreateCurrentSystem and CreateCurrentRuntime from PlatformDetection. SetPlatformTriple can replace it only before it is first initialized (afterwards it throws InvalidOperationException("The platform triple has already been initialized; cannot set a new one")).
Public operations useful to library authors:
| Method | Description |
|---|---|
Compile(MethodBase method, RuntimeMethodHandle handle = default) |
JIT-compiles a method, including generic instantiations. Throws ArgumentException("Cannot prepare generic method definition") for open generic definitions. |
GetIdentifiable(MethodBase method) |
A canonical MethodBase, suitable as a dictionary or ConditionalWeakTable key. |
PinMethodIfNeeded(MethodBase) |
Keeps a method from being collected while detoured, when the runtime needs it. |
TryDisableInlining(MethodBase, RuntimeMethodHandle = default) |
Asks the runtime to stop inlining a method, where supported. |
GetNativeMethodBody(MethodBase, RuntimeMethodHandle = default) |
The real code address, following precode thunks. Throws NotSupportedException("Could not get entrypoint for ... (stuck in a loop)") if it cannot. |
CreateSimpleDetour(...), CreateNativeDetour(...) |
Low-level byte patching (with an optional alternate entry point for calling the original). |
HostTriple, SupportedFeatures, Abi |
Information about the current platform. |
The remaining members exist to implement the detour factory.
IArchitecture, ISystem, IRuntime
From docs/Core/Architecture.md and the implementations in src/MonoMod.Core/Platforms:
IArchitecture(x86Arch,x86_64Arch,Arm64Arch) decides which jump sequence to write (ComputeDetourInfo,GetDetourBytes) and how to retarget an existing one (ComputeRetargetInfo,GetRetargetBytes). It also providesKnownMethodThunks, byte patterns of runtime precode stubs that must be walked to reach a method's real body. On x86_64 one detour kind,Rel32Ind64, jumps through a nearby indirection cell; this works more often because the memory allocator can place that cell close to the patched code.ISystem(WindowsSystem,LinuxSystem,MacOSSystem) handles memory: estimating readable memory after an address, an atomicPatchDatamethod, and an allocator that can allocate "near" an address.PatchDatais atomic because of platforms such as Apple M1, where memory can never be writable and executable at the same time: the whole make-writable/copy/restore sequence is done natively without disturbing running managed code. On POSIX systems it also provides a native exception helper (see below).IRuntime(FxCLR2Runtime,FxCLR4Runtime,Core21Runtime...Core110Runtime,MonoRuntime) pokes into runtime internals: method identification, getting a reliableRuntimeMethodHandle, disabling inlining, pinning, getting a method's entry point, and (for CoreCLR) theOnMethodCompiledevent.
The CoreCLR JIT Hook
To know when a method is recompiled, MonoMod.Core hooks CoreCLR's JIT. The runtime loads the clrjit library, whose getJit export returns an ICorJitCompiler interface. MonoMod replaces the compileMethod slot of its vtable with its own hook. Because the vtable layout and calling convention change between versions, each runtime class exposes the slot indices and an expected JIT version GUID, which is compared with the JIT's getVersionGuid result, as the runtime itself does. Altjits are not handled. If several CLRs are loaded in a process, use the JitPath switch.
Native Exception Helper
On Linux and macOS, exception unwinding relies on unwind tables stored in the loaded ELF/Mach-O binaries, which dynamically generated code does not have. For native exceptions to propagate safely through MonoMod's hooks, ISystem can provide an INativeExceptionHelper, implemented by a small native library that MonoMod writes to disk and loads (by default in /tmp; see HelperDropPath). Per its design document it currently supports propagating, not catching, native exceptions.
Runtime-Async Methods
Newer CoreCLR versions implement runtime async: the runtime, not the C# compiler, generates the async state machine. Every method that might be runtime-async (returns Task, Task<T>, ValueTask or ValueTask<T>) has two entry points, a normal one and an async-ABI one. MonoMod.Core detours both. For the async variant it injects a stub that checks the continuation argument: if non-null (the runtime is resuming a suspended call), it immediately calls the original method through an alternate entry point; otherwise it calls the detour target, which must itself use the async ABI. This stub is regenerated every time the method is recompiled, because the runtime may resume continuations in older code versions. RuntimeAsync.IsSupported (in MonoMod.Utils) reports whether the running runtime has the feature, and DynamicMethodDefinition.IsAsync marks generated methods as runtime-async.