Patcher (MonoMod.Patcher)

MonoMod.Patcher is the ahead-of-time patcher and relinker. It reads an input assembly (for example a game's Celeste.exe) plus one or more patch assemblies (*.mm.dll) written in ordinary C#, merges the patches into the input, fixes every reference, and writes a new, patched assembly. This page covers the command line, how patch assemblies are found, the patching pipeline, the MonoModder class for embedding the patcher in an installer, and the environment variables it reads. The attributes you use inside patches are on Patch Modifiers.

Note: The repository's docs/README.Patcher.md calls the executable MonoMod.exe. In the current source tree the project's AssemblyName is MonoMod.Patcher, so a build produces MonoMod.Patcher.exe (or MonoMod.Patcher.dll to run with dotnet on modern targets). The commands below use MonoMod.Patcher; substitute the file name you actually have. The program prints MonoMod <version> on start either way.

Command Line

MonoMod.Patcher [options] <input assembly> [<mod> ... <output>]

Options

Options set environment variables for the current process, which the MonoModder constructor then reads:

Option Aliases Sets Effect
--dependency-missing-throw=0 --lean-dependencies MONOMOD_DEPENDENCY_MISSING_THROW=0 Do not fail when a dependency cannot be found.
--cleanup=0 --skip-cleanup MONOMOD_CLEANUP=0 Keep MonoMod's attributes in the output.
--cleanup-all=1 --cleanup-all MONOMOD_CLEANUP_ALL=1 Also remove types whose namespace or name starts with MonoMod and references to MonoMod* assemblies.
--verbose=1 --verbose, -v MONOMOD_LOG_VERBOSE=1 Verbose logging.
--cache=0 --uncached MONOMOD_RELINKER_CACHED=0 No effect in the current source: nothing reads this variable.

Options must be spelled exactly as above (no other forms are recognized), and they must come before the input path: the input is the argument right after the last recognized option.

Positional Arguments and How They Are Interpreted

The program decides what the remaining arguments mean from their count (see Program.cs). Let N be the total number of arguments, options included:

Invocation Mods Output
MonoMod.Patcher Game.exe Scanned from Game.exe's directory MONOMODDED_Game.exe next to the input
MonoMod.Patcher Game.exe Out.exe Scanned from the directory Out.exe
MonoMod.Patcher Game.exe A.mm.dll B.mm.dll Out.exe A.mm.dll, B.mm.dll (everything between input and output) Out.exe (always the last argument)

Rules:

  • When N ≤ 2, mods are scanned from the input's directory and any second argument is the output.
  • When N > 2, mods are read from the arguments between the input and the last argument, and the last argument is the output.
  • An existing output file is deleted before patching.

Warning: MonoMod.Patcher Game.exe MyMod.mm.dll (two arguments) does not apply MyMod.mm.dll as a listed mod. It treats MyMod.mm.dll as the output path, deletes that file, and scans the directory for mods. To list mods explicitly you must also give an output path.

Warning: Options count toward N. MonoMod.Patcher --verbose Game.exe Out.exe has N = 3, so it reads mods from the (empty) range between Game.exe and Out.exe and applies no mods at all. With options, either list the mods explicitly or omit the output path.

With no arguments, it prints No valid arguments (assembly path) passed.; if only options are given, No assembly path passed.. Both exit with code 0. When an exception occurs (in Release builds), it is printed and the exit code is -1.

Mod Discovery

When scanning a directory, a file is loaded as a mod if:

  • its file name starts with the input module's name minus its last three characters, which keeps the dot (Celeste. for Celeste.exe), or with that prefix with spaces removed (the comparison is case-sensitive), and
  • it ends with .mm.dll (case-insensitive).

So Celeste.MyMod.mm.dll and Celeste.Everest.mm.dll match for Celeste.exe, while CelesteTools.mm.dll does not. For an input named My Game.exe, both My Game.Mod.mm.dll and MyGame.Mod.mm.dll match.

Additional mods can be listed in MONOMOD_MODS (separated by the platform's path separator, ; on Windows and : elsewhere); they are read when the input is read. A listed path that is a directory is scanned with the same rules.

Example

You have Celeste.exe and want to change Celeste.Player.Added(Scene):

  1. Create a class library named Celeste.ModNameHere.mm, targeting the same framework as the game.
  2. Reference Celeste.exe, MonoMod.Patcher (for the attributes) and MonoMod.Utils. Set Copy Local = false on the game's assemblies, or your build will contain a copy of the game.
  3. Write a patch class:
#pragma warning disable CS0626 // orig_ method is marked external and has no attributes on it.
namespace Celeste
{
    // "patch_" + the original type name, in the same namespace. Alternatively place it
    // anywhere and use [MonoModPatch("global::Celeste.Player")].
    class patch_Player : Player
    {
        // Declares the original method. MonoMod renames the original body to orig_Added.
        public extern void orig_Added(Scene scene);

        public override void Added(Scene scene)
        {
            // code before
            orig_Added(scene);
            // code after
        }
    }
}
  1. Build Celeste.ModNameHere.mm.dll, copy it next to Celeste.exe, and run:
MonoMod.Patcher Celeste.exe

The result is MONOMODDED_Celeste.exe. Installers such as Everest's MiniInstaller automate exactly this step.

Patch types default to internal visibility, which keeps them out of runtime mods' sight. To expose new members to runtime mods, add extension methods in a public static class.

How Patching Works

The Main method runs Read(), ReadMod(...), MapDependencies(), AutoPatch() and Write(). Inside AutoPatch and the rule parsing it triggers:

  1. Rules. If a patch assembly contains a type MonoMod.MonoModRules, it is isolated, its static constructor runs, and the type is removed from the mod so different mods' rules do not conflict. Rules can add relink maps, set flags, and register custom attribute handlers. See MonoModRules.
  2. Attribute parsing. Each type is checked for MonoModCustomAttribute/MonoModCustomMethodAttribute handler declarations and for MonoModLinkFrom/MonoModHook relinks.
  3. New types. Types (including nested types) that do not exist in the input are copied, except patch types and ignored types.
  4. Members. Each member of a patch type is copied or patched. A patched method keeps the original body under orig_<name> (unless [MonoModReplace]). A patched static constructor automatically gets a call to the original .cctor (as orig_cctor) inserted before its final ret.
  5. References. Relink maps are applied and every reference (calls, field accesses, type references) is fixed to point into the patched module.
  6. Post-processing. Unless disabled, MonoMod's own attributes are removed (cleanup), members marked [MonoModPublic] (or everything, with MONOMOD_PUBLIC_EVERYTHING) are made public, and a marker type MonoMod.WasHere is added.

Detecting a Patched Assembly

bool patched = Assembly.GetExecutingAssembly().GetType("MonoMod.WasHere") != null;

This is trivially bypassed and does not detect other tools' changes; it is a convenience, not a security check.

Multiple Patches

Several patch assemblies can be applied in one run as long as they do not change the same code. When they do, the result depends on the patching order and is not strictly defined. The upstream docs recommend runtime hooks (Hook) for multi-mod scenarios.

Environment Variables

Read by the MonoModder constructor (and, for MONOMOD_MODS, by Read()):

Variable Default Effect
MONOMOD_DEPDIRS unset Extra dependency search directories, separated by the path separator.
MONOMOD_MODS unset Extra mods (files or directories) to read, separated by the path separator.
MONOMOD_LOG_VERBOSE off 1 enables verbose logs.
MONOMOD_CLEANUP on 0 keeps MonoMod attributes in the output.
MONOMOD_CLEANUP_ALL off 1 also removes MonoMod* types and assembly references.
MONOMOD_PUBLIC_EVERYTHING off 1 makes every type, method, field, property and event public.
MONOMOD_PREVENTINLINE off 1 is intended to mark every method NoInlining (see the warning below).
MONOMOD_STRICT off 1 throws RelinkTargetNotFoundException when a relink target or a dependency is missing, instead of skipping it.
MONOMOD_DEPENDENCY_MISSING_THROW on 0 tolerates missing dependencies.
MONOMOD_DEPENDENCY_REMOVE_PATCH on 0 keeps references to *.mm patch assemblies in the output.
MONOMOD_DEBUG_FORMAT auto (PDB on Windows, MDB elsewhere) pdb or mdb (case-insensitive) selects the debug symbol format written.
MONOMOD_MSCORLIB_UPGRADE auto 0 disables, any other non-empty value enables remapping of mscorlib references. When unset, it is enabled if the input references mscorlib 2.0.5.0 (typical of Unity games).
MONOMOD_GAC_ENABLED on for .NET Framework builds, off otherwise 0 (Framework) / 1 (others) changes whether the GAC is searched for dependencies.

Flags are compared literally: MONOMOD_STRICT=true does not enable strict mode; only 1 does. Likewise only 0 disables the "on by default" ones.

Warning: MONOMOD_PREVENTINLINE=1 currently does the opposite of what its name says. The code sets NoInlining and then applies ImplAttributes &= 0x0100, which keeps only the AggressiveInlining bit and clears every other implementation flag, including the NoInlining it just set. Avoid it, or verify the output with a decompiler.

Note: Setting MONOMOD_DEPENDENCY_MISSING_THROW=0 makes the default missing-dependency resolver log Use MMILRT.Modder.MissingDependencyThrow instead of setting the env var MONOMOD_DEPENDENCY_MISSING_THROW. The setting still takes effect. In MONOMOD_STRICT mode, missing dependencies throw regardless.

Using the Patcher From Code

MonoMod.MonoModder is the class Main uses, and it is designed to be embedded in installers:

using MonoMod;

using (var mm = new MonoModder
{
    InputPath = "Celeste.exe",
    OutputPath = "MONOMODDED_Celeste.exe",
})
{
    mm.Read();
    mm.ReadMod("Celeste.MyMod.mm.dll");   // a file, or a directory to scan
    mm.MapDependencies();
    mm.AutoPatch();
    mm.Write();
}

Useful public members (fields unless noted):

Member Description
InputPath/Input, OutputPath/Output Paths or streams.
Read(), ReadMod(string path), ReadMod(Stream), MapDependencies(), AutoPatch(), Write() The pipeline steps.
DependencyDirs List<string> of search directories.
Mods The loaded mod modules.
SharedData Dictionary<string, object> used by MonoModIfFlag and rules.
RelinkMap, RelinkModuleMap, SkipList Relinking and skipping state.
CustomAttributeHandlers, CustomMethodAttributeHandlers Handlers keyed by attribute full name.
OnReadMod, PostProcessors, MissingDependencyResolver, MethodParser, MethodRewriter, MethodBodyRewriter Extension hooks.
Strict, MissingDependencyThrow, CleanupEnabled, PublicEverything, PreventInline, RemovePatchReferences, UpgradeMSCORLIB, GACEnabled, LogVerboseEnabled, DebugSymbolOutputFormat, ReadingMode Options (initialized from the environment variables above; set them after construction to override).
Log(string), LogVerbose(string) Logging.

See Also