Search code examples
c#dll

Checking a dll content with C#


I play a game with a lot of mods. These mods come in the form of resources (images, contiguration files) as well as .dlls for C# code added or modifying the original game. The problem is that there is no mechanism to prevent conflicts between mods. Example of errors

Mods are available on the steam workshop, but some are also available on Github if you want to see an example, such as CommonSense. Dll are in 1.x/Assemblies section.

I'd like to create software that scans mod files to check a potential conflict, especially reading the .dll files to ensure that the same method is not modified by multiple mods.

So far, I can't figure out how to read the contents of a dll file “easily”.

Would you have an example of code to read a dll file or to extract its methods?


Solution

  • The following code uses MetadataLoadContext to read all the HarmonyPatch attributes from a mod dll (CommonSense.dll) and print out the first (type) and second (method name) arguments. This may help you know which methods have been patched.

    var paths = new List<string>(Directory.GetFiles(@"E:\rimworldmod", "*.dll"));
    var resolver = new PathAssemblyResolver(paths);
    var mlc = new MetadataLoadContext(resolver);
    var asm = mlc.LoadFromAssemblyPath(@"E:\rimworldmod\CommonSense.dll");
    foreach(var t in asm.DefinedTypes)
    {
        foreach (var cad in t.CustomAttributes)
        {
            if (cad.AttributeType.FullName == "HarmonyLib.HarmonyPatch")
            {
                var aargs = cad.ConstructorArguments;
                if (aargs.Count > 1)
                    Console.WriteLine($"\t{aargs[0]} {aargs[1]}");
            }
        } 
    }
    

    Some notes:

    I placed all the relevant DLLs (HarmonyMod and dlls in the package krafs.rimworld.ref) in the E:\rimworldmod directory.

    Some patches, such as JobDriver_Goto_MoveNext_CommonSensePatch, which uses transpiler. The method name is declared in the method body, for this situation, you need to analyze the IL code.