Decompiled source of AutoHookGenPatcher v1.0.4
BepInEx/patchers/BepInEx.MonoMod.AutoHookGenPatcher.dll
Decompiled 6 months agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Threading.Tasks; using System.Xml.Linq; using AutoHookGenPatcher.Config; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Microsoft.CodeAnalysis; using Mono.Cecil; using Mono.Collections.Generic; using MonoMod; using MonoMod.RuntimeDetour.HookGen; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("BepInEx.MonoMod.AutoHookGenPatcher")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.4.0")] [assembly: AssemblyInformationalVersion("1.0.4+945f6afd225cb5bd55671f9f85e7515494fa6afd")] [assembly: AssemblyProduct("BepInEx.MonoMod.AutoHookGenPatcher")] [assembly: AssemblyTitle("BepInEx.MonoMod.AutoHookGenPatcher")] [assembly: AssemblyVersion("1.0.4.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace AutoHookGenPatcher { public static class HookGenPatch { private static readonly object hookGenLock = new object(); private static bool skipHashing => false; internal static bool RunHookGen(CachedAssemblyInfo plugin) { //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Unknown result type (might be due to invalid IL or missing references) //IL_025d: Unknown result type (might be due to invalid IL or missing references) //IL_0265: Unknown result type (might be due to invalid IL or missing references) //IL_0267: Unknown result type (might be due to invalid IL or missing references) //IL_026e: Expected O, but got Unknown //IL_02fe: Unknown result type (might be due to invalid IL or missing references) //IL_0305: Expected O, but got Unknown //IL_034d: Unknown result type (might be due to invalid IL or missing references) //IL_0357: Expected O, but got Unknown //IL_0399: Unknown result type (might be due to invalid IL or missing references) //IL_03a3: Expected O, but got Unknown string gUID = plugin.GUID; string path = plugin.Path; string text = Patcher.mmhookPath; if (plugin.Path.Contains(Paths.ManagedPath)) { text = Path.Combine(Patcher.mmhookPath, "Managed"); } else if (plugin.Path.Contains(Paths.PluginPath)) { text = Path.Combine(Patcher.mmhookPath, "plugins"); } else if (plugin.Path.Contains(Paths.BepInExAssemblyDirectory)) { text = Path.Combine(Patcher.mmhookPath, "core"); } else if (plugin.Path.Contains(Paths.PatcherPluginPath)) { text = Path.Combine(Patcher.mmhookPath, "patchers"); } string text2 = ".dll"; string text3 = "MMHOOK_" + gUID + text2; string text4 = path; string text5 = Path.Combine(text, text3); bool flag = true; foreach (string mmHookFile in Patcher.mmHookFiles) { if (Path.GetFileName(mmHookFile).Equals(text3)) { text5 = mmHookFile; flag = false; break; } } if (flag) { Directory.CreateDirectory(text); } FileInfo fileInfo = new FileInfo(text4); long length = fileInfo.Length; long num = 0L; if (File.Exists(text5)) { try { AssemblyDefinition val = AssemblyDefinition.ReadAssembly(text5); try { if (val.MainModule.GetType("BepHookGen.size" + length) != null) { if (skipHashing) { Patcher.ExtendedLogging("[RunHookGen] (skip hashing) Already ran for latest version of " + text3); return true; } num = fileInfo.MakeHash(); if (val.MainModule.GetType("BepHookGen.content" + num) != null) { Patcher.ExtendedLogging("[RunHookGen] Already ran for latest version of " + text3); plugin.MMHOOKDate = File.GetLastWriteTime(text5).Ticks; return true; } } } finally { ((IDisposable)val)?.Dispose(); } } catch (BadImageFormatException) { Patcher.Logger.LogWarning((object)("Failed to read " + Path.GetFileName(text5) + ", probably corrupted, remaking one.")); } } Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE", "1"); Environment.SetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW", "0"); MonoModder val2 = null; try { lock (hookGenLock) { val2 = new MonoModder { InputPath = text4, OutputPath = text5, ReadingMode = (ReadingMode)2 }; IAssemblyResolver assemblyResolver = val2.AssemblyResolver; IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null); if (obj != null) { ((BaseAssemblyResolver)obj).AddSearchDirectory(Paths.BepInExAssemblyDirectory); } val2.Read(); val2.MapDependencies(); if (File.Exists(text5)) { Patcher.Logger.LogDebug((object)("Clearing " + text5)); File.Delete(text5); } } Patcher.Logger.LogInfo((object)("[RunHookGen] Starting HookGenerator for " + text3)); HookGenerator val3; lock (hookGenLock) { val3 = new HookGenerator(val2, Path.GetFileName(text5)); } ModuleDefinition outputModule = val3.OutputModule; try { val3.Generate(); outputModule.Types.Add(new TypeDefinition("BepHookGen", "size" + length, (TypeAttributes)1, outputModule.TypeSystem.Object)); if (!skipHashing) { outputModule.Types.Add(new TypeDefinition("BepHookGen", "content" + ((num == 0L) ? fileInfo.MakeHash() : num), (TypeAttributes)1, outputModule.TypeSystem.Object)); } lock (hookGenLock) { outputModule.Write(text5); } } finally { ((IDisposable)outputModule)?.Dispose(); } Patcher.Logger.LogInfo((object)("[RunHookGen] HookGen done for " + text3)); plugin.MMHOOKDate = File.GetLastWriteTime(text5).Ticks; } catch (BadImageFormatException) { plugin.BadImageFormat = true; } catch (Exception arg) { try { Patcher.Logger.LogInfo((object)string.Format("[{0}] Error in HookGen for {1}: {2}", "RunHookGen", text3, arg)); } catch (Exception) { } } finally { if (val2 != null) { val2.Dispose(); } } return true; } private static long MakeHash(this FileInfo fileInfo) { FileStream inputStream = fileInfo.OpenRead(); byte[] value = null; using (MD5 mD = new MD5CryptoServiceProvider()) { value = mD.ComputeHash(inputStream); } long num = BitConverter.ToInt64(value, 0); if (num == 0L) { return 1L; } return num; } } internal class CachedAssemblyInfo { internal string GUID { get; set; } internal string Path { get; set; } internal long DateModified { get; set; } internal long MMHOOKDate { get; set; } internal List<string> References { get; set; } internal bool AlreadyHasMMHOOK { get; set; } internal Version PluginVersion { get; set; } internal bool BadImageFormat { get; set; } internal bool IsDuplicate { get; set; } internal CachedAssemblyInfo(string guid, string path, long dateModified, long mmhookDate, List<string>? references, string? pluginVersion, bool badImageFormat, bool alreadyHasMMHOOK) { GUID = guid; Path = path; DateModified = dateModified; MMHOOKDate = mmhookDate; References = references ?? new List<string>(); PluginVersion = ((pluginVersion == null || pluginVersion == "") ? new Version(0, 0, 0) : new Version(pluginVersion)); BadImageFormat = badImageFormat; AlreadyHasMMHOOK = alreadyHasMMHOOK; IsDuplicate = false; } internal CachedAssemblyInfo(string guid, string path, long dateModified, long mmhookDate, List<string>? references, string pluginVersion, bool badImageFormat) : this(guid, path, dateModified, mmhookDate, references, pluginVersion, badImageFormat, alreadyHasMMHOOK: false) { } internal CachedAssemblyInfo(string path) : this(null, path, 0L, 0L, null, null, badImageFormat: false, alreadyHasMMHOOK: false) { } } internal static class PluginInfo { public const string PLUGIN_GUID = "BepInEx.MonoMod.AutoHookGenPatcher"; public const string PLUGIN_NAME = "AutoHookGenPatcher"; public const string PLUGIN_VERSION = "1.0.0"; } internal static class Patcher { internal static string mmhookPath = null; internal static ManualLogSource Logger = Logger.CreateLogSource("AutoHookGenPatcher"); private static readonly PluginConfig BoundConfig = new PluginConfig(new ConfigFile(Path.Combine(Paths.ConfigPath, "AutoHookGenPatcher.cfg"), false)); internal static List<CachedAssemblyInfo> currentPlugins = new List<CachedAssemblyInfo>(); internal static List<Task> hookGenTasks = new List<Task>(); internal static List<string> mmhookOverrides = new List<string>(); internal static List<string> mmHookFiles = new List<string>(); internal static Dictionary<string, Version> GUIDtoVer = new Dictionary<string, Version>(); internal static string? cacheLocation; internal static bool isCacheUpdateNeeded = false; internal const int cacheVersionID = 2; public static IEnumerable<string> TargetDLLs { get; } = new string[0]; public static void Initialize() { if (BoundConfig.ExtendedLogging.Value) { Logger.LogInfo((object)"[Initialize] Extended Logging is enabled."); if (BoundConfig.GenerateForAllPlugins.Value) { Logger.LogInfo((object)"[Initialize] GenerateForAllPlugins is enabled."); } } mmhookOverrides.Add("Assembly-CSharp"); mmhookPath = Path.Combine(Paths.PluginPath, "MMHOOK"); cacheLocation = Path.Combine(Paths.CachePath, "AutoHookGenPatcher_MMHOOK_Cache.xml"); mmHookFiles = (from name in Directory.GetFiles(Paths.PluginPath, "*.dll", SearchOption.AllDirectories) where Path.GetFileName(name).StartsWith("MMHOOK_") select name).ToList(); if (!Directory.Exists(mmhookPath)) { Directory.CreateDirectory(mmhookPath); } Stopwatch stopwatch = Stopwatch.StartNew(); Begin(); stopwatch.Stop(); ExtendedLogging(string.Format("[{0}] Took {1}ms", "Initialize", stopwatch.ElapsedMilliseconds)); } internal static void ExtendedLogging(string message) { if (BoundConfig.ExtendedLogging.Value) { Logger.LogInfo((object)message); } } private static void Begin() { List<CachedAssemblyInfo> list = TryLoadCache(); currentPlugins = GetPlugins(list).ToList(); for (int i = 0; i < currentPlugins.Count; i++) { CachedAssemblyInfo cachedAssemblyInfo = currentPlugins[i]; if (IsPluginInfoUpToDate(cachedAssemblyInfo)) { MarkIfDuplicate(cachedAssemblyInfo, cachedAssemblyInfo.GUID, cachedAssemblyInfo.PluginVersion); continue; } ReadPluginInfoAndMMHOOKReferences(cachedAssemblyInfo); isCacheUpdateNeeded = true; } int num = 0; int num2 = currentPlugins.Count; for (int j = 0; j < currentPlugins.Count; j++) { CachedAssemblyInfo plugin = currentPlugins[j]; if (plugin.IsDuplicate) { ExtendedLogging(string.Format("[{0}] Skipping HookGen Check For Duplicate or Old Version of {1} ({2})", "Begin", plugin.GUID, plugin.PluginVersion)); num2--; } else if (plugin.BadImageFormat) { ExtendedLogging("[Begin] Skipping HookGen Check For " + plugin.GUID + " Because BadImageFormatException"); num2--; } else if (plugin.AlreadyHasMMHOOK) { num++; } else if (BoundConfig.GenerateForAllPlugins.Value || mmhookOverrides.Contains(plugin.GUID) || currentPlugins.SelectMany((CachedAssemblyInfo plugins) => plugins.References).Contains(plugin.GUID)) { Task task = new Task(delegate { StartHookGen(plugin); }); task.Start(); hookGenTasks.Add(task); } } if (BoundConfig.GenerateForAllPlugins.Value && BoundConfig.DisableGenerateForAllPlugins.Value) { Logger.LogInfo((object)"[Begin] DisableGenerateForAllPlugins is enabled, disabling GenerateForAllPlugins."); BoundConfig.GenerateForAllPlugins.Value = false; } ExtendedLogging(string.Format("[{0}] Already Has MMHOOK: {1} Out of {2} Assemblies", "Begin", num, num2)); ExtendedLogging(string.Format("[{0}] Waiting for {1} HookGen Task{2} to finish.", "Begin", hookGenTasks.Count, (hookGenTasks.Count == 1) ? "" : "s")); hookGenTasks.ForEach(delegate(Task x) { x.Wait(); }); if (isCacheUpdateNeeded || list == null) { WriteCache(currentPlugins); } } private static void StartHookGen(CachedAssemblyInfo plugin) { if (HookGenPatch.RunHookGen(plugin)) { lock (plugin) { plugin.AlreadyHasMMHOOK = true; } isCacheUpdateNeeded = true; } } private static IEnumerable<CachedAssemblyInfo> GetPlugins(List<CachedAssemblyInfo>? cachedAssemblies) { List<string> list = new List<string>(); Directory.GetFiles(Paths.ManagedPath, "*.dll", SearchOption.AllDirectories).ToList().ForEach(list.Add); Directory.GetFiles(Paths.BepInExAssemblyDirectory, "*.dll", SearchOption.AllDirectories).ToList().ForEach(list.Add); Directory.GetFiles(Paths.PatcherPluginPath, "*.dll", SearchOption.AllDirectories).ToList().ForEach(list.Add); Directory.GetFiles(Paths.PluginPath, "*.dll", SearchOption.AllDirectories).ToList().ForEach(list.Add); IEnumerable<string> enumerable = list.Where((string name) => !Path.GetFileName(name).StartsWith("MMHOOK_")); List<string> mmhookFileNames = new List<string>(); mmHookFiles.ForEach(delegate(string x) { mmhookFileNames.Add(Path.GetFileName(x)); }); foreach (string assemblyPath in enumerable) { CachedAssemblyInfo cachedAssemblyInfo = cachedAssemblies?.Find((CachedAssemblyInfo ass) => ass.Path.Equals(assemblyPath)); if (cachedAssemblyInfo == null) { ExtendedLogging("[GetPlugins] Found New Assembly: " + Path.GetFileName(assemblyPath)); yield return new CachedAssemblyInfo(assemblyPath); } else { bool alreadyHasMMHOOK = mmhookFileNames.Contains("MMHOOK_" + cachedAssemblyInfo.GUID + ".dll"); yield return new CachedAssemblyInfo(cachedAssemblyInfo.GUID, assemblyPath, cachedAssemblyInfo.DateModified, cachedAssemblyInfo.MMHOOKDate, cachedAssemblyInfo.References, cachedAssemblyInfo.PluginVersion.ToString(), cachedAssemblyInfo.BadImageFormat, alreadyHasMMHOOK); } } } private static bool IsPluginInfoUpToDate(CachedAssemblyInfo cachedAssemblyInfo) { CachedAssemblyInfo cachedAssemblyInfo2 = cachedAssemblyInfo; long ticks = File.GetLastWriteTime(cachedAssemblyInfo2.Path).Ticks; if (ticks == cachedAssemblyInfo2.DateModified) { if (!cachedAssemblyInfo2.AlreadyHasMMHOOK) { return true; } string text = mmHookFiles.FirstOrDefault((string filePath) => Path.GetFileNameWithoutExtension(filePath).EndsWith(cachedAssemblyInfo2.GUID)); if (text == null) { Logger.LogError((object)("[IsPluginInfoUpToDate] Plugin " + cachedAssemblyInfo2.GUID + "'s MMHOOK was found yet it couldn't be found, this shouldn't be possible.")); cachedAssemblyInfo2.AlreadyHasMMHOOK = false; return false; } long ticks2 = File.GetLastWriteTime(text).Ticks; if (cachedAssemblyInfo2.MMHOOKDate != ticks2) { ExtendedLogging("[IsPluginInfoUpToDate] Plugin " + cachedAssemblyInfo2.GUID + " is up-to-date, but MMHOOK is outdated."); cachedAssemblyInfo2.AlreadyHasMMHOOK = false; } return true; } cachedAssemblyInfo2.DateModified = ticks; cachedAssemblyInfo2.AlreadyHasMMHOOK = false; return false; } private static void ReadPluginInfoAndMMHOOKReferences(CachedAssemblyInfo cachedAssemblyInfo) { try { AssemblyDefinition val = AssemblyDefinition.ReadAssembly(cachedAssemblyInfo.Path); try { cachedAssemblyInfo.GUID = GetPluginGUID(cachedAssemblyInfo, val); if (cachedAssemblyInfo.IsDuplicate) { ExtendedLogging("[ReadPluginInfoAndMMHOOKReferences] Skipping Reading This Version of " + cachedAssemblyInfo.GUID); return; } ExtendedLogging("[ReadPluginInfoAndMMHOOKReferences] Starting Reading: " + cachedAssemblyInfo.GUID); IEnumerable<AssemblyNameReference> enumerable = ((IEnumerable<AssemblyNameReference>)val.MainModule.AssemblyReferences).Where((AssemblyNameReference x) => x.Name.StartsWith("MMHOOK_")); cachedAssemblyInfo.References.Clear(); foreach (AssemblyNameReference item2 in enumerable) { ExtendedLogging("[ReadPluginInfoAndMMHOOKReferences] Found Reference to " + item2.Name + " in " + cachedAssemblyInfo.GUID + "."); string item = item2.Name.Substring(7, item2.Name.Length - 7); cachedAssemblyInfo.References.Add(item); } } finally { ((IDisposable)val)?.Dispose(); } } catch (BadImageFormatException) { ExtendedLogging("[ReadPluginInfoAndMMHOOKReferences] BadImageFormatException: " + cachedAssemblyInfo.Path); cachedAssemblyInfo.GUID = GetPluginGUID(cachedAssemblyInfo); cachedAssemblyInfo.BadImageFormat = true; } catch (Exception arg) { Logger.LogError((object)string.Format("[{0}] An error occurred while trying to read {1}\n{2}", "ReadPluginInfoAndMMHOOKReferences", cachedAssemblyInfo.Path, arg)); cachedAssemblyInfo.GUID = GetPluginGUID(cachedAssemblyInfo); } } private static string GetPluginGUID(CachedAssemblyInfo cachedAssemblyInfo, AssemblyDefinition? pluginAssembly = null) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) CustomAttribute val = null; if (pluginAssembly != null) { IEnumerable<CustomAttribute> customAttributes = pluginAssembly.MainModule.GetCustomAttributes(); val = customAttributes.FirstOrDefault((Func<CustomAttribute, bool>)((CustomAttribute x) => ((MemberReference)x.AttributeType).Name.Equals("BepInPlugin"))); } string text = null; Version version = new Version(0, 0, 0); if (val != null) { Collection<CustomAttributeArgument> constructorArguments = val.ConstructorArguments; CustomAttributeArgument val2 = constructorArguments[0]; text = ((CustomAttributeArgument)(ref val2)).Value.ToString(); val2 = constructorArguments[2]; version = new Version(((CustomAttributeArgument)(ref val2)).Value.ToString()); MarkIfDuplicate(cachedAssemblyInfo, text, version); } if (val == null || text == null || text == "") { string fileName = Path.GetFileName(cachedAssemblyInfo.Path); text = Path.GetFileNameWithoutExtension(fileName); MarkIfDuplicate(cachedAssemblyInfo, text, version); } cachedAssemblyInfo.PluginVersion = version; return text; } private static bool MarkIfDuplicate(CachedAssemblyInfo cachedAssemblyInfo, string plugin_GUID, Version plugin_Ver) { string plugin_GUID2 = plugin_GUID; CachedAssemblyInfo cachedAssemblyInfo2 = cachedAssemblyInfo; if (!GUIDtoVer.ContainsKey(plugin_GUID2)) { GUIDtoVer.Add(plugin_GUID2, plugin_Ver); return false; } if (GUIDtoVer[plugin_GUID2].CompareTo(plugin_Ver) < 0) { ExtendedLogging(string.Format("[{0}] Found Newer Version of {1} {2} => {3} (this)", "MarkIfDuplicate", plugin_GUID2, GUIDtoVer[plugin_GUID2], plugin_Ver)); GUIDtoVer.Remove(plugin_GUID2); currentPlugins.Find((CachedAssemblyInfo plugin) => plugin.GUID.Equals(plugin_GUID2) && plugin != cachedAssemblyInfo2).IsDuplicate = true; GUIDtoVer.Add(plugin_GUID2, plugin_Ver); return false; } ExtendedLogging(string.Format("[{0}] Another Plugin {1} With Same Version or Newer {2} => {3} Found", "MarkIfDuplicate", plugin_GUID2, plugin_Ver, GUIDtoVer[plugin_GUID2])); cachedAssemblyInfo2.IsDuplicate = true; return true; } private static List<CachedAssemblyInfo>? TryLoadCache() { if (!File.Exists(cacheLocation)) { ExtendedLogging("[TryLoadCache] Cache didn't exist."); return null; } XDocument xDocument = new XDocument(); List<CachedAssemblyInfo> list = new List<CachedAssemblyInfo>(); try { xDocument = XDocument.Load(cacheLocation); XAttribute xAttribute = xDocument.Root.Attribute("Ver"); if (xAttribute == null || int.Parse(xAttribute.Value) != 2) { ExtendedLogging("Cache version doesn't match, forcing a refresh."); return null; } foreach (XElement item in xDocument.Root.Elements()) { list.Add(new CachedAssemblyInfo(item.Attribute("guid").Value, item.Attribute("path").Value, long.Parse(item.Attribute("dateModified").Value), long.Parse(item.Attribute("MMHOOKDate").Value), item.Attribute("references").Value.Split(new char[1] { '/' }, StringSplitOptions.RemoveEmptyEntries).ToList(), item.Attribute("pluginVersion").Value, bool.Parse(item.Attribute("badImageFormat").Value))); } ExtendedLogging(string.Format("[{0}] Loaded Cache, which contains {1} entries.", "TryLoadCache", list.Count)); return list; } catch (Exception arg) { Logger.LogError((object)$"Failed to load cache! Rebuilding it.\n{arg}"); return null; } } private static void WriteCache(IEnumerable<CachedAssemblyInfo> cachedAssemblyInfos) { try { ExtendedLogging("[WriteCache] Updating cache."); XElement xElement = new XElement("cache", new XAttribute("Ver", 2), cachedAssemblyInfos.Select((CachedAssemblyInfo assembly) => new XElement("assembly", new XAttribute("guid", assembly.GUID), new XAttribute("path", assembly.Path), new XAttribute("dateModified", assembly.DateModified), new XAttribute("MMHOOKDate", assembly.MMHOOKDate), new XAttribute("references", string.Join('/', assembly.References)), new XAttribute("pluginVersion", assembly.PluginVersion.ToString()), new XAttribute("badImageFormat", assembly.BadImageFormat)))); File.WriteAllText(cacheLocation, xElement.ToString()); } catch (Exception ex) { Logger.LogError((object)("[WriteCache] Error while writing cache file, clearing it.\n" + ex)); File.Delete(cacheLocation); } } public static void Patch(AssemblyDefinition _) { } } } namespace AutoHookGenPatcher.Config { public class PluginConfig { public ConfigEntry<bool> GenerateForAllPlugins; public ConfigEntry<bool> DisableGenerateForAllPlugins; public ConfigEntry<bool> ExtendedLogging; public PluginConfig(ConfigFile cfg) { GenerateForAllPlugins = cfg.Bind<bool>("Generate MMHOOK File for All Plugins", "Enabled", false, "If enabled, AutoHookGenPatcher will generate MMHOOK files for all plugins\neven if their MMHOOK files were not referenced by other plugins.\nUse this for getting the MMHOOK files you need for your plugin."); DisableGenerateForAllPlugins = cfg.Bind<bool>("Generate MMHOOK File for All Plugins", "Disable After Generating", true, "Automatically disable the above setting after the MMHOOK files have been generated."); ExtendedLogging = cfg.Bind<bool>("Extended Logging", "Enabled", false, "If enabled, AutoHookGenPatcher will print more information about what it is doing."); } } }
BepInEx/core/MonoMod.dll
Decompiled 6 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Cecil.Mdb; using Mono.Cecil.Pdb; using Mono.Collections.Generic; using MonoMod.Cil; using MonoMod.InlineRT; using MonoMod.Utils; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("0x0ade")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2021 0x0ade")] [assembly: AssemblyDescription("General purpose .NET assembly modding \"basework\". This package contains the core IL patcher and relinker.")] [assembly: AssemblyFileVersion("21.8.5.1")] [assembly: AssemblyInformationalVersion("21.08.05.01")] [assembly: AssemblyProduct("MonoMod")] [assembly: AssemblyTitle("MonoMod")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("21.8.5.1")] [module: UnverifiableCode] internal static class MultiTargetShims { private static readonly object[] _NoArgs = new object[0]; public static TypeReference GetConstraintType(this TypeReference type) { return type; } } namespace MonoMod { [MonoMod__SafeToCopy__] public class MonoModAdded : Attribute { } [MonoMod__SafeToCopy__] public class MonoModConstructor : Attribute { } [MonoMod__SafeToCopy__] public class MonoModCustomAttributeAttribute : Attribute { public MonoModCustomAttributeAttribute(string h) { } } [MonoMod__SafeToCopy__] public class MonoModCustomMethodAttributeAttribute : Attribute { public MonoModCustomMethodAttributeAttribute(string h) { } } [MonoMod__SafeToCopy__] public class MonoModEnumReplace : Attribute { } [MonoMod__SafeToCopy__] public class MonoModForceCall : Attribute { } [MonoMod__SafeToCopy__] public class MonoModForceCallvirt : Attribute { } [MonoMod__SafeToCopy__] [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] [Obsolete("Use MonoModLinkFrom or RuntimeDetour / HookGen instead.")] public class MonoModHook : Attribute { public string FindableID; public Type Type; public MonoModHook(string findableID) { FindableID = findableID; } public MonoModHook(Type type) { Type = type; FindableID = type.FullName; } } [MonoMod__SafeToCopy__] public class MonoModIfFlag : Attribute { public MonoModIfFlag(string key) { } public MonoModIfFlag(string key, bool fallback) { } } [MonoMod__SafeToCopy__] public class MonoModIgnore : Attribute { } [MonoMod__SafeToCopy__] [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class MonoModLinkFrom : Attribute { public string FindableID; public Type Type; public MonoModLinkFrom(string findableID) { FindableID = findableID; } public MonoModLinkFrom(Type type) { Type = type; FindableID = type.FullName; } } [MonoMod__SafeToCopy__] public class MonoModLinkTo : Attribute { public MonoModLinkTo(string t) { } public MonoModLinkTo(Type t) { } public MonoModLinkTo(string t, string n) { } public MonoModLinkTo(Type t, string n) { } } [MonoMod__SafeToCopy__] public class MonoModNoNew : Attribute { } [MonoMod__SafeToCopy__] public class MonoModOnPlatform : Attribute { public MonoModOnPlatform(params Platform[] p) { } } [MonoMod__SafeToCopy__] public class MonoModOriginal : Attribute { } [MonoMod__SafeToCopy__] public class MonoModOriginalName : Attribute { public MonoModOriginalName(string n) { } } [MonoMod__SafeToCopy__] public class MonoModPatch : Attribute { public MonoModPatch(string name) { } } [MonoMod__SafeToCopy__] public class MonoModPublic : Attribute { } [MonoMod__SafeToCopy__] public class MonoModRemove : Attribute { } [MonoMod__SafeToCopy__] public class MonoModReplace : Attribute { } [MonoMod__SafeToCopy__] public class MonoModTargetModule : Attribute { public MonoModTargetModule(string name) { } } [MonoMod__SafeToCopy__] internal class MonoMod__SafeToCopy__ : Attribute { } public delegate bool MethodParser(MonoModder modder, MethodBody body, Instruction instr, ref int instri); public delegate void MethodRewriter(MonoModder modder, MethodDefinition method); public delegate void MethodBodyRewriter(MonoModder modder, MethodBody body, Instruction instr, int instri); public delegate ModuleDefinition MissingDependencyResolver(MonoModder modder, ModuleDefinition main, string name, string fullName); public delegate void PostProcessor(MonoModder modder); public delegate void ModReadEventHandler(MonoModder modder, ModuleDefinition mod); public class RelinkMapEntry { public string Type; public string FindableID; public RelinkMapEntry() { } public RelinkMapEntry(string type, string findableID) { Type = type; FindableID = findableID; } } public enum DebugSymbolFormat { Auto, MDB, PDB } public class MonoModder : IDisposable { public static readonly bool IsMono = (object)Type.GetType("Mono.Runtime") != null; public static readonly Version Version = typeof(MonoModder).Assembly.GetName().Version; public Dictionary<string, object> SharedData = new Dictionary<string, object>(); public Dictionary<string, object> RelinkMap = new Dictionary<string, object>(); public Dictionary<string, ModuleDefinition> RelinkModuleMap = new Dictionary<string, ModuleDefinition>(); public HashSet<string> SkipList = new HashSet<string>(EqualityComparer<string>.Default); public Dictionary<string, IMetadataTokenProvider> RelinkMapCache = new Dictionary<string, IMetadataTokenProvider>(); public Dictionary<string, TypeReference> RelinkModuleMapCache = new Dictionary<string, TypeReference>(); public Dictionary<string, OpCode> ForceCallMap = new Dictionary<string, OpCode>(); public ModReadEventHandler OnReadMod; public PostProcessor PostProcessors; public Dictionary<string, Action<object, object[]>> CustomAttributeHandlers = new Dictionary<string, Action<object, object[]>> { { "MonoMod.MonoModPublic", delegate { } } }; public Dictionary<string, Action<object, object[]>> CustomMethodAttributeHandlers = new Dictionary<string, Action<object, object[]>>(); public MissingDependencyResolver MissingDependencyResolver; public MethodParser MethodParser; public MethodRewriter MethodRewriter; public MethodBodyRewriter MethodBodyRewriter; public Stream Input; public string InputPath; public Stream Output; public string OutputPath; public List<string> DependencyDirs = new List<string>(); public ModuleDefinition Module; public Dictionary<ModuleDefinition, List<ModuleDefinition>> DependencyMap = new Dictionary<ModuleDefinition, List<ModuleDefinition>>(); public Dictionary<string, ModuleDefinition> DependencyCache = new Dictionary<string, ModuleDefinition>(); public Func<ICustomAttributeProvider, TypeReference, bool> ShouldCleanupAttrib; public bool LogVerboseEnabled; public bool CleanupEnabled; public bool PublicEverything; public List<ModuleReference> Mods = new List<ModuleReference>(); public bool Strict; public bool MissingDependencyThrow; public bool RemovePatchReferences; public bool PreventInline; public bool? UpgradeMSCORLIB; public ReadingMode ReadingMode = (ReadingMode)1; public DebugSymbolFormat DebugSymbolOutputFormat; public int CurrentRID; protected IAssemblyResolver _assemblyResolver; protected ReaderParameters _readerParameters; protected WriterParameters _writerParameters; public bool GACEnabled; private string[] _GACPathsNone = new string[0]; protected string[] _GACPaths; protected MethodDefinition _mmOriginalCtor; protected MethodDefinition _mmOriginalNameCtor; protected MethodDefinition _mmAddedCtor; protected MethodDefinition _mmPatchCtor; public virtual IAssemblyResolver AssemblyResolver { get { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown if (_assemblyResolver == null) { DefaultAssemblyResolver val = new DefaultAssemblyResolver(); foreach (string dependencyDir in DependencyDirs) { ((BaseAssemblyResolver)val).AddSearchDirectory(dependencyDir); } _assemblyResolver = (IAssemblyResolver)(object)val; } return _assemblyResolver; } set { _assemblyResolver = value; } } public virtual ReaderParameters ReaderParameters { get { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown if (_readerParameters == null) { _readerParameters = new ReaderParameters(ReadingMode) { AssemblyResolver = AssemblyResolver, ReadSymbols = true }; } return _readerParameters; } set { _readerParameters = value; } } public virtual WriterParameters WriterParameters { get { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown //IL_0067: Expected O, but got Unknown //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown if (_writerParameters == null) { bool flag = DebugSymbolOutputFormat == DebugSymbolFormat.PDB; bool flag2 = DebugSymbolOutputFormat == DebugSymbolFormat.MDB; if (DebugSymbolOutputFormat == DebugSymbolFormat.Auto) { if ((PlatformHelper.Current & 0x25) == 37) { flag = true; } else { flag2 = true; } } WriterParameters val = new WriterParameters { WriteSymbols = true }; object symbolWriterProvider; if (!flag) { if (!flag2) { symbolWriterProvider = null; } else { ISymbolWriterProvider val2 = (ISymbolWriterProvider)new MdbWriterProvider(); symbolWriterProvider = val2; } } else { ISymbolWriterProvider val2 = (ISymbolWriterProvider)new NativePdbWriterProvider(); symbolWriterProvider = val2; } val.SymbolWriterProvider = (ISymbolWriterProvider)symbolWriterProvider; _writerParameters = val; } return _writerParameters; } set { _writerParameters = value; } } public string[] GACPaths { get { if (!GACEnabled) { return _GACPathsNone; } if (_GACPaths != null) { return _GACPaths; } if (!IsMono) { string environmentVariable = Environment.GetEnvironmentVariable("windir"); if (string.IsNullOrEmpty(environmentVariable)) { return _GACPaths = _GACPathsNone; } environmentVariable = Path.Combine(environmentVariable, "Microsoft.NET"); environmentVariable = Path.Combine(environmentVariable, "assembly"); _GACPaths = new string[3] { Path.Combine(environmentVariable, "GAC_32"), Path.Combine(environmentVariable, "GAC_64"), Path.Combine(environmentVariable, "GAC_MSIL") }; } else { List<string> list = new List<string>(); string text = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(typeof(object).Module.FullyQualifiedName)), "gac"); if (Directory.Exists(text)) { list.Add(text); } string environmentVariable2 = Environment.GetEnvironmentVariable("MONO_GAC_PREFIX"); if (!string.IsNullOrEmpty(environmentVariable2)) { string[] array = environmentVariable2.Split(new char[1] { Path.PathSeparator }); foreach (string text2 in array) { if (!string.IsNullOrEmpty(text2)) { string path = text2; path = Path.Combine(path, "lib"); path = Path.Combine(path, "mono"); path = Path.Combine(path, "gac"); if (Directory.Exists(path) && !list.Contains(path)) { list.Add(path); } } } } _GACPaths = list.ToArray(); } return _GACPaths; } set { GACEnabled = true; _GACPaths = value; } } public MonoModder() { //IL_00c0: Unknown result type (might be due to invalid IL or missing references) MethodParser = DefaultParser; MissingDependencyResolver = DefaultMissingDependencyResolver; PostProcessors = (PostProcessor)Delegate.Combine(PostProcessors, new PostProcessor(DefaultPostProcessor)); string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_DEPDIRS"); if (!string.IsNullOrEmpty(environmentVariable)) { foreach (string item in from dir in environmentVariable.Split(new char[1] { Path.PathSeparator }) select dir.Trim()) { IAssemblyResolver assemblyResolver = AssemblyResolver; IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null); if (obj != null) { ((BaseAssemblyResolver)obj).AddSearchDirectory(item); } DependencyDirs.Add(item); } } LogVerboseEnabled = Environment.GetEnvironmentVariable("MONOMOD_LOG_VERBOSE") == "1"; CleanupEnabled = Environment.GetEnvironmentVariable("MONOMOD_CLEANUP") != "0"; PublicEverything = Environment.GetEnvironmentVariable("MONOMOD_PUBLIC_EVERYTHING") == "1"; PreventInline = Environment.GetEnvironmentVariable("MONOMOD_PREVENTINLINE") == "1"; Strict = Environment.GetEnvironmentVariable("MONOMOD_STRICT") == "1"; MissingDependencyThrow = Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW") != "0"; RemovePatchReferences = Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_REMOVE_PATCH") != "0"; string environmentVariable2 = Environment.GetEnvironmentVariable("MONOMOD_DEBUG_FORMAT"); if (environmentVariable2 != null) { environmentVariable2 = environmentVariable2.ToLowerInvariant(); if (environmentVariable2 == "pdb") { DebugSymbolOutputFormat = DebugSymbolFormat.PDB; } else if (environmentVariable2 == "mdb") { DebugSymbolOutputFormat = DebugSymbolFormat.MDB; } } string environmentVariable3 = Environment.GetEnvironmentVariable("MONOMOD_MSCORLIB_UPGRADE"); UpgradeMSCORLIB = (string.IsNullOrEmpty(environmentVariable3) ? null : new bool?(environmentVariable3 != "0")); GACEnabled = Environment.GetEnvironmentVariable("MONOMOD_GAC_ENABLED") != "0"; MonoModRulesManager.Register(this); } public virtual void ClearCaches(bool all = false, bool shareable = false, bool moduleSpecific = false) { if (all || shareable) { foreach (KeyValuePair<string, ModuleDefinition> item in DependencyCache) { item.Value.Dispose(); } DependencyCache.Clear(); } if (all || moduleSpecific) { RelinkMapCache.Clear(); RelinkModuleMapCache.Clear(); } } public virtual void Dispose() { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) ClearCaches(all: true); ModuleDefinition module = Module; if (module != null) { module.Dispose(); } Module = null; ((IDisposable)AssemblyResolver)?.Dispose(); AssemblyResolver = null; foreach (ModuleDefinition mod in Mods) { if ((int)mod != 0) { mod.Dispose(); } } foreach (List<ModuleDefinition> value in DependencyMap.Values) { foreach (ModuleDefinition item in value) { if (item != null) { item.Dispose(); } } } DependencyMap.Clear(); Input?.Dispose(); Output?.Dispose(); } public virtual void Log(object value) { Log(value.ToString()); } public virtual void Log(string text) { Console.Write("[MonoMod] "); Console.WriteLine(text); } public virtual void LogVerbose(object value) { if (LogVerboseEnabled) { Log(value); } } public virtual void LogVerbose(string text) { if (LogVerboseEnabled) { Log(text); } } private static ModuleDefinition _ReadModule(Stream input, ReaderParameters args) { if (args.ReadSymbols) { try { return ModuleDefinition.ReadModule(input, args); } catch { args.ReadSymbols = false; input.Seek(0L, SeekOrigin.Begin); } } return ModuleDefinition.ReadModule(input, args); } private static ModuleDefinition _ReadModule(string input, ReaderParameters args) { if (args.ReadSymbols) { try { return ModuleDefinition.ReadModule(input, args); } catch { args.ReadSymbols = false; } } return ModuleDefinition.ReadModule(input, args); } public virtual void Read() { if (Module != null) { return; } if (Input != null) { Log("Reading input stream into module."); Module = _ReadModule(Input, GenReaderParameters(mainModule: true)); } else if (InputPath != null) { Log("Reading input file into module."); IAssemblyResolver assemblyResolver = AssemblyResolver; IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null); if (obj != null) { ((BaseAssemblyResolver)obj).AddSearchDirectory(Path.GetDirectoryName(InputPath)); } DependencyDirs.Add(Path.GetDirectoryName(InputPath)); Module = _ReadModule(InputPath, GenReaderParameters(mainModule: true, InputPath)); } string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_MODS"); if (string.IsNullOrEmpty(environmentVariable)) { return; } foreach (string item in from path in environmentVariable.Split(new char[1] { Path.PathSeparator }) select path.Trim()) { ReadMod(item); } } public virtual void MapDependencies() { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown foreach (ModuleDefinition mod in Mods) { ModuleDefinition main = mod; MapDependencies(main); } MapDependencies(Module); } public virtual void MapDependencies(ModuleDefinition main) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) if (DependencyMap.ContainsKey(main)) { return; } DependencyMap[main] = new List<ModuleDefinition>(); Enumerator<AssemblyNameReference> enumerator = main.AssemblyReferences.GetEnumerator(); try { while (enumerator.MoveNext()) { AssemblyNameReference current = enumerator.Current; MapDependency(main, current); } } finally { ((IDisposable)enumerator).Dispose(); } } public virtual void MapDependency(ModuleDefinition main, AssemblyNameReference depRef) { MapDependency(main, depRef.Name, depRef.FullName, depRef); } public virtual void MapDependency(ModuleDefinition main, string name, string fullName = null, AssemblyNameReference depRef = null) { if (!DependencyMap.TryGetValue(main, out var value)) { value = (DependencyMap[main] = new List<ModuleDefinition>()); } if (fullName != null && (DependencyCache.TryGetValue(fullName, out var value2) || DependencyCache.TryGetValue(fullName + " [RT:" + main.RuntimeVersion + "]", out value2))) { LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " ((" + fullName + "), (" + name + ")) from cache"); value.Add(value2); MapDependencies(value2); return; } if (DependencyCache.TryGetValue(name, out value2) || DependencyCache.TryGetValue(name + " [RT:" + main.RuntimeVersion + "]", out value2)) { LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " (" + name + ") from cache"); value.Add(value2); MapDependencies(value2); return; } string text = Path.GetExtension(name).ToLowerInvariant(); bool flag = text == "pdb" || text == "mdb"; string text2 = null; foreach (string dependencyDir in DependencyDirs) { text2 = Path.Combine(dependencyDir, name + ".dll"); if (!File.Exists(text2)) { text2 = Path.Combine(dependencyDir, name + ".exe"); } if (!File.Exists(text2) && !flag) { text2 = Path.Combine(dependencyDir, name); } if (File.Exists(text2)) { break; } text2 = null; } if (text2 == null && depRef != null) { try { AssemblyDefinition obj = AssemblyResolver.Resolve(depRef); value2 = ((obj != null) ? obj.MainModule : null); } catch { } if (value2 != null) { text2 = value2.FileName; } } if (text2 == null) { string[] gACPaths = GACPaths; for (int i = 0; i < gACPaths.Length; i++) { text2 = Path.Combine(gACPaths[i], name); if (Directory.Exists(text2)) { string[] directories = Directory.GetDirectories(text2); int num = 0; int num2 = 0; for (int j = 0; j < directories.Length; j++) { string text3 = directories[j]; if (text3.StartsWith(text2)) { text3 = text3.Substring(text2.Length + 1); } Match match = Regex.Match(text3, "\\d+"); if (match.Success) { int num3 = int.Parse(match.Value); if (num3 > num) { num = num3; num2 = j; } } } text2 = Path.Combine(directories[num2], name + ".dll"); break; } text2 = null; } } if (text2 == null) { try { AssemblyDefinition obj3 = AssemblyResolver.Resolve(AssemblyNameReference.Parse(fullName ?? name)); value2 = ((obj3 != null) ? obj3.MainModule : null); } catch { } if (value2 != null) { text2 = value2.FileName; } } if (value2 == null) { if (text2 != null && File.Exists(text2)) { value2 = _ReadModule(text2, GenReaderParameters(mainModule: false, text2)); } else if ((value2 = MissingDependencyResolver?.Invoke(this, main, name, fullName)) == null) { return; } } LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " ((" + fullName + "), (" + name + ")) loaded"); value.Add(value2); if (fullName == null) { fullName = value2.Assembly.FullName; } DependencyCache[fullName] = value2; DependencyCache[name] = value2; MapDependencies(value2); } public virtual ModuleDefinition DefaultMissingDependencyResolver(MonoModder mod, ModuleDefinition main, string name, string fullName) { //IL_007f: Unknown result type (might be due to invalid IL or missing references) if (MissingDependencyThrow && Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW") == "0") { Log("[MissingDependencyResolver] [WARNING] Use MMILRT.Modder.MissingDependencyThrow instead of setting the env var MONOMOD_DEPENDENCY_MISSING_THROW"); MissingDependencyThrow = false; } if (MissingDependencyThrow || Strict) { throw new RelinkTargetNotFoundException("MonoMod cannot map dependency " + ((ModuleReference)main).Name + " -> ((" + fullName + "), (" + name + ")) - not found", (IMetadataTokenProvider)(object)main, (IMetadataTokenProvider)null); } return null; } public virtual void Write(Stream output = null, string outputPath = null) { output = output ?? Output; outputPath = outputPath ?? OutputPath; PatchRefsInType(PatchWasHere()); if (output != null) { Log("[Write] Writing modded module into output stream."); Module.Write(output, WriterParameters); } else { Log("[Write] Writing modded module into output file."); Module.Write(outputPath, WriterParameters); } } public virtual ReaderParameters GenReaderParameters(bool mainModule, string path = null) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Expected O, but got Unknown ReaderParameters readerParameters = ReaderParameters; ReaderParameters val = new ReaderParameters(readerParameters.ReadingMode); val.AssemblyResolver = readerParameters.AssemblyResolver; val.MetadataResolver = readerParameters.MetadataResolver; val.InMemory = readerParameters.InMemory; val.MetadataImporterProvider = readerParameters.MetadataImporterProvider; val.ReflectionImporterProvider = readerParameters.ReflectionImporterProvider; val.ThrowIfSymbolsAreNotMatching = readerParameters.ThrowIfSymbolsAreNotMatching; val.ApplyWindowsRuntimeProjections = readerParameters.ApplyWindowsRuntimeProjections; val.SymbolStream = readerParameters.SymbolStream; val.SymbolReaderProvider = readerParameters.SymbolReaderProvider; val.ReadSymbols = readerParameters.ReadSymbols; if (path != null && !File.Exists(path + ".mdb") && !File.Exists(Path.ChangeExtension(path, "pdb"))) { val.ReadSymbols = false; } return val; } public virtual void ReadMod(string path) { if (Directory.Exists(path)) { Log("[ReadMod] Loading mod dir: " + path); string text = ((ModuleReference)Module).Name.Substring(0, ((ModuleReference)Module).Name.Length - 3); string value = text.Replace(" ", ""); if (!DependencyDirs.Contains(path)) { IAssemblyResolver assemblyResolver = AssemblyResolver; IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null); if (obj != null) { ((BaseAssemblyResolver)obj).AddSearchDirectory(path); } DependencyDirs.Add(path); } string[] files = Directory.GetFiles(path); foreach (string text2 in files) { if ((Path.GetFileName(text2).StartsWith(text) || Path.GetFileName(text2).StartsWith(value)) && text2.ToLower().EndsWith(".mm.dll")) { ReadMod(text2); } } return; } Log("[ReadMod] Loading mod: " + path); ModuleDefinition val = _ReadModule(path, GenReaderParameters(mainModule: false, path)); string directoryName = Path.GetDirectoryName(path); if (!DependencyDirs.Contains(directoryName)) { IAssemblyResolver assemblyResolver2 = AssemblyResolver; IAssemblyResolver obj2 = ((assemblyResolver2 is BaseAssemblyResolver) ? assemblyResolver2 : null); if (obj2 != null) { ((BaseAssemblyResolver)obj2).AddSearchDirectory(directoryName); } DependencyDirs.Add(directoryName); } Mods.Add((ModuleReference)(object)val); OnReadMod?.Invoke(this, val); } public virtual void ReadMod(Stream stream) { Log($"[ReadMod] Loading mod: stream#{(uint)stream.GetHashCode()}"); ModuleDefinition val = _ReadModule(stream, GenReaderParameters(mainModule: false)); Mods.Add((ModuleReference)(object)val); OnReadMod?.Invoke(this, val); } public virtual void ParseRules(ModuleDefinition mod) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) TypeDefinition type = mod.GetType("MonoMod.MonoModRules"); Type rulesTypeMMILRT = null; if (type != null) { rulesTypeMMILRT = this.ExecuteRules(type); mod.Types.Remove(type); } Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current = enumerator.Current; ParseRulesInType(current, rulesTypeMMILRT); } } finally { ((IDisposable)enumerator).Dispose(); } } public virtual void ParseRulesInType(TypeDefinition type, Type rulesTypeMMILRT = null) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_02b8: Unknown result type (might be due to invalid IL or missing references) //IL_0372: Unknown result type (might be due to invalid IL or missing references) //IL_0377: Unknown result type (might be due to invalid IL or missing references) //IL_025c: Unknown result type (might be due to invalid IL or missing references) //IL_0287: Unknown result type (might be due to invalid IL or missing references) //IL_0431: Unknown result type (might be due to invalid IL or missing references) //IL_0436: Unknown result type (might be due to invalid IL or missing references) Extensions.GetPatchFullName((MemberReference)(object)type); if (!MatchingConditionals((ICustomAttributeProvider)(object)type, Module)) { return; } CustomAttribute customAttribute = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModCustomAttributeAttribute"); CustomAttributeArgument val; if (customAttribute != null) { val = customAttribute.ConstructorArguments[0]; MethodInfo method2 = rulesTypeMMILRT.GetMethod((string)((CustomAttributeArgument)(ref val)).Value); CustomAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args) { method2.Invoke(self, args); }; } customAttribute = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModCustomMethodAttributeAttribute"); if (customAttribute != null) { val = customAttribute.ConstructorArguments[0]; MethodInfo method = rulesTypeMMILRT.GetMethod((string)((CustomAttributeArgument)(ref val)).Value); ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length == 2 && Extensions.IsCompatible(parameters[0].ParameterType, typeof(ILContext))) { CustomMethodAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown ILContext il = new ILContext((MethodDefinition)args[0]); il.Invoke((Manipulator)delegate { method.Invoke(self, new object[2] { il, args[1] }); }); if (il.IsReadOnly) { il.Dispose(); } }; } else { CustomMethodAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args) { method.Invoke(self, args); }; } } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModHook")) { ParseLinkFrom((MemberReference)(object)type, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModLinkFrom")) { ParseLinkFrom((MemberReference)(object)type, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModLinkTo")) { ParseLinkTo((MemberReference)(object)type, val2); } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore")) { return; } Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator(); try { while (enumerator.MoveNext()) { MethodDefinition current = enumerator.Current; if (MatchingConditionals((ICustomAttributeProvider)(object)current, Module)) { for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModHook")) { ParseLinkFrom((MemberReference)(object)current, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModLinkFrom")) { ParseLinkFrom((MemberReference)(object)current, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModLinkTo")) { ParseLinkTo((MemberReference)(object)current, val2); } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModForceCall")) { ForceCallMap[Extensions.GetID((MethodReference)(object)current, (string)null, (string)null, true, false)] = OpCodes.Call; } else if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModForceCallvirt")) { ForceCallMap[Extensions.GetID((MethodReference)(object)current, (string)null, (string)null, true, false)] = OpCodes.Callvirt; } } } } finally { ((IDisposable)enumerator).Dispose(); } Enumerator<FieldDefinition> enumerator2 = type.Fields.GetEnumerator(); try { while (enumerator2.MoveNext()) { FieldDefinition current2 = enumerator2.Current; if (MatchingConditionals((ICustomAttributeProvider)(object)current2, Module)) { for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModHook")) { ParseLinkFrom((MemberReference)(object)current2, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModLinkFrom")) { ParseLinkFrom((MemberReference)(object)current2, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModLinkTo")) { ParseLinkTo((MemberReference)(object)current2, val2); } } } } finally { ((IDisposable)enumerator2).Dispose(); } Enumerator<PropertyDefinition> enumerator3 = type.Properties.GetEnumerator(); try { while (enumerator3.MoveNext()) { PropertyDefinition current3 = enumerator3.Current; if (MatchingConditionals((ICustomAttributeProvider)(object)current3, Module)) { for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModHook")) { ParseLinkFrom((MemberReference)(object)current3, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModLinkFrom")) { ParseLinkFrom((MemberReference)(object)current3, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModLinkTo")) { ParseLinkTo((MemberReference)(object)current3, val2); } } } } finally { ((IDisposable)enumerator3).Dispose(); } Enumerator<TypeDefinition> enumerator4 = type.NestedTypes.GetEnumerator(); try { while (enumerator4.MoveNext()) { TypeDefinition current4 = enumerator4.Current; ParseRulesInType(current4, rulesTypeMMILRT); } } finally { ((IDisposable)enumerator4).Dispose(); } } public virtual void ParseLinkFrom(MemberReference target, CustomAttribute hook) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Expected O, but got Unknown //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) CustomAttributeArgument val = hook.ConstructorArguments[0]; string key = (string)((CustomAttributeArgument)(ref val)).Value; object value; if (target is TypeReference) { value = Extensions.GetPatchFullName((MemberReference)(TypeReference)target); } else if (target is MethodReference) { value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(MethodReference)target).DeclaringType), Extensions.GetID((MethodReference)target, (string)null, (string)null, false, false)); } else if (target is FieldReference) { value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(FieldReference)target).DeclaringType), ((MemberReference)(FieldReference)target).Name); } else { if (!(target is PropertyReference)) { return; } value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(PropertyReference)target).DeclaringType), ((MemberReference)(PropertyReference)target).Name); } RelinkMap[key] = value; } public virtual void ParseLinkTo(MemberReference from, CustomAttribute hook) { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) MemberReference obj = ((from is MethodReference) ? from : null); string key = ((obj != null) ? Extensions.GetID((MethodReference)(object)obj, (string)null, (string)null, true, false) : null) ?? Extensions.GetPatchFullName(from); CustomAttributeArgument val; if (hook.ConstructorArguments.Count == 1) { Dictionary<string, object> relinkMap = RelinkMap; val = hook.ConstructorArguments[0]; relinkMap[key] = (string)((CustomAttributeArgument)(ref val)).Value; } else { Dictionary<string, object> relinkMap2 = RelinkMap; val = hook.ConstructorArguments[0]; string type = (string)((CustomAttributeArgument)(ref val)).Value; val = hook.ConstructorArguments[1]; relinkMap2[key] = new RelinkMapEntry(type, (string)((CustomAttributeArgument)(ref val)).Value); } } public virtual void RunCustomAttributeHandlers(ICustomAttributeProvider cap) { //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Expected O, but got Unknown if (!cap.HasCustomAttributes) { return; } CustomAttribute[] array = cap.CustomAttributes.ToArray(); foreach (CustomAttribute val in array) { if (CustomAttributeHandlers.TryGetValue(((MemberReference)val.AttributeType).FullName, out var value)) { value?.Invoke(null, new object[2] { cap, val }); } if (cap is MethodReference && CustomMethodAttributeHandlers.TryGetValue(((MemberReference)val.AttributeType).FullName, out value)) { value?.Invoke(null, new object[2] { (object)(MethodDefinition)cap, val }); } } } public virtual void AutoPatch() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Expected O, but got Unknown Log("[AutoPatch] Parsing rules in loaded mods"); foreach (ModuleDefinition mod4 in Mods) { ModuleDefinition mod = mod4; ParseRules(mod); } Log("[AutoPatch] PrePatch pass"); foreach (ModuleDefinition mod5 in Mods) { ModuleDefinition mod2 = mod5; PrePatchModule(mod2); } Log("[AutoPatch] Patch pass"); foreach (ModuleDefinition mod6 in Mods) { ModuleDefinition mod3 = mod6; PatchModule(mod3); } Log("[AutoPatch] PatchRefs pass"); PatchRefs(); if (PostProcessors != null) { Delegate[] invocationList = PostProcessors.GetInvocationList(); for (int i = 0; i < invocationList.Length; i++) { Log($"[PostProcessor] PostProcessor pass #{i + 1}"); ((PostProcessor)invocationList[i])?.Invoke(this); } } } public virtual IMetadataTokenProvider Relinker(IMetadataTokenProvider mtp, IGenericParameterProvider context) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) try { return PostRelinker(MainRelinker(mtp, context) ?? mtp, context) ?? throw new RelinkTargetNotFoundException(mtp, (IMetadataTokenProvider)(object)context); } catch (Exception ex) { throw new RelinkFailedException((string)null, ex, mtp, (IMetadataTokenProvider)(object)context); } } public virtual IMetadataTokenProvider MainRelinker(IMetadataTokenProvider mtp, IGenericParameterProvider context) { //IL_0075: Unknown result type (might be due to invalid IL or missing references) TypeReference val = (TypeReference)(object)((mtp is TypeReference) ? mtp : null); if (val != null) { if (((MemberReference)val).Module == Module) { return (IMetadataTokenProvider)(object)val; } if (((MemberReference)val).Module != null && !Mods.Contains((ModuleReference)(object)((MemberReference)val).Module)) { return (IMetadataTokenProvider)(object)Module.ImportReference(val); } val = (TypeReference)(((object)Extensions.SafeResolve(val)) ?? ((object)val)); TypeReference val2 = FindTypeDeep(Extensions.GetPatchFullName((MemberReference)(object)val)); if (val2 == null) { if (RelinkMap.ContainsKey(((MemberReference)val).FullName)) { return null; } throw new RelinkTargetNotFoundException(mtp, (IMetadataTokenProvider)(object)context); } return (IMetadataTokenProvider)(object)Module.ImportReference(val2); } if (mtp is FieldReference || mtp is MethodReference || mtp is PropertyReference || mtp is EventReference) { return Extensions.ImportReference(Module, mtp); } throw new InvalidOperationException($"MonoMod default relinker can't handle metadata token providers of the type {((object)mtp).GetType()}"); } public virtual IMetadataTokenProvider PostRelinker(IMetadataTokenProvider mtp, IGenericParameterProvider context) { return ResolveRelinkTarget(mtp) ?? mtp; } public virtual IMetadataTokenProvider ResolveRelinkTarget(IMetadataTokenProvider mtp, bool relink = true, bool relinkModule = true) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Expected O, but got Unknown //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Expected O, but got Unknown //IL_027b: Unknown result type (might be due to invalid IL or missing references) //IL_0282: Expected O, but got Unknown //IL_022f: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_0237: Expected O, but got Unknown //IL_023c: Expected O, but got Unknown //IL_02d2: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_01a9: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Expected O, but got Unknown //IL_0193: Unknown result type (might be due to invalid IL or missing references) string text = null; string text2; if (mtp is TypeReference) { text2 = ((MemberReference)(TypeReference)mtp).FullName; } else if (mtp is MethodReference) { text2 = Extensions.GetID((MethodReference)mtp, (string)null, (string)null, true, false); text = Extensions.GetID((MethodReference)mtp, (string)null, (string)null, true, true); } else if (mtp is FieldReference) { text2 = ((MemberReference)(FieldReference)mtp).FullName; } else { if (!(mtp is PropertyReference)) { return null; } text2 = ((MemberReference)(PropertyReference)mtp).FullName; } if (RelinkMapCache.TryGetValue(text2, out var value)) { return value; } if (relink && (RelinkMap.TryGetValue(text2, out var value2) || (text != null && RelinkMap.TryGetValue(text, out value2)))) { if (value2 is IMetadataTokenProvider) { return RelinkMapCache[text2] = Extensions.ImportReference(Module, (IMetadataTokenProvider)value2); } if (value2 is RelinkMapEntry) { string type = ((RelinkMapEntry)value2).Type; string findableID = ((RelinkMapEntry)value2).FindableID; TypeReference obj = FindTypeDeep(type); TypeDefinition val2 = ((obj != null) ? Extensions.SafeResolve(obj) : null); if (val2 == null) { return RelinkMapCache[text2] = ResolveRelinkTarget(mtp, relink: false, relinkModule); } value2 = Extensions.FindMethod(val2, findableID, true) ?? ((object)Extensions.FindField(val2, findableID)) ?? ((object)(Extensions.FindProperty(val2, findableID) ?? null)); if (value2 == null) { if (Strict) { throw new RelinkTargetNotFoundException(string.Format("{0} ({1}, {2}) (remap: {3})", "MonoMod relinker failed finding", type, findableID, mtp), mtp, (IMetadataTokenProvider)null); } return null; } return RelinkMapCache[text2] = Extensions.ImportReference(Module, (IMetadataTokenProvider)value2); } if (value2 is string && mtp is TypeReference) { IMetadataTokenProvider val5 = (IMetadataTokenProvider)(object)FindTypeDeep((string)value2); if (val5 == null) { if (Strict) { throw new RelinkTargetNotFoundException(string.Format("{0} {1} (remap: {2})", "MonoMod relinker failed finding", value2, mtp), mtp, (IMetadataTokenProvider)null); } return null; } value2 = Extensions.ImportReference(Module, ResolveRelinkTarget(val5, relink: false, relinkModule) ?? val5); } if (value2 is IMetadataTokenProvider) { Dictionary<string, IMetadataTokenProvider> relinkMapCache = RelinkMapCache; string key = text2; IMetadataTokenProvider val6 = (IMetadataTokenProvider)value2; IMetadataTokenProvider result = val6; relinkMapCache[key] = val6; return result; } throw new InvalidOperationException($"MonoMod doesn't support RelinkMap value of type {value2.GetType()} (remap: {mtp})"); } if (relinkModule && mtp is TypeReference) { if (RelinkModuleMapCache.TryGetValue(text2, out var value3)) { return (IMetadataTokenProvider)(object)value3; } value3 = (TypeReference)mtp; if (RelinkModuleMap.TryGetValue(value3.Scope.Name, out var value4)) { TypeReference type2 = (TypeReference)(object)value4.GetType(((MemberReference)value3).FullName); if (type2 == null) { if (Strict) { throw new RelinkTargetNotFoundException(string.Format("{0} {1} (remap: {2})", "MonoMod relinker failed finding", ((MemberReference)value3).FullName, mtp), mtp, (IMetadataTokenProvider)null); } return null; } return (IMetadataTokenProvider)(object)(RelinkModuleMapCache[text2] = Module.ImportReference(type2)); } return (IMetadataTokenProvider)(object)Module.ImportReference(value3); } return null; } public virtual bool DefaultParser(MonoModder mod, MethodBody body, Instruction instr, ref int instri) { return true; } public virtual TypeReference FindType(string name) { return FindType(Module, name, new Stack<ModuleDefinition>()) ?? Module.GetType(name, false); } public virtual TypeReference FindType(string name, bool runtimeName) { return FindType(Module, name, new Stack<ModuleDefinition>()) ?? Module.GetType(name, runtimeName); } protected virtual TypeReference FindType(ModuleDefinition main, string fullName, Stack<ModuleDefinition> crawled) { TypeReference type; if ((type = main.GetType(fullName, false)) != null) { return type; } if (fullName.StartsWith("<PrivateImplementationDetails>/")) { return null; } if (crawled.Contains(main)) { return null; } crawled.Push(main); foreach (ModuleDefinition item in DependencyMap[main]) { if ((!RemovePatchReferences || !((AssemblyNameReference)item.Assembly.Name).Name.EndsWith(".mm")) && (type = FindType(item, fullName, crawled)) != null) { return type; } } return null; } public virtual TypeReference FindTypeDeep(string name) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown TypeReference val = FindType(name, runtimeName: false); if (val != null) { return val; } Stack<ModuleDefinition> crawled = new Stack<ModuleDefinition>(); val = null; foreach (ModuleDefinition mod in Mods) { ModuleDefinition key = mod; foreach (ModuleDefinition item in DependencyMap[key]) { if ((val = FindType(item, name, crawled)) != null) { IMetadataScope scope = val.Scope; AssemblyNameReference dllRef = (AssemblyNameReference)(object)((scope is AssemblyNameReference) ? scope : null); if (dllRef != null && !((IEnumerable<AssemblyNameReference>)Module.AssemblyReferences).Any((AssemblyNameReference n) => n.Name == dllRef.Name)) { Module.AssemblyReferences.Add(dllRef); } return Module.ImportReference(val); } } } return null; } public virtual void PrePatchModule(ModuleDefinition mod) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Expected O, but got Unknown Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current = enumerator.Current; PrePatchType(current); } } finally { ((IDisposable)enumerator).Dispose(); } Enumerator<ModuleReference> enumerator2 = mod.ModuleReferences.GetEnumerator(); try { while (enumerator2.MoveNext()) { ModuleReference current2 = enumerator2.Current; if (!Module.ModuleReferences.Contains(current2)) { Module.ModuleReferences.Add(current2); } } } finally { ((IDisposable)enumerator2).Dispose(); } Enumerator<Resource> enumerator3 = mod.Resources.GetEnumerator(); try { while (enumerator3.MoveNext()) { Resource current3 = enumerator3.Current; if (current3 is EmbeddedResource) { Module.Resources.Add((Resource)new EmbeddedResource(current3.Name.StartsWith(((AssemblyNameReference)mod.Assembly.Name).Name) ? (((AssemblyNameReference)Module.Assembly.Name).Name + current3.Name.Substring(((AssemblyNameReference)mod.Assembly.Name).Name.Length)) : current3.Name, current3.Attributes, ((EmbeddedResource)current3).GetResourceData())); } } } finally { ((IDisposable)enumerator3).Dispose(); } } public virtual void PrePatchType(TypeDefinition type, bool forceAdd = false) { //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Expected O, but got Unknown //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0161: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01c2: Expected O, but got Unknown //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_0223: Expected O, but got Unknown string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)type); if ((((TypeReference)type).Namespace != "MonoMod" && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore")) || SkipList.Contains(patchFullName) || !MatchingConditionals((ICustomAttributeProvider)(object)type, Module) || (((MemberReference)type).FullName == "MonoMod.MonoModRules" && !forceAdd)) { return; } TypeReference val = (forceAdd ? null : Module.GetType(patchFullName, false)); TypeDefinition val2 = ((val != null) ? Extensions.SafeResolve(val) : null); if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModReplace") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModRemove")) { if (val2 != null) { if (val2.DeclaringType == null) { Module.Types.Remove(val2); } else { val2.DeclaringType.NestedTypes.Remove(val2); } } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModRemove")) { return; } } else if (val != null) { PrePatchNested(type); return; } LogVerbose("[PrePatchType] Adding " + patchFullName + " to the target module."); TypeDefinition val3 = new TypeDefinition(((TypeReference)type).Namespace, ((MemberReference)type).Name, type.Attributes, type.BaseType); Enumerator<GenericParameter> enumerator = ((TypeReference)type).GenericParameters.GetEnumerator(); try { while (enumerator.MoveNext()) { GenericParameter current = enumerator.Current; ((TypeReference)val3).GenericParameters.Add(Extensions.Clone(current)); } } finally { ((IDisposable)enumerator).Dispose(); } Enumerator<InterfaceImplementation> enumerator2 = type.Interfaces.GetEnumerator(); try { while (enumerator2.MoveNext()) { InterfaceImplementation current2 = enumerator2.Current; val3.Interfaces.Add(current2); } } finally { ((IDisposable)enumerator2).Dispose(); } val3.ClassSize = type.ClassSize; if (type.DeclaringType != null) { val3.DeclaringType = Extensions.Relink((TypeReference)(object)type.DeclaringType, new Relinker(Relinker), (IGenericParameterProvider)(object)val3).Resolve(); val3.DeclaringType.NestedTypes.Add(val3); } else { Module.Types.Add(val3); } val3.PackingSize = type.PackingSize; Extensions.AddRange<SecurityDeclaration>(val3.SecurityDeclarations, (IEnumerable<SecurityDeclaration>)type.SecurityDeclarations); val3.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor())); val = (TypeReference)(object)val3; PrePatchNested(type); } protected virtual void PrePatchNested(TypeDefinition type) { for (int i = 0; i < type.NestedTypes.Count; i++) { PrePatchType(type.NestedTypes[i]); } } public virtual void PatchModule(ModuleDefinition mod) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current = enumerator.Current; if ((((TypeReference)current).Namespace == "MonoMod" || ((TypeReference)current).Namespace.StartsWith("MonoMod.")) && ((MemberReference)current.BaseType).FullName == "System.Attribute") { PatchType(current); } } } finally { ((IDisposable)enumerator).Dispose(); } enumerator = mod.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current2 = enumerator.Current; if ((!(((TypeReference)current2).Namespace == "MonoMod") && !((TypeReference)current2).Namespace.StartsWith("MonoMod.")) || !(((MemberReference)current2.BaseType).FullName == "System.Attribute")) { PatchType(current2); } } } finally { ((IDisposable)enumerator).Dispose(); } } public virtual void PatchType(TypeDefinition type) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_020e: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Unknown result type (might be due to invalid IL or missing references) //IL_02b2: Unknown result type (might be due to invalid IL or missing references) //IL_02b7: Unknown result type (might be due to invalid IL or missing references) string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)type); TypeReference type2 = Module.GetType(patchFullName, false); if (type2 == null) { return; } TypeDefinition val = ((type2 != null) ? Extensions.SafeResolve(type2) : null); Enumerator<CustomAttribute> enumerator; if ((((TypeReference)type).Namespace != "MonoMod" && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore")) || SkipList.Contains(patchFullName) || !MatchingConditionals((ICustomAttributeProvider)(object)type, Module)) { if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore") && val != null) { enumerator = type.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName)) { val.CustomAttributes.Add(Extensions.Clone(current)); } } } finally { ((IDisposable)enumerator).Dispose(); } } PatchNested(type); return; } if (patchFullName == ((MemberReference)type).FullName) { LogVerbose("[PatchType] Patching type " + patchFullName); } else { LogVerbose("[PatchType] Patching type " + patchFullName + " (prefixed: " + ((MemberReference)type).FullName + ")"); } enumerator = type.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current2 = enumerator.Current; if (!Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)val, ((MemberReference)current2.AttributeType).FullName)) { val.CustomAttributes.Add(Extensions.Clone(current2)); } } } finally { ((IDisposable)enumerator).Dispose(); } HashSet<MethodDefinition> hashSet = new HashSet<MethodDefinition>(); Enumerator<PropertyDefinition> enumerator2 = type.Properties.GetEnumerator(); try { while (enumerator2.MoveNext()) { PropertyDefinition current3 = enumerator2.Current; PatchProperty(val, current3, hashSet); } } finally { ((IDisposable)enumerator2).Dispose(); } HashSet<MethodDefinition> hashSet2 = new HashSet<MethodDefinition>(); Enumerator<EventDefinition> enumerator3 = type.Events.GetEnumerator(); try { while (enumerator3.MoveNext()) { EventDefinition current4 = enumerator3.Current; PatchEvent(val, current4, hashSet2); } } finally { ((IDisposable)enumerator3).Dispose(); } Enumerator<MethodDefinition> enumerator4 = type.Methods.GetEnumerator(); try { while (enumerator4.MoveNext()) { MethodDefinition current5 = enumerator4.Current; if (!hashSet.Contains(current5) && !hashSet2.Contains(current5)) { PatchMethod(val, current5); } } } finally { ((IDisposable)enumerator4).Dispose(); } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModEnumReplace")) { int num = 0; while (num < val.Fields.Count) { if (((MemberReference)val.Fields[num]).Name == "value__") { num++; } else { val.Fields.RemoveAt(num); } } } Enumerator<FieldDefinition> enumerator5 = type.Fields.GetEnumerator(); try { while (enumerator5.MoveNext()) { FieldDefinition current6 = enumerator5.Current; PatchField(val, current6); } } finally { ((IDisposable)enumerator5).Dispose(); } PatchNested(type); } protected virtual void PatchNested(TypeDefinition type) { for (int i = 0; i < type.NestedTypes.Count; i++) { PatchType(type.NestedTypes[i]); } } public virtual void PatchProperty(TypeDefinition targetType, PropertyDefinition prop, HashSet<MethodDefinition> propMethods = null) { //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_02c8: Unknown result type (might be due to invalid IL or missing references) //IL_02cd: Unknown result type (might be due to invalid IL or missing references) //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Expected O, but got Unknown //IL_022b: Expected O, but got Unknown //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_0242: Expected O, but got Unknown //IL_0248: Unknown result type (might be due to invalid IL or missing references) //IL_024d: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_02a0: Unknown result type (might be due to invalid IL or missing references) //IL_02ab: Unknown result type (might be due to invalid IL or missing references) //IL_02b0: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Expected O, but got Unknown //IL_02b5: Expected O, but got Unknown //IL_0363: Unknown result type (might be due to invalid IL or missing references) //IL_0368: Unknown result type (might be due to invalid IL or missing references) if (!MatchingConditionals((ICustomAttributeProvider)(object)prop, Module)) { return; } ((MemberReference)prop).Name = Extensions.GetPatchName((MemberReference)(object)prop); PropertyDefinition val = Extensions.FindProperty(targetType, ((MemberReference)prop).Name); string text = "<" + ((MemberReference)prop).Name + ">__BackingField"; FieldDefinition val2 = Extensions.FindField(prop.DeclaringType, text); FieldDefinition val3 = Extensions.FindField(targetType, text); Enumerator<CustomAttribute> enumerator; Enumerator<MethodDefinition> enumerator2; if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModIgnore")) { if (val != null) { enumerator = prop.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName)) { val.CustomAttributes.Add(Extensions.Clone(current)); } } } finally { ((IDisposable)enumerator).Dispose(); } } if (val2 != null) { val2.DeclaringType.Fields.Remove(val2); } if (prop.GetMethod != null) { propMethods?.Add(prop.GetMethod); } if (prop.SetMethod != null) { propMethods?.Add(prop.SetMethod); } enumerator2 = prop.OtherMethods.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodDefinition current2 = enumerator2.Current; propMethods?.Add(current2); } return; } finally { ((IDisposable)enumerator2).Dispose(); } } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModReplace")) { if (val != null) { targetType.Properties.Remove(val); if (val3 != null) { targetType.Fields.Remove(val3); } if (val.GetMethod != null) { targetType.Methods.Remove(val.GetMethod); } if (val.SetMethod != null) { targetType.Methods.Remove(val.SetMethod); } enumerator2 = val.OtherMethods.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodDefinition current3 = enumerator2.Current; targetType.Methods.Remove(current3); } } finally { ((IDisposable)enumerator2).Dispose(); } } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModRemove")) { return; } } if (val == null) { PropertyDefinition val4 = new PropertyDefinition(((MemberReference)prop).Name, prop.Attributes, ((PropertyReference)prop).PropertyType); val = val4; PropertyDefinition val5 = val4; val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor())); Enumerator<ParameterDefinition> enumerator3 = ((PropertyReference)prop).Parameters.GetEnumerator(); try { while (enumerator3.MoveNext()) { ParameterDefinition current4 = enumerator3.Current; ((PropertyReference)val5).Parameters.Add(Extensions.Clone(current4)); } } finally { ((IDisposable)enumerator3).Dispose(); } val5.DeclaringType = targetType; targetType.Properties.Add(val5); if (val2 != null) { FieldDefinition val6 = new FieldDefinition(text, val2.Attributes, ((FieldReference)val2).FieldType); val3 = val6; FieldDefinition val7 = val6; targetType.Fields.Add(val7); } } enumerator = prop.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current5 = enumerator.Current; val.CustomAttributes.Add(Extensions.Clone(current5)); } } finally { ((IDisposable)enumerator).Dispose(); } MethodDefinition getMethod = prop.GetMethod; MethodDefinition getMethod2; if (getMethod != null && (getMethod2 = PatchMethod(targetType, getMethod)) != null) { val.GetMethod = getMethod2; propMethods?.Add(getMethod); } MethodDefinition setMethod = prop.SetMethod; if (setMethod != null && (getMethod2 = PatchMethod(targetType, setMethod)) != null) { val.SetMethod = getMethod2; propMethods?.Add(setMethod); } enumerator2 = prop.OtherMethods.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodDefinition current6 = enumerator2.Current; if ((getMethod2 = PatchMethod(targetType, current6)) != null) { val.OtherMethods.Add(getMethod2); propMethods?.Add(current6); } } } finally { ((IDisposable)enumerator2).Dispose(); } } public virtual void PatchEvent(TypeDefinition targetType, EventDefinition srcEvent, HashSet<MethodDefinition> propMethods = null) { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_02a8: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) //IL_023e: Unknown result type (might be due to invalid IL or missing references) //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Expected O, but got Unknown //IL_0252: Expected O, but got Unknown //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_0269: Expected O, but got Unknown //IL_0283: Unknown result type (might be due to invalid IL or missing references) //IL_028e: Unknown result type (might be due to invalid IL or missing references) //IL_0295: Expected O, but got Unknown //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_036f: Unknown result type (might be due to invalid IL or missing references) //IL_0374: Unknown result type (might be due to invalid IL or missing references) ((MemberReference)srcEvent).Name = Extensions.GetPatchName((MemberReference)(object)srcEvent); EventDefinition val = Extensions.FindEvent(targetType, ((MemberReference)srcEvent).Name); string text = "<" + ((MemberReference)srcEvent).Name + ">__BackingField"; FieldDefinition val2 = Extensions.FindField(srcEvent.DeclaringType, text); FieldDefinition val3 = Extensions.FindField(targetType, text); Enumerator<CustomAttribute> enumerator; Enumerator<MethodDefinition> enumerator2; if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModIgnore")) { if (val != null) { enumerator = srcEvent.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName)) { val.CustomAttributes.Add(Extensions.Clone(current)); } } } finally { ((IDisposable)enumerator).Dispose(); } } if (val2 != null) { val2.DeclaringType.Fields.Remove(val2); } if (srcEvent.AddMethod != null) { propMethods?.Add(srcEvent.AddMethod); } if (srcEvent.RemoveMethod != null) { propMethods?.Add(srcEvent.RemoveMethod); } if (srcEvent.InvokeMethod != null) { propMethods?.Add(srcEvent.InvokeMethod); } enumerator2 = srcEvent.OtherMethods.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodDefinition current2 = enumerator2.Current; propMethods?.Add(current2); } return; } finally { ((IDisposable)enumerator2).Dispose(); } } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModReplace")) { if (val != null) { targetType.Events.Remove(val); if (val3 != null) { targetType.Fields.Remove(val3); } if (val.AddMethod != null) { targetType.Methods.Remove(val.AddMethod); } if (val.RemoveMethod != null) { targetType.Methods.Remove(val.RemoveMethod); } if (val.InvokeMethod != null) { targetType.Methods.Remove(val.InvokeMethod); } if (val.OtherMethods != null) { enumerator2 = val.OtherMethods.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodDefinition current3 = enumerator2.Current; targetType.Methods.Remove(current3); } } finally { ((IDisposable)enumerator2).Dispose(); } } } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModRemove")) { return; } } if (val == null) { EventDefinition val4 = new EventDefinition(((MemberReference)srcEvent).Name, srcEvent.Attributes, ((EventReference)srcEvent).EventType); val = val4; EventDefinition val5 = val4; val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor())); val5.DeclaringType = targetType; targetType.Events.Add(val5); if (val2 != null) { FieldDefinition val6 = new FieldDefinition(text, val2.Attributes, ((FieldReference)val2).FieldType); targetType.Fields.Add(val6); } } enumerator = srcEvent.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current4 = enumerator.Current; val.CustomAttributes.Add(Extensions.Clone(current4)); } } finally { ((IDisposable)enumerator).Dispose(); } MethodDefinition addMethod = srcEvent.AddMethod; MethodDefinition addMethod2; if (addMethod != null && (addMethod2 = PatchMethod(targetType, addMethod)) != null) { val.AddMethod = addMethod2; propMethods?.Add(addMethod); } MethodDefinition removeMethod = srcEvent.RemoveMethod; if (removeMethod != null && (addMethod2 = PatchMethod(targetType, removeMethod)) != null) { val.RemoveMethod = addMethod2; propMethods?.Add(removeMethod); } MethodDefinition invokeMethod = srcEvent.InvokeMethod; if (invokeMethod != null && (addMethod2 = PatchMethod(targetType, invokeMethod)) != null) { val.InvokeMethod = addMethod2; propMethods?.Add(invokeMethod); } enumerator2 = srcEvent.OtherMethods.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodDefinition current5 = enumerator2.Current; if ((addMethod2 = PatchMethod(targetType, current5)) != null) { val.OtherMethods.Add(addMethod2); propMethods?.Add(current5); } } } finally { ((IDisposable)enumerator2).Dispose(); } } public virtual void PatchField(TypeDefinition targetType, FieldDefinition field) { //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Expected O, but got Unknown //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Expected O, but got Unknown //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)field.DeclaringType); if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModNoNew") || SkipList.Contains(patchFullName + "::" + ((MemberReference)field).Name) || !MatchingConditionals((ICustomAttributeProvider)(object)field, Module)) { return; } ((MemberReference)field).Name = Extensions.GetPatchName((MemberReference)(object)field); if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModReplace")) { FieldDefinition val = Extensions.FindField(targetType, ((MemberReference)field).Name); if (val != null) { targetType.Fields.Remove(val); } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModRemove")) { return; } } FieldDefinition val2 = Extensions.FindField(targetType, ((MemberReference)field).Name); Enumerator<CustomAttribute> enumerator; if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModIgnore") && val2 != null) { enumerator = field.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName)) { val2.CustomAttributes.Add(Extensions.Clone(current)); } } return; } finally { ((IDisposable)enumerator).Dispose(); } } if (val2 == null) { val2 = new FieldDefinition(((MemberReference)field).Name, field.Attributes, ((FieldReference)field).FieldType); val2.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor())); val2.InitialValue = field.InitialValue; if (field.HasConstant) { val2.Constant = field.Constant; } targetType.Fields.Add(val2); } enumerator = field.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current2 = enumerator.Current; val2.CustomAttributes.Add(Extensions.Clone(current2)); } } finally { ((IDisposable)enumerator).Dispose(); } } public virtual MethodDefinition PatchMethod(TypeDefinition targetType, MethodDefinition method) { //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Expected O, but got Unknown //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_0202: Unknown result type (might be due to invalid IL or missing references) //IL_021a: Unknown result type (might be due to invalid IL or missing references) //IL_024b: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Unknown result type (might be due to invalid IL or missing references) //IL_025b: Unknown result type (might be due to invalid IL or missing references) //IL_0268: Unknown result type (might be due to invalid IL or missing references) //IL_028a: Unknown result type (might be due to invalid IL or missing references) //IL_028f: Unknown result type (might be due to invalid IL or missing references) //IL_049f: Unknown result type (might be due to invalid IL or missing references) //IL_04b4: Unknown result type (might be due to invalid IL or missing references) //IL_04bb: Expected O, but got Unknown //IL_04c3: Unknown result type (might be due to invalid IL or missing references) //IL_04d0: Unknown result type (might be due to invalid IL or missing references) //IL_04f7: Unknown result type (might be due to invalid IL or missing references) //IL_0504: Unknown result type (might be due to invalid IL or missing references) //IL_0511: Unknown result type (might be due to invalid IL or missing references) //IL_0564: Unknown result type (might be due to invalid IL or missing references) //IL_0569: Unknown result type (might be due to invalid IL or missing references) //IL_0453: Unknown result type (might be due to invalid IL or missing references) //IL_0458: Unknown result type (might be due to invalid IL or missing references) //IL_03d1: Unknown result type (might be due to invalid IL or missing references) //IL_02ce: Unknown result type (might be due to invalid IL or missing references) //IL_02d8: Expected O, but got Unknown //IL_05a8: Unknown result type (might be due to invalid IL or missing references) //IL_05ad: Unknown result type (might be due to invalid IL or missing references) //IL_0300: Unknown result type (might be due to invalid IL or missing references) //IL_0305: Unknown result type (might be due to invalid IL or missing references) //IL_069a: Unknown result type (might be due to invalid IL or missing references) //IL_06a1: Expected O, but got Unknown //IL_06be: Unknown result type (might be due to invalid IL or missing references) //IL_05ec: Unknown result type (might be due to invalid IL or missing references) //IL_05f1: Unknown result type (might be due to invalid IL or missing references) //IL_0630: Unknown result type (might be due to invalid IL or missing references) //IL_0635: Unknown result type (might be due to invalid IL or missing references) //IL_0676: Unknown result type (might be due to invalid IL or missing references) //IL_0680: Expected O, but got Unknown if (((MemberReference)method).Name.StartsWith("orig_") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModOriginal")) { return null; } if (!AllowedSpecialName(method, targetType) || !MatchingConditionals((ICustomAttributeProvider)(object)method, Module)) { return null; } string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)targetType); if (SkipList.Contains(Extensions.GetID((MethodReference)(object)method, (string)null, patchFullName, true, false))) { return null; } ((MemberReference)method).Name = Extensions.GetPatchName((MemberReference)(object)method); if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModConstructor")) { if (!method.IsSpecialName && !Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModOriginalName")) { CustomAttribute val = new CustomAttribute(GetMonoModOriginalNameCtor()); val.ConstructorArguments.Add(new CustomAttributeArgument(Module.TypeSystem.String, (object)("orig_" + ((MemberReference)method).Name))); method.CustomAttributes.Add(val); } ((MemberReference)method).Name = (method.IsStatic ? ".cctor" : ".ctor"); method.IsSpecialName = true; method.IsRuntimeSpecialName = true; } MethodDefinition val2 = Extensions.FindMethod(targetType, Extensions.GetID((MethodReference)(object)method, (string)null, patchFullName, true, false), true); MethodDefinition obj = method; string text = patchFullName; MethodDefinition val3 = Extensions.FindMethod(targetType, Extensions.GetID((MethodReference)(object)obj, method.GetOriginalName(), text, true, false), true); if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModIgnore")) { if (val2 != null) { Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName) || CustomMethodAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName)) { val2.CustomAttributes.Add(Extensions.Clone(current)); } } } finally { ((IDisposable)enumerator).Dispose(); } } return null; } if (val2 == null && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModNoNew")) { return null; } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModRemove")) { if (val2 != null) { targetType.Methods.Remove(val2); } return null; } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModReplace")) { if (val2 != null) { val2.CustomAttributes.Clear(); val2.Attributes = method.Attributes; val2.IsPInvokeImpl = method.IsPInvokeImpl; val2.ImplAttributes = method.ImplAttributes; } } else if (val2 != null && val3 == null) { val3 = Extensions.Clone(val2, (MethodDefinition)null); ((MemberReference)val3).Name = method.GetOriginalName(); val3.Attributes = (MethodAttributes)(val2.Attributes & 0xF7FF & 0xEFFF); ((MemberReference)val3).MetadataToken = GetMetadataToken((TokenType)100663296); val3.IsVirtual = false; val3.Overrides.Clear(); Enumerator<MethodReference> enumerator2 = method.Overrides.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodReference current2 = enumerator2.Current; val3.Overrides.Add(current2); } } finally { ((IDisposable)enumerator2).Dispose(); } val3.CustomAttributes.Add(new CustomAttribute(GetMonoModOriginalCtor())); MethodDefinition val4 = Extensions.FindMethod(method.DeclaringType, Extensions.GetID((MethodReference)(object)method, method.GetOriginalName(), (string)null, true, false), true); if (val4 != null) { Enumerator<CustomAttribute> enumerator = val4.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current3 = enumerator.Current; if (CustomAttributeHandlers.ContainsKey(((MemberReference)current3.AttributeType).FullName) || CustomMethodAttributeHandlers.ContainsKey(((MemberReference)current3.AttributeType).FullName)) { val3.CustomAttributes.Add(Extensions.Clone(current3)); } } } finally { ((IDisposable)enumerator).Dispose(); } } targetType.Methods.Add(val3); } if (val3 != null && method.IsConstructor && method.IsStatic && method.HasBody && !Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModConstructor")) { Collection<Instruction> instructions = method.Body.Instructions; ILProcessor iLProcessor = method.Body.GetILProcessor(); iLProcessor.InsertBefore(instructions[instructions.Count - 1], iLProcessor.Create(OpCodes.Call, (MethodReference)(object)val3)); } if (val2 != null) { val2.Body = Extensions.Clone(method.Body, val2); val2.IsManaged = method.IsManaged; val2.IsIL = method.IsIL; val2.IsNative = method.IsNative; val2.PInvokeInfo = method.PInvokeInfo; val2.IsPreserveSig = method.IsPreserveSig; val2.IsInternalCall = method.IsInternalCall; val2.IsPInvokeImpl = method.IsPInvokeImpl; Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current4 = enumerator.Current; val2.CustomAttributes.Add(Extensions.Clone(current4)); } } finally { ((IDisposable)enumerator).Dispose(); } method = val2; } else { MethodDefinition val5 = new MethodDefinition(((MemberReference)method).Name, method.Attributes, Module.TypeSystem.Void); ((MemberReference)val5).MetadataToken = GetMetadataToken((TokenType)100663296); ((MethodReference)val5).CallingConvention = ((MethodReference)method).CallingConvention; ((MethodReference)val5).ExplicitThis = ((MethodReference)method).ExplicitThis; ((MethodReference)val5).MethodReturnType = ((MethodReference)method).MethodReturnType; val5.Attributes = method.Attributes; val5.ImplAttributes = method.ImplAttributes; val5.SemanticsAttributes = method.SemanticsAttributes; val5.DeclaringType = targetType; ((MethodReference)val5).ReturnType = ((MethodReference)method).ReturnType; val5.Body = Extensions.Clone(method.Body, val5); val5.PInvokeInfo = method.PInvokeInfo; val5.IsPInvokeImpl = method.IsPInvokeImpl; Enumerator<GenericParameter> enumerator3 = ((MethodReference)method).GenericParameters.GetEnumerator(); try { while (enumerator3.MoveNext()) { GenericParameter current5 = enumerator3.Current; ((MethodReference)val5).GenericParameters.Add(Extensions.Clone(current5)); } } finally { ((IDisposable)enumerator3).Dispose(); } Enumerator<ParameterDefinition> enumerator4 = ((MethodReference)method).Parameters.GetEnumerator(); try { while (enumerator4.MoveNext()) { ParameterDefinition current6 = enumerator4.Current; ((MethodReference)val5).Parameters.Add(Extensions.Clone(current6)); } } finally { ((IDisposable)enumerator4).Dispose(); } Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current7 = enumerator.Current; val5.CustomAttributes.Add(Extensions.Clone(current7)); } } finally { ((IDisposable)enumerator).Dispose(); } Enumerator<MethodReference> enumerator2 = method.Overrides.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodReference current8 = enumerator2.Current; val5.Overrides.Add(current8); } } finally { ((IDisposable)enumerator2).Dispose(); } val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor())); targetType.Methods.Add(val5); method = val5; } if (val3 != null) { CustomAttribute val6 = new CustomAttribute(GetMonoModOriginalNameCtor()); val6.ConstructorArguments.Add(new CustomAttributeArgument(Module.TypeSystem.String, (object)((MemberReference)val3).Name)); method.CustomAttributes.Add(val6); } return method; } public virtual void PatchRefs() { //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) if (!UpgradeMSCORLIB.HasValue) { Version fckUnity = new Version(2, 0, 5, 0); UpgradeMSCORLIB = ((IEnumerable<AssemblyNameReference>)Module.AssemblyReferences).Any((AssemblyNameReference x) => x.Version == fckUnity); } if (UpgradeMSCORLIB.Value) { List<AssemblyNameReference> list = new List<AssemblyNameReference>(); for (int i = 0; i < Module.AssemblyReferences.Count; i++) { AssemblyNameReference val = Module.AssemblyReferences[i]; if (val.Name == "mscorlib") { list.Add(val); } } if (list.Count > 1) { AssemblyNameReference val2 = list.OrderByDescending((AssemblyNameReference x) => x.Version).First(); if (DependencyCache.TryGetValue(val2.FullName, out var value)) { for (int j = 0; j < Module.AssemblyReferences.Count; j++) { AssemblyNameReference val3 = Module.AssemblyReferences[j]; if (val3.Name == "mscorlib" && val2.Version > val3.Version) { LogVerbose("[PatchRefs] Removing and relinking duplicate mscorlib: " + val3.Version); RelinkModuleMap[val3.FullName] = value; Module.AssemblyReferences.RemoveAt(j); j--; } } } } } Enumerator<TypeDefinition> enumerator = Module.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current = enumerator.Current; PatchRefsInType(current); } } finally { ((IDisposable)enumerator).Dispose(); } } public virtual void PatchRefs(ModuleDefinition mod) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current = enumerator.Current; PatchRefsInType(current); } } finally { ((IDisposable)enumerator).Dispose(); } } public virtual void PatchRefsInType(TypeDefinition type) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Expected O, but got Unknown //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Expected O, but got Unknown //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Expected O, but got Unknown //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Expected O, but got Unknown //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01cb: Expected O, but got Unknown //IL_0228: Unknown result type (might be due to invalid IL or missing references) //IL_0233: Expected O, but got Unknown //IL_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_02a6: Unknown result type (might be due to invalid IL or missing references) //IL_025c: Unknown result type (might be due to invalid IL or missing references) //IL_0267: Expected O, but got Unknown //IL_02da: Unknown result type (might be due to invalid IL or missing references) //IL_02df: Unknown result type (might be due to invalid IL or missing references) //IL_02fd: Unknown result type (might be due to invalid IL or missing references) //IL_0308: Expected O, but got Unknown //IL_0331: Unknown result type (might be due to invalid IL or missing references) //IL_033c: Expected O, but got Unknown LogVerbose($"[VERBOSE] [PatchRefsInType] Patching refs in {type}"); if (type.BaseType != null) { type.BaseType = Extensions.Relink(type.BaseType, new Relinker(Relinker), (IGenericParameterProvider)(object)type); } for (int i = 0; i < ((TypeReference)type).GenericParameters.Count; i++) { ((TypeReference)type).GenericParameters[i] = Extensions.Relink(((TypeReference)type).GenericParameters[i], new Relinker(Relinker), (IGenericParameterProvider)(object)type); } for (int j = 0; j < type.Interfaces.Count; j++) { InterfaceImplementation obj = type.Interfaces[j]; InterfaceImplementation val = new InterfaceImplementation(Extensions.Relink(obj.InterfaceType, new Relinker(Relinker), (IGenericParameterProvider)(object)type)); Enumerator<CustomAttribute> enumerator = obj.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; val.CustomAttributes.Add(Extensions.Relink(current, new Relinker(Relinker), (IGenericParameterProvider)(object)type)); } } finally { ((IDisposable)enumerator).Dispose(); } type.Interfaces[j] = val; } for (int k = 0; k < type.CustomAttributes.Count; k++) { type.CustomAttributes[k] = Extensions.Relink(type.CustomAttributes[k], new Relinker(Relinker), (IGenericParameterProvider)(object)type); } Enumerator<PropertyDefinition> enumerator2 = type.Properties.GetEnumerator(); try { while (enumerator2.MoveNext()) { PropertyDefinition current2 = enumerator2.Current; ((PropertyReference)current2).PropertyType = Extensions.Relink(((PropertyReference)current2).PropertyType, new Relinker(Relinker), (IGenericParameterProvider)(object)type); for (int l = 0; l < current2.CustomAttributes.Count; l++) { current2.CustomAttributes[l] = Extensions.Relink(current2.CustomAttributes[l], new Relinker(Relinker), (IGenericParameterProvider)(object)type); } } } finally { ((IDisposable)enumerator2).Dispose(); } Enumerator<EventDefinition> enumerator3 = type.Events.GetEnumerator(); try { while (enumerator3.MoveNext()) { EventDefinition current3 = enumerator3.Current; ((EventReference)current3).EventType = Extensions.Relink(((EventReference)current3).EventType, new Relinker(Relinker), (IGenericParameterProvider)(object)type); for (int m = 0; m < current3.CustomAttributes.Count; m++) { current3.CustomAttributes[m] = Extensions.Relink(current3.CustomAttributes[m], new Relinker(Relinker), (IGenericParameterProvider)(object)type); } } } finally { ((IDisposable)enumerator3).Dispose(); } Enumerator<MethodDefinition> enumerator4 = type.Methods.GetEnumerator(); try { while (enumerator4.MoveNext()) { MethodDefinition current4 = enumerator4.Current; PatchRefsInMethod(current4); } } finally { ((IDisposable)enumerator4).Dispose(); } Enumerator<FieldDefinition> enumerator5 = type.Fields.GetEnumerator(); try { while (enumerator5.MoveNext()) { FieldDefinition current5 = enumerator5.Current; ((FieldReference)current5).FieldType = Extensions.Relink(((FieldReference)current5).FieldType, new Relinker(Relinker), (IGenericParameterProvider)(object)type); for (int n = 0; n < current5.CustomAttributes.Count; n++) { current5.CustomAttributes[n] = Extensions.Relink(current5.CustomAttributes[n], new Relinker(Relinker), (IGenericParameterProvider)(object)type); } } } finally { ((IDisposable)enumerator5).Dispose(); } for (int num = 0; num < type.NestedTypes.Count; num++) { PatchRefsInType(type.NestedTypes[num]); } } public virtual void PatchRefsInMethod(MethodDefinition method) { //IL_0030: Unknown result t
BepInEx/core/MonoMod.RuntimeDetour.HookGen.dll
Decompiled 6 months agousing System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; using MonoMod.Utils; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("0x0ade")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2021 0x0ade")] [assembly: AssemblyDescription("Auto-generate hook helper .dlls, hook arbitrary methods via events: On.Namespace.Type.Method += YourHandlerHere;")] [assembly: AssemblyFileVersion("21.8.5.1")] [assembly: AssemblyInformationalVersion("21.08.05.01")] [assembly: AssemblyProduct("MonoMod.RuntimeDetour.HookGen")] [assembly: AssemblyTitle("MonoMod.RuntimeDetour.HookGen")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("21.8.5.1")] [module: UnverifiableCode] internal static class MultiTargetShims { private static readonly object[] _NoArgs = new object[0]; public static TypeReference GetConstraintType(this TypeReference type) { return type; } } namespace MonoMod { internal static class MMDbgLog { public static readonly string Tag; public static TextWriter Writer; public static bool Debugging; static MMDbgLog() { Tag = typeof(MMDbgLog).Assembly.GetName().Name; if (Environment.GetEnvironmentVariable("MONOMOD_DBGLOG") == "1" || (Environment.GetEnvironmentVariable("MONOMOD_DBGLOG")?.ToLowerInvariant()?.Contains(Tag.ToLowerInvariant())).GetValueOrDefault()) { Start(); } } public static void WaitForDebugger() { if (!Debugging) { Debugging = true; Debugger.Launch(); Thread.Sleep(6000); Debugger.Break(); } } public static void Start() { if (Writer != null) { return; } string text = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG_PATH"); if (text == "-") { Writer = Console.Out; return; } if (string.IsNullOrEmpty(text)) { text = "mmdbglog.txt"; } text = Path.GetFullPath(Path.GetFileNameWithoutExtension(text) + "-" + Tag + Path.GetExtension(text)); try { if (File.Exists(text)) { File.Delete(text); } } catch { } try { string directoryName = Path.GetDirectoryName(text); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } Writer = new StreamWriter(new FileStream(text, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), Encoding.UTF8); } catch { } } public static void Log(string str) { TextWriter writer = Writer; if (writer != null) { writer.WriteLine(str); writer.Flush(); } } public static T Log<T>(string str, T value) { TextWriter writer = Writer; if (writer == null) { return value; } writer.WriteLine(string.Format(str, value)); writer.Flush(); return value; } } } namespace MonoMod.RuntimeDetour.HookGen { public class HookGenerator { private const string ObsoleteMessageBackCompat = "This method only exists for backwards-compatibility purposes."; private static readonly Regex NameVerifyRegex; private static readonly Dictionary<Type, string> ReflTypeNameMap; private static readonly Dictionary<string, string> TypeNameMap; public MonoModder Modder; public ModuleDefinition OutputModule; public string Namespace; public string NamespaceIL; public bool HookOrig; public bool HookPrivate; public string HookExtName; public ModuleDefinition module_RuntimeDetour; public ModuleDefinition module_Utils; public TypeReference t_MulticastDelegate; public TypeReference t_IAsyncResult; public TypeReference t_AsyncCallback; public TypeReference t_MethodBase; public TypeReference t_RuntimeMethodHandle; public TypeReference t_EditorBrowsableState; public MethodReference m_Object_ctor; public MethodReference m_ObsoleteAttribute_ctor; public MethodReference m_EditorBrowsableAttribute_ctor; public MethodReference m_GetMethodFromHandle; public MethodReference m_Add; public MethodReference m_Remove; public MethodReference m_Modify; public MethodReference m_Unmodify; public TypeReference t_ILManipulator; static HookGenerator() { NameVerifyRegex = new Regex("[^a-zA-Z]"); ReflTypeNameMap = new Dictionary<Type, string> { { typeof(string), "string" }, { typeof(object), "object" }, { typeof(bool), "bool" }, { typeof(byte), "byte" }, { typeof(char), "char" }, { typeof(decimal), "decimal" }, { typeof(double), "double" }, { typeof(short), "short" }, { typeof(int), "int" }, { typeof(long), "long" }, { typeof(sbyte), "sbyte" }, { typeof(float), "float" }, { typeof(ushort), "ushort" }, { typeof(uint), "uint" }, { typeof(ulong), "ulong" }, { typeof(void), "void" } }; TypeNameMap = new Dictionary<string, string>(); foreach (KeyValuePair<Type, string> item in ReflTypeNameMap) { TypeNameMap[item.Key.FullName] = item.Value; } } public HookGenerator(MonoModder modder, string name) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown //IL_0306: Unknown result type (might be due to invalid IL or missing references) //IL_030b: Unknown result type (might be due to invalid IL or missing references) //IL_0317: Unknown result type (might be due to invalid IL or missing references) //IL_0321: Expected O, but got Unknown //IL_0326: Expected O, but got Unknown Modder = modder; OutputModule = ModuleDefinition.CreateModule(name, new ModuleParameters { Architecture = modder.Module.Architecture, AssemblyResolver = modder.Module.AssemblyResolver, Kind = (ModuleKind)0, Runtime = modder.Module.Runtime }); modder.MapDependencies(); Extensions.AddRange<AssemblyNameReference>(OutputModule.AssemblyReferences, (IEnumerable<AssemblyNameReference>)modder.Module.AssemblyReferences); modder.DependencyMap[OutputModule] = new List<ModuleDefinition>(modder.DependencyMap[modder.Module]); Namespace = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE"); if (string.IsNullOrEmpty(Namespace)) { Namespace = "On"; } NamespaceIL = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE_IL"); if (string.IsNullOrEmpty(NamespaceIL)) { NamespaceIL = "IL"; } HookOrig = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_ORIG") == "1"; HookPrivate = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE") == "1"; modder.MapDependency(modder.Module, "MonoMod.RuntimeDetour", (string)null, (AssemblyNameReference)null); if (!modder.DependencyCache.TryGetValue("MonoMod.RuntimeDetour", out module_RuntimeDetour)) { throw new FileNotFoundException("MonoMod.RuntimeDetour not found!"); } modder.MapDependency(modder.Module, "MonoMod.Utils", (string)null, (AssemblyNameReference)null); if (!modder.DependencyCache.TryGetValue("MonoMod.Utils", out module_Utils)) { throw new FileNotFoundException("MonoMod.Utils not found!"); } t_MulticastDelegate = OutputModule.ImportReference(modder.FindType("System.MulticastDelegate")); t_IAsyncResult = OutputModule.ImportReference(modder.FindType("System.IAsyncResult")); t_AsyncCallback = OutputModule.ImportReference(modder.FindType("System.AsyncCallback")); t_MethodBase = OutputModule.ImportReference(modder.FindType("System.Reflection.MethodBase")); t_RuntimeMethodHandle = OutputModule.ImportReference(modder.FindType("System.RuntimeMethodHandle")); t_EditorBrowsableState = OutputModule.ImportReference(modder.FindType("System.ComponentModel.EditorBrowsableState")); TypeDefinition type = module_RuntimeDetour.GetType("MonoMod.RuntimeDetour.HookGen.HookEndpointManager"); t_ILManipulator = OutputModule.ImportReference((TypeReference)(object)module_Utils.GetType("MonoMod.Cil.ILContext/Manipulator")); m_Object_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.Object").Resolve(), "System.Void .ctor()", true)); m_ObsoleteAttribute_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.ObsoleteAttribute").Resolve(), "System.Void .ctor(System.String,System.Boolean)", true)); m_EditorBrowsableAttribute_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.ComponentModel.EditorBrowsableAttribute").Resolve(), "System.Void .ctor(System.ComponentModel.EditorBrowsableState)", true)); ModuleDefinition outputModule = OutputModule; MethodReference val = new MethodReference("GetMethodFromHandle", t_MethodBase, t_MethodBase); val.Parameters.Add(new ParameterDefinition(t_RuntimeMethodHandle)); m_GetMethodFromHandle = outputModule.ImportReference(val); m_Add = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Add", true)); m_Remove = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Remove", true)); m_Modify = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Modify", true)); m_Unmodify = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Unmodify", true)); } public void Generate() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) Enumerator<TypeDefinition> enumerator = Modder.Module.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current = enumerator.Current; GenerateFor(current, out var hookType, out var hookILType); if (hookType != null && hookILType != null && !((TypeReference)hookType).IsNested) { OutputModule.Types.Add(hookType); OutputModule.Types.Add(hookILType); } } } finally { ((IDisposable)enumerator).Dispose(); } } public void GenerateFor(TypeDefinition type, out TypeDefinition hookType, out TypeDefinition hookILType) { //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Expected O, but got Unknown //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Expected O, but got Unknown //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) hookType = (hookILType = null); if (((TypeReference)type).HasGenericParameters || type.IsRuntimeSpecialName || ((MemberReference)type).Name.StartsWith("<") || (!HookPrivate && type.IsNotPublic)) { return; } Modder.LogVerbose("[HookGen] Generating for type " + ((MemberReference)type).FullName); hookType = new TypeDefinition(((TypeReference)type).IsNested ? null : (Namespace + (string.IsNullOrEmpty(((TypeReference)type).Namespace) ? "" : ("." + ((TypeReference)type).Namespace))), ((MemberReference)type).Name, (TypeAttributes)(((!((TypeReference)type).IsNested) ? 1 : 2) | 0x80 | 0x100 | 0), OutputModule.TypeSystem.Object); hookILType = new TypeDefinition(((TypeReference)type).IsNested ? null : (NamespaceIL + (string.IsNullOrEmpty(((TypeReference)type).Namespace) ? "" : ("." + ((TypeReference)type).Namespace))), ((MemberReference)type).Name, (TypeAttributes)(((!((TypeReference)type).IsNested) ? 1 : 2) | 0x80 | 0x100 | 0), OutputModule.TypeSystem.Object); bool flag = false; Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator(); try { while (enumerator.MoveNext()) { MethodDefinition current = enumerator.Current; flag |= GenerateFor(hookType, hookILType, current); } } finally { ((IDisposable)enumerator).Dispose(); } Enumerator<TypeDefinition> enumerator2 = type.NestedTypes.GetEnumerator(); try { while (enumerator2.MoveNext()) { TypeDefinition current2 = enumerator2.Current; GenerateFor(current2, out var hookType2, out var hookILType2); if (hookType2 != null && hookILType2 != null) { flag = true; hookType.NestedTypes.Add(hookType2); hookILType.NestedTypes.Add(hookILType2); } } } finally { ((IDisposable)enumerator2).Dispose(); } if (!flag) { hookType = (hookILType = null); } } public bool GenerateFor(TypeDefinition hookType, TypeDefinition hookILType, MethodDefinition method) { //IL_02fa: Unknown result type (might be due to invalid IL or missing references) //IL_0304: Expected O, but got Unknown //IL_031e: Unknown result type (might be due to invalid IL or missing references) //IL_0328: Expected O, but got Unknown //IL_0380: Unknown result type (might be due to invalid IL or missing references) //IL_0387: Expected O, but got Unknown //IL_0392: Unknown result type (might be due to invalid IL or missing references) //IL_039c: Expected O, but got Unknown //IL_03a0: Unknown result type (might be due to invalid IL or missing references) //IL_03aa: Expected O, but got Unknown //IL_03b7: Unknown result type (might be due to invalid IL or missing references) //IL_03c4: Unknown result type (might be due to invalid IL or missing references) //IL_03d5: Unknown result type (might be due to invalid IL or missing references) //IL_03e5: Unknown result type (might be due to invalid IL or missing references) //IL_03ec: Expected O, but got Unknown //IL_03fb: Unknown result type (might be due to invalid IL or missing references) //IL_0407: Unknown result type (might be due to invalid IL or missing references) //IL_0443: Unknown result type (might be due to invalid IL or missing references) //IL_044a: Expected O, but got Unknown //IL_0455: Unknown result type (might be due to invalid IL or missing references) //IL_045f: Expected O, but got Unknown //IL_0463: Unknown result type (might be due to invalid IL or missing references) //IL_046d: Expected O, but got Unknown //IL_047a: Unknown result type (might be due to invalid IL or missing references) //IL_0487: Unknown result type (might be due to invalid IL or missing references) //IL_0498: Unknown result type (might be due to invalid IL or missing references) //IL_04a8: Unknown result type (might be due to invalid IL or missing references) //IL_04af: Expected O, but got Unknown //IL_04be: Unknown result type (might be due to invalid IL or missing references) //IL_04ca: Unknown result type (might be due to invalid IL or missing references) //IL_04ea: Unknown result type (might be due to invalid IL or missing references) //IL_04ef: Unknown result type (might be due to invalid IL or missing references) //IL_04f7: Unknown result type (might be due to invalid IL or missing references) //IL_0501: Expected O, but got Unknown //IL_0533: Unknown result type (might be due to invalid IL or missing references) //IL_053a: Expected O, but got Unknown //IL_0549: Unknown result type (might be due to invalid IL or missing references) //IL_0553: Expected O, but got Unknown //IL_0557: Unknown result type (might be due to invalid IL or missing references) //IL_0561: Expected O, but got Unknown //IL_056e: Unknown result type (might be due to invalid IL or missing references) //IL_057b: Unknown result type (might be due to invalid IL or missing references) //IL_058c: Unknown result type (might be due to invalid IL or missing references) //IL_059c: Unknown result type (might be due to invalid IL or missing references) //IL_05a3: Expected O, but got Unknown //IL_05b2: Unknown result type (might be due to invalid IL or missing references) //IL_05be: Unknown result type (might be due to invalid IL or missing references) //IL_05fa: Unknown result type (might be due to invalid IL or missing references) //IL_0601: Expected O, but got Unknown //IL_0610: Unknown result type (might be due to invalid IL or missing references) //IL_061a: Expected O, but got Unknown //IL_061e: Unknown result type (might be due to invalid IL or missing references) //IL_0628: Expected O, but got Unknown //IL_0635: Unknown result type (might be due to invalid IL or missing references) //IL_0642: Unknown result type (might be due to invalid IL or missing references) //IL_0653: Unknown result type (might be due to invalid IL or missing references) //IL_0663: Unknown result type (might be due to invalid IL or missing references) //IL_066a: Expected O, but got Unknown //IL_0679: Unknown result type (might be due to invalid IL or missing references) //IL_0685: Unknown result type (might be due to invalid IL or missing references) //IL_06a9: Unknown result type (might be due to invalid IL or missing references) //IL_06ae: Unknown result type (might be due to invalid IL or missing references) //IL_06b6: Unknown result type (might be due to invalid IL or missing references) //IL_06c0: Expected O, but got Unknown if (((MethodReference)method).HasGenericParameters || method.IsAbstract || (method.IsSpecialName && !method.IsConstructor)) { return false; } if (!HookOrig && ((MemberReference)method).Name.StartsWith("orig_")) { return false; } if (!HookPrivate && method.IsPrivate) { return false; } string name = GetFriendlyName((MethodReference)(object)method); bool flag = true; if (((MethodReference)method).Parameters.Count == 0) { flag = false; } IEnumerable<MethodDefinition> source = null; if (flag) { source = ((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Where((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name && other != method); if (source.Count() == 0) { flag = false; } } if (flag) { StringBuilder stringBuilder = new StringBuilder(); for (int parami = 0; parami < ((MethodReference)method).Parameters.Count; parami++) { ParameterDefinition param = ((MethodReference)method).Parameters[parami]; if (!TypeNameMap.TryGetValue(((MemberReference)((ParameterReference)param).ParameterType).FullName, out var typeName)) { typeName = GetFriendlyName(((ParameterReference)param).ParameterType, full: false); } if (source.Any(delegate(MethodDefinition other) { ParameterDefinition val11 = ((IEnumerable<ParameterDefinition>)((MethodReference)other).Parameters).ElementAtOrDefault(parami); return val11 != null && GetFriendlyName(((ParameterReference)val11).ParameterType, full: false) == typeName && ((ParameterReference)val11).ParameterType.Namespace != ((ParameterReference)param).ParameterType.Namespace; })) { typeName = GetFriendlyName(((ParameterReference)param).ParameterType, full: true); } stringBuilder.Append("_"); stringBuilder.Append(typeName.Replace(".", "").Replace("`", "")); } name += stringBuilder.ToString(); } if (Extensions.FindEvent(hookType, name) != null) { int num = 1; string text; while (Extensions.FindEvent(hookType, text = name + "_" + num) != null) { num++; } name = text; } TypeDefinition val = GenerateDelegateFor(method); ((MemberReference)val).Name = "orig_" + name; val.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never)); hookType.NestedTypes.Add(val); TypeDefinition val2 = GenerateDelegateFor(method); ((MemberReference)val2).Name = "hook_" + name; ((MethodReference)Extensions.FindMethod(val2, "Invoke", true)).Parameters.Insert(0, new ParameterDefinition("orig", (ParameterAttributes)0, (TypeReference)(object)val)); ((MethodReference)Extensions.FindMethod(val2, "BeginInvoke", true)).Parameters.Insert(0, new ParameterDefinition("orig", (ParameterAttributes)0, (TypeReference)(object)val)); val2.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never)); hookType.NestedTypes.Add(val2); MethodReference val3 = OutputModule.ImportReference((MethodReference)(object)method); MethodDefinition val4 = new MethodDefinition("add_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void); ((MethodReference)val4).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, (TypeReference)(object)val2)); val4.Body = new MethodBody(val4); ILProcessor iLProcessor = val4.Body.GetILProcessor(); iLProcessor.Emit(OpCodes.Ldtoken, val3); iLProcessor.Emit(OpCodes.Call, m_GetMethodFromHandle); iLProcessor.Emit(OpCodes.Ldarg_0); GenericInstanceMethod val5 = new GenericInstanceMethod(m_Add); val5.GenericArguments.Add((TypeReference)(object)val2); iLProcessor.Emit(OpCodes.Call, (MethodReference)(object)val5); iLProcessor.Emit(OpCodes.Ret); hookType.Methods.Add(val4); MethodDefinition val6 = new MethodDefinition("remove_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void); ((MethodReference)val6).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, (TypeReference)(object)val2)); val6.Body = new MethodBody(val6); ILProcessor iLProcessor2 = val6.Body.GetILProcessor(); iLProcessor2.Emit(OpCodes.Ldtoken, val3); iLProcessor2.Emit(OpCodes.Call, m_GetMethodFromHandle); iLProcessor2.Emit(OpCodes.Ldarg_0); val5 = new GenericInstanceMethod(m_Remove); val5.GenericArguments.Add((TypeReference)(object)val2); iLProcessor2.Emit(OpCodes.Call, (MethodReference)(object)val5); iLProcessor2.Emit(OpCodes.Ret); hookType.Methods.Add(val6); EventDefinition val7 = new EventDefinition(name, (EventAttributes)0, (TypeReference)(object)val2) { AddMethod = val4, RemoveMethod = val6 }; hookType.Events.Add(val7); MethodDefinition val8 = new MethodDefinition("add_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void); ((MethodReference)val8).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, t_ILManipulator)); val8.Body = new MethodBody(val8); ILProcessor iLProcessor3 = val8.Body.GetILProcessor(); iLProcessor3.Emit(OpCodes.Ldtoken, val3); iLProcessor3.Emit(OpCodes.Call, m_GetMethodFromHandle); iLProcessor3.Emit(OpCodes.Ldarg_0); val5 = new GenericInstanceMethod(m_Modify); val5.GenericArguments.Add((TypeReference)(object)val2); iLProcessor3.Emit(OpCodes.Call, (MethodReference)(object)val5); iLProcessor3.Emit(OpCodes.Ret); hookILType.Methods.Add(val8); MethodDefinition val9 = new MethodDefinition("remove_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void); ((MethodReference)val9).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, t_ILManipulator)); val9.Body = new MethodBody(val9); ILProcessor iLProcessor4 = val9.Body.GetILProcessor(); iLProcessor4.Emit(OpCodes.Ldtoken, val3); iLProcessor4.Emit(OpCodes.Call, m_GetMethodFromHandle); iLProcessor4.Emit(OpCodes.Ldarg_0); val5 = new GenericInstanceMethod(m_Unmodify); val5.GenericArguments.Add((TypeReference)(object)val2); iLProcessor4.Emit(OpCodes.Call, (MethodReference)(object)val5); iLProcessor4.Emit(OpCodes.Ret); hookILType.Methods.Add(val9); EventDefinition val10 = new EventDefinition(name, (EventAttributes)0, t_ILManipulator) { AddMethod = val8, RemoveMethod = val9 }; hookILType.Events.Add(val10); return true; } public TypeDefinition GenerateDelegateFor(MethodDefinition method) { //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Expected O, but got Unknown //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Expected O, but got Unknown //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Expected O, but got Unknown //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Expected O, but got Unknown //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Expected O, but got Unknown //IL_016f: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Expected O, but got Unknown //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Expected O, but got Unknown //IL_01a9: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Expected O, but got Unknown //IL_01f1: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Expected O, but got Unknown //IL_0236: Unknown result type (might be due to invalid IL or missing references) //IL_0240: Expected O, but got Unknown //IL_025d: Unknown result type (might be due to invalid IL or missing references) //IL_0262: Unknown result type (might be due to invalid IL or missing references) //IL_0269: Unknown result type (might be due to invalid IL or missing references) //IL_0272: Expected O, but got Unknown //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02a7: Unknown result type (might be due to invalid IL or missing references) //IL_02b1: Expected O, but got Unknown //IL_02dd: Unknown result type (might be due to invalid IL or missing references) //IL_02e7: Expected O, but got Unknown //IL_0300: Unknown result type (might be due to invalid IL or missing references) //IL_030a: Expected O, but got Unknown //IL_030e: Unknown result type (might be due to invalid IL or missing references) //IL_0318: Expected O, but got Unknown //IL_033f: Unknown result type (might be due to invalid IL or missing references) //IL_0344: Unknown result type (might be due to invalid IL or missing references) //IL_034b: Unknown result type (might be due to invalid IL or missing references) //IL_0354: Expected O, but got Unknown //IL_0367: Unknown result type (might be due to invalid IL or missing references) //IL_0371: Expected O, but got Unknown //IL_0375: Unknown result type (might be due to invalid IL or missing references) //IL_037f: Expected O, but got Unknown string name = GetFriendlyName((MethodReference)(object)method); int num = ((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Where((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name).ToList().IndexOf(method); if (num != 0) { string suffix = num.ToString(); do { name = name + "_" + suffix; } while (((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Any((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name + suffix)); } name = "d_" + name; TypeDefinition val = new TypeDefinition((string)null, (string)null, (TypeAttributes)258, t_MulticastDelegate); MethodDefinition val2 = new MethodDefinition(".ctor", (MethodAttributes)6278, OutputModule.TypeSystem.Void) { ImplAttributes = (MethodImplAttributes)3, HasThis = true }; ((MethodReference)val2).Parameters.Add(new ParameterDefinition(OutputModule.TypeSystem.Object)); ((MethodReference)val2).Parameters.Add(new ParameterDefinition(OutputModule.TypeSystem.IntPtr)); val2.Body = new MethodBody(val2); val.Methods.Add(val2); MethodDefinition val3 = new MethodDefinition("Invoke", (MethodAttributes)454, ImportVisible(((MethodReference)method).ReturnType)) { ImplAttributes = (MethodImplAttributes)3, HasThis = true }; if (!method.IsStatic) { TypeReference val4 = ImportVisible((TypeReference)(object)method.DeclaringType); if (((TypeReference)method.DeclaringType).IsValueType) { val4 = (TypeReference)new ByReferenceType(val4); } ((MethodReference)val3).Parameters.Add(new ParameterDefinition("self", (ParameterAttributes)0, val4)); } Enumerator<ParameterDefinition> enumerator = ((MethodReference)method).Parameters.GetEnumerator(); try { while (enumerator.MoveNext()) { ParameterDefinition current = enumerator.Current; ((MethodReference)val3).Parameters.Add(new ParameterDefinition(((ParameterReference)current).Name, (ParameterAttributes)(current.Attributes & 0xFFEF & 0xEFFF), ImportVisible(((ParameterReference)current).ParameterType))); } } finally { ((IDisposable)enumerator).Dispose(); } val3.Body = new MethodBody(val3); val.Methods.Add(val3); MethodDefinition val5 = new MethodDefinition("BeginInvoke", (MethodAttributes)454, t_IAsyncResult) { ImplAttributes = (MethodImplAttributes)3, HasThis = true }; enumerator = ((MethodReference)val3).Parameters.GetEnumerator(); try { while (enumerator.MoveNext()) { ParameterDefinition current2 = enumerator.Current; ((MethodReference)val5).Parameters.Add(new ParameterDefinition(((ParameterReference)current2).Name, current2.Attributes, ((ParameterReference)current2).ParameterType)); } } finally { ((IDisposable)enumerator).Dispose(); } ((MethodReference)val5).Parameters.Add(new ParameterDefinition("callback", (ParameterAttributes)0, t_AsyncCallback)); ((MethodReference)val5).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, OutputModule.TypeSystem.Object)); val5.Body = new MethodBody(val5); val.Methods.Add(val5); MethodDefinition val6 = new MethodDefinition("EndInvoke", (MethodAttributes)454, OutputModule.TypeSystem.Object) { ImplAttributes = (MethodImplAttributes)3, HasThis = true }; ((MethodReference)val6).Parameters.Add(new ParameterDefinition("result", (ParameterAttributes)0, t_IAsyncResult)); val6.Body = new MethodBody(val6); val.Methods.Add(val6); return val; } private string GetFriendlyName(MethodReference method) { string text = ((MemberReference)method).Name; if (text.StartsWith(".")) { text = text.Substring(1); } return text.Replace('.', '_'); } private string GetFriendlyName(TypeReference type, bool full) { if (type is TypeSpecification) { StringBuilder stringBuilder = new StringBuilder(); BuildFriendlyName(stringBuilder, type, full); return stringBuilder.ToString(); } if (!full) { return ((MemberReference)type).Name; } return ((MemberReference)type).FullName; } private void BuildFriendlyName(StringBuilder builder, TypeReference type, bool full) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) if (!(type is TypeSpecification)) { builder.Append((full ? ((MemberReference)type).FullName : ((MemberReference)type).Name).Replace("_", "")); return; } if (type.IsByReference) { builder.Append("ref"); } else if (type.IsPointer) { builder.Append("ptr"); } BuildFriendlyName(builder, ((TypeSpecification)type).ElementType, full); if (type.IsArray) { builder.Append("Array"); } } private bool IsPublic(TypeDefinition typeDef) { if (typeDef != null && (typeDef.IsNestedPublic || typeDef.IsPublic)) { return !typeDef.IsNotPublic; } return false; } private bool HasPublicArgs(GenericInstanceType typeGen) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) Enumerator<TypeReference> enumerator = typeGen.GenericArguments.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeReference current = enumerator.Current; if (current.IsGenericParameter) { return false; } GenericInstanceType val = (GenericInstanceType)(object)((current is GenericInstanceType) ? current : null); if (val != null && !HasPublicArgs(val)) { return false; } if (!IsPublic(Extensions.SafeResolve(current))) { return false; } } } finally { ((IDisposable)enumerator).Dispose(); } return true; } private TypeReference ImportVisible(TypeReference typeRef) { for (TypeDefinition val = ((typeRef != null) ? Extensions.SafeResolve(typeRef) : null); val != null; val = ((typeRef != null) ? Extensions.SafeResolve(typeRef) : null)) { GenericInstanceType val2 = (GenericInstanceType)(object)((typeRef is GenericInstanceType) ? typeRef : null); if (val2 == null || HasPublicArgs(val2)) { TypeDefinition val3 = val; while (true) { if (val3 != null) { if (IsPublic(val3) && (val3 == val || !((TypeReference)val3).HasGenericParameters)) { val3 = val3.DeclaringType; continue; } if (!val.IsEnum) { break; } typeRef = ((FieldReference)Extensions.FindField(val, "value__")).FieldType; } try { return OutputModule.ImportReference(typeRef); } catch { return OutputModule.TypeSystem.Object; } } } typeRef = val.BaseType; } return OutputModule.TypeSystem.Object; } private CustomAttribute GenerateObsolete(string message, bool error) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown CustomAttribute val = new CustomAttribute(m_ObsoleteAttribute_ctor); val.ConstructorArguments.Add(new CustomAttributeArgument(OutputModule.TypeSystem.String, (object)message)); val.ConstructorArguments.Add(new CustomAttributeArgument(OutputModule.TypeSystem.Boolean, (object)error)); return val; } private CustomAttribute GenerateEditorBrowsable(EditorBrowsableState state) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown CustomAttribute val = new CustomAttribute(m_EditorBrowsableAttribute_ctor); val.ConstructorArguments.Add(new CustomAttributeArgument(t_EditorBrowsableState, (object)state)); return val; } } internal class Program { private static void Main(string[] args) { //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Expected O, but got Unknown Console.WriteLine("MonoMod.RuntimeDetour.HookGen " + typeof(Program).Assembly.GetName().Version); Console.WriteLine("using MonoMod " + typeof(MonoModder).Assembly.GetName().Version); Console.WriteLine("using MonoMod.RuntimeDetour " + typeof(Detour).Assembly.GetName().Version); if (args.Length == 0) { Console.WriteLine("No valid arguments (assembly path) passed."); if (Debugger.IsAttached) { Console.ReadKey(); } return; } int num = 0; for (int i = 0; i < args.Length; i++) { if (args[i] == "--namespace" && i + 2 < args.Length) { i++; Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE", args[i]); continue; } if (args[i] == "--namespace-il" && i + 2 < args.Length) { i++; Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE_IL", args[i]); continue; } if (args[i] == "--orig") { Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_ORIG", "1"); continue; } if (args[i] == "--private") { Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE", "1"); continue; } num = i; break; } if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW"))) { Environment.SetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW", "0"); } if (num >= args.Length) { Console.WriteLine("No assembly path passed."); if (Debugger.IsAttached) { Console.ReadKey(); } return; } string text = args[num]; string text2 = ((args.Length != 1 && num != args.Length - 1) ? args[^1] : null); text2 = text2 ?? Path.Combine(Path.GetDirectoryName(text), "MMHOOK_" + Path.ChangeExtension(Path.GetFileName(text), "dll")); MonoModder val = new MonoModder { InputPath = text, OutputPath = text2, ReadingMode = (ReadingMode)2 }; try { val.Read(); val.MapDependencies(); if (File.Exists(text2)) { val.Log("[HookGen] Clearing " + text2); File.Delete(text2); } val.Log("[HookGen] Starting HookGenerator"); HookGenerator hookGenerator = new HookGenerator(val, Path.GetFileName(text2)); ModuleDefinition outputModule = hookGenerator.OutputModule; try { hookGenerator.Generate(); outputModule.Write(text2); } finally { ((IDisposable)outputModule)?.Dispose(); } val.Log("[HookGen] Done."); } finally { ((IDisposable)val)?.Dispose(); } if (Debugger.IsAttached) { Console.ReadKey(); } } } }