Patch Modifiers and MonoModRules
Patch assemblies for the Patcher are ordinary C# libraries. MonoMod reads their types and members and decides what to do from naming conventions (patch_, orig_) and from a set of modifier attributes in the MonoMod namespace (defined in the MonoMod.Patcher assembly). This page documents the naming conventions, every modifier, and the MonoModRules class that runs code at patch time.
- Naming conventions
- Modifier reference
- Conditional patching
- Relinking
- MonoModRules
- Custom attribute handlers
Naming Conventions
| Convention | Meaning |
|---|---|
class patch_Foo in the same namespace as Foo |
Patches the existing type Foo. The patch_ prefix is stripped. Inheriting from Foo (class patch_Foo : Foo) lets you use its visible members without redeclaring them. |
[MonoModPatch("global::Ns.Foo")] on any class |
Same as patch_, with a custom compile-time name and location. |
| A method with the same signature as an existing one | Replaces that method's body. The original body is kept as orig_<Name>. |
extern method named orig_<Name> |
Declares the original so your new body can call it. Add #pragma warning disable CS0626 to silence the compiler warning about extern without attributes. |
| A new member or type | Added to the target. |
Not every member is patched. From AllowedSpecialName in MonoModder.cs: property getters and setters and operator methods (op_*) are patched; static constructors are patched (and automatically call the original .cctor); instance constructors are only patched when marked [MonoModConstructor]; other runtime-special-name methods are skipped.
Modifier Reference
All modifiers live in namespace MonoMod. Unless noted, they are removed from the output by the cleanup pass.
| Attribute | Applies to | Effect |
|---|---|---|
[MonoModIgnore] |
type, method | MonoMod ignores the item (except for its MonoMod attributes). Use it for members you declare only to satisfy the compiler, for example a base class from another assembly. |
[MonoModReplace] |
method | No orig_ method is generated; your body replaces the original outright. |
| field | The field's attributes and type are replaced. | |
| property | The original property is removed first, as if you were adding your own. | |
| type | The original type is removed first. | |
[MonoModRemove] |
field, method, type (and properties/events) | The item is removed from the output. |
[MonoModNoNew] |
type, method | Only patch if the item already exists in the input; never add it. |
[MonoModConstructor] |
constructor, or method | Patch an instance constructor; on a regular method, treat it like a constructor. |
[MonoModOriginal] |
method | Marks a method as an "original" even if it is not named orig_*. MonoMod adds it automatically to generated originals. |
[MonoModOriginalName("name")] |
method (the patch, not the orig_) |
Name to give the generated original instead of orig_<Name>. |
[MonoModPublic] |
method, field, property, type | Makes the item public in the output. |
[MonoModEnumReplace] |
enum type | The enum's values are replaced. |
[MonoModForceCall] |
method | All calls to the method are rewritten to call. |
[MonoModForceCallvirt] |
method | All calls to the method are rewritten to callvirt. |
[MonoModTargetModule("name")] |
type | Patch only when the input module's assembly name (simple or full) equals name. Use it to target a specific version or to ship one mod for several inputs. |
[MonoModIfFlag("key")], [MonoModIfFlag("key", fallback)] |
type, method, field | Conditional on a flag. See below. |
[MonoModOnPlatform(params OSKind[])] |
type, method, field | Intended as an #ifdef PLATFORM. See the warning below. |
[MonoModLinkTo(...)] |
type, method, field | Calls to this item from mods are relinked to another target. |
[MonoModLinkFrom("id")], [MonoModLinkFrom(Type)] |
type, method, field (multiple allowed) | Calls to the item identified by id are relinked to the item carrying the attribute. |
[MonoModHook(...)] |
Obsolete: "Use MonoModLinkFrom or RuntimeDetour / HookGen instead." | |
[MonoModCustomAttribute("handler")], [MonoModCustomMethodAttribute("handler")] |
your attribute class | Registers a handler method in your MonoModRules. See Custom attribute handlers. |
[MonoModAdded] |
Added by MonoMod to patched types and members. |
Conditional Patching
MonoModIfFlag
[MonoModIfFlag("key")] reads MonoModder.SharedData["key"]:
| Flag state | [MonoModIfFlag("key")] |
[MonoModIfFlag("key", false)] |
|---|---|---|
set to true |
patched | patched |
set to false |
ignored | ignored |
not set, or not a bool |
patched (fallback true) |
ignored |
Set flags from MonoModRules with MonoModRule.Flag.Set("key", value) or directly on MonoModder.SharedData when embedding the patcher.
MonoModTargetModule
Acts as a filter on the input module only: the type is skipped unless asmName.Name == name || asmName.FullName == name.
MonoModOnPlatform
Warning: In the current source,
[MonoModOnPlatform]with at least one platform makes the item be ignored on every platform. InMatchingConditionals, a matching platform only executescontinueinside the inner loop over platforms (it does not mark a match), and afterwards the status is combined withplats.Length == 0. Until this is fixed, use[MonoModIfFlag]with a flag set inMonoModRulesfromPlatformDetection.OSinstead.
// Workaround with MonoModRules:
namespace MonoMod
{
static class MonoModRules
{
static MonoModRules()
{
MonoMod.InlineRT.MonoModRule.Flag.Set("Windows",
MonoMod.Utils.PlatformDetection.OS.Is(MonoMod.Utils.OSKind.Windows));
}
}
}
[MonoModIfFlag("Windows")]
class patch_WindowsOnlyThing { /* ... */ }
Relinking
Relinking rewrites references in the patched module (and its mods) from one item to another:
[MonoModLinkFrom("id")]on your member: references toid(a type full name or a member's "findable ID", the same format MonoMod uses internally, such asSystem.Void Ns.Type::Method(System.Int32)) now go to your member.[MonoModLinkTo(type)],[MonoModLinkTo(type, name)](and string overloads) on a stub in your mod: calls to the stub go to the given target instead. This is how mods call members they cannot reference directly.- From rules:
MonoModRule.RelinkType(from, to),MonoModRule.RelinkMember(from, toType, toMember)andMonoModRule.RelinkModule(from, toName).
Without MONOMOD_STRICT=1, a relink whose target cannot be found is silently skipped; in strict mode it throws RelinkTargetNotFoundException.
MonoModRules
If a patch assembly contains a type named exactly MonoMod.MonoModRules, MonoMod isolates it, runs its static constructor at patch time, and then removes the type from the mod. Rules code uses the static helper class MonoMod.InlineRT.MonoModRule:
| Member | Description |
|---|---|
MonoModRule.Modder |
The current MonoModder. |
RelinkModule(string from, string toName) |
Redirect references to assembly from to the module named toName (the input, or a mapped dependency). |
RelinkType(string from, string to) |
Redirect a type. |
RelinkMember(string from, string toType, string toMember) |
Redirect a member. |
Patch(string id, bool patch) |
false adds the item ID to the skip list (it will not be patched); true removes it again. |
Flag.Get(string key) / Flag.Set(string key, bool value) |
Boolean flags in SharedData. |
Data.Get(string key) / Data.Set(string key, object value) |
Arbitrary values in SharedData. |
namespace MonoMod
{
static class MonoModRules
{
static MonoModRules()
{
// Relink references to XNA to FNA when patching on non-Windows systems.
if (!MonoMod.Utils.PlatformDetection.OS.Is(MonoMod.Utils.OSKind.Windows))
MonoMod.InlineRT.MonoModRule.RelinkModule("Microsoft.Xna.Framework", "FNA");
MonoMod.InlineRT.MonoModRule.Flag.Set("HasFancyFeature", true);
}
}
}
Note:
Flag.GetandData.Getuse the dictionary indexer, so they throwKeyNotFoundExceptionfor a key that was never set. Check withModder.SharedData.ContainsKey(key)first if unsure.
Custom Attribute Handlers
You can define your own modifier attributes and handle them in your rules:
using Mono.Cecil;
using MonoMod.Cil;
// 1. The attribute, pointing at a handler method name in MonoModRules.
[MonoModCustomMethodAttribute(nameof(MonoModRules.PatchLogCalls))]
class PatchLogCallsAttribute : Attribute { }
namespace MonoMod
{
static class MonoModRules
{
// 2. The handler: public static, (ILContext, CustomAttribute) for method attributes.
public static void PatchLogCalls(ILContext il, CustomAttribute attrib)
{
var c = new ILCursor(il);
c.EmitLdstr("patched!");
c.EmitCall(typeof(Console).GetMethod("WriteLine", new[] { typeof(string) })!);
}
}
}
// 3. Use it on a method in your patch.
class patch_Player : Player
{
public extern void orig_Update();
[PatchLogCalls]
public new void Update() => orig_Update();
}
How handlers are found and called (ParseRulesInType and RunCustomAttributeHandlers):
- The handler name is looked up with
GetMethod(name)on the isolated rules type, so it must be a public static method ofMonoModRules. [MonoModCustomAttribute]handlers are called ashandler(ICustomAttributeProvider item, CustomAttribute attribute)for any item carrying the attribute.[MonoModCustomMethodAttribute]handlers are called for methods only. If the handler's first parameter is anILContext, MonoMod wraps the method in anILContextfor you (handler(ILContext il, CustomAttribute attribute)); otherwise it is called ashandler(MethodDefinition method, CustomAttribute attribute).- An attribute you place on your
orig_declaration is copied to the generated original method when it has a registered handler.