Core Keeper is now using mod.io for their official mod support Read more here
Decompiled source of NewBepin v1.0.0
BepInEx/core/0Harmony20.dll
Decompiled a week ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using HarmonyLib.Internal; using HarmonyLib.Internal.Patching; using HarmonyLib.Internal.Util; using HarmonyLib.Tools; using HarmonyXInterop; using JetBrains.Annotations; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; using MonoMod.Cil; using MonoMod.RuntimeDetour; using MonoMod.Utils; using MonoMod.Utils.Cil; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: ComVisible(false)] [assembly: Guid("69F6541D-A0F5-419D-B0EE-F5017F1D34F3")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("0Harmony20")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.0.0.0+6830e686c7931164a4e34595a34cbfa15846d1d4")] [assembly: AssemblyProduct("HarmonyX2Interop")] [assembly: AssemblyTitle("0Harmony20")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.0.0.0")] [module: UnverifiableCode] namespace JetBrains.Annotations { [AttributeUsage(AttributeTargets.All)] internal sealed class UsedImplicitlyAttribute : Attribute { public ImplicitUseKindFlags UseKindFlags { get; } public ImplicitUseTargetFlags TargetFlags { get; } public UsedImplicitlyAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter | AttributeTargets.GenericParameter)] internal sealed class MeansImplicitUseAttribute : Attribute { [UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; } [UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; } public MeansImplicitUseAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } } [Flags] internal enum ImplicitUseKindFlags { Default = 7, Access = 1, Assign = 2, InstantiatedWithFixedConstructorSignature = 4, InstantiatedNoFixedConstructorSignature = 8 } [Flags] internal enum ImplicitUseTargetFlags { Default = 1, Itself = 1, Members = 2, WithInheritors = 4, WithMembers = 3 } } namespace HarmonyLib { public static class Priority { public const int Last = 0; public const int VeryLow = 100; public const int Low = 200; public const int LowerThanNormal = 300; public const int Normal = 400; public const int HigherThanNormal = 500; public const int High = 600; public const int VeryHigh = 700; public const int First = 800; } public enum MethodType { Normal, Getter, Setter, Constructor, StaticConstructor } public enum ArgumentType { Normal, Ref, Out, Pointer } public enum HarmonyPatchType { All, Prefix, Postfix, Transpiler, Finalizer, ReversePatch } public enum HarmonyReversePatchType { Original, Snapshot } [MeansImplicitUse] public class HarmonyAttribute : Attribute { public HarmonyMethod info = new HarmonyMethod(); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public class HarmonyPatch : HarmonyAttribute { public HarmonyPatch() { } public HarmonyPatch(Type declaringType) { info.declaringType = declaringType; } public HarmonyPatch(Type declaringType, Type[] argumentTypes) { info.declaringType = declaringType; info.argumentTypes = argumentTypes; } public HarmonyPatch(Type declaringType, string methodName) { info.declaringType = declaringType; info.methodName = methodName; } public HarmonyPatch(Type declaringType, string methodName, params Type[] argumentTypes) { info.declaringType = declaringType; info.methodName = methodName; info.argumentTypes = argumentTypes; } public HarmonyPatch(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations) { info.declaringType = declaringType; info.methodName = methodName; ParseSpecialArguments(argumentTypes, argumentVariations); } public HarmonyPatch(Type declaringType, MethodType methodType) { info.declaringType = declaringType; info.methodType = methodType; } public HarmonyPatch(Type declaringType, MethodType methodType, params Type[] argumentTypes) { info.declaringType = declaringType; info.methodType = methodType; info.argumentTypes = argumentTypes; } public HarmonyPatch(Type declaringType, MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations) { info.declaringType = declaringType; info.methodType = methodType; ParseSpecialArguments(argumentTypes, argumentVariations); } public HarmonyPatch(Type declaringType, string methodName, MethodType methodType) { info.declaringType = declaringType; info.methodName = methodName; info.methodType = methodType; } public HarmonyPatch(string methodName) { info.methodName = methodName; } public HarmonyPatch(string methodName, params Type[] argumentTypes) { info.methodName = methodName; info.argumentTypes = argumentTypes; } public HarmonyPatch(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations) { info.methodName = methodName; ParseSpecialArguments(argumentTypes, argumentVariations); } public HarmonyPatch(string methodName, MethodType methodType) { info.methodName = methodName; info.methodType = methodType; } public HarmonyPatch(MethodType methodType) { info.methodType = methodType; } public HarmonyPatch(MethodType methodType, params Type[] argumentTypes) { info.methodType = methodType; info.argumentTypes = argumentTypes; } public HarmonyPatch(MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations) { info.methodType = methodType; ParseSpecialArguments(argumentTypes, argumentVariations); } public HarmonyPatch(Type[] argumentTypes) { info.argumentTypes = argumentTypes; } public HarmonyPatch(Type[] argumentTypes, ArgumentType[] argumentVariations) { ParseSpecialArguments(argumentTypes, argumentVariations); } private void ParseSpecialArguments(Type[] argumentTypes, ArgumentType[] argumentVariations) { if (argumentVariations == null || argumentVariations.Length == 0) { info.argumentTypes = argumentTypes; return; } if (argumentTypes.Length < argumentVariations.Length) { throw new ArgumentException("argumentVariations contains more elements than argumentTypes", "argumentVariations"); } List<Type> list = new List<Type>(); for (int i = 0; i < argumentTypes.Length; i++) { Type type = argumentTypes[i]; switch (argumentVariations[i]) { case ArgumentType.Ref: case ArgumentType.Out: type = type.MakeByRefType(); break; case ArgumentType.Pointer: type = type.MakePointerType(); break; } list.Add(type); } info.argumentTypes = list.ToArray(); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public class HarmonyReversePatch : HarmonyAttribute { public HarmonyReversePatch(HarmonyReversePatchType type = HarmonyReversePatchType.Original) { info.reversePatchType = type; } } [AttributeUsage(AttributeTargets.Class)] public class HarmonyPatchAll : HarmonyAttribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class HarmonyPriority : HarmonyAttribute { public HarmonyPriority(int priority) { info.priority = priority; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class HarmonyBefore : HarmonyAttribute { public HarmonyBefore(params string[] before) { info.before = before; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class HarmonyAfter : HarmonyAttribute { public HarmonyAfter(params string[] after) { info.after = after; } } [AttributeUsage(AttributeTargets.Method)] public class HarmonyPrepare : Attribute { } [AttributeUsage(AttributeTargets.Method)] public class HarmonyCleanup : Attribute { } [AttributeUsage(AttributeTargets.Method)] public class HarmonyTargetMethod : Attribute { } [AttributeUsage(AttributeTargets.Method)] public class HarmonyTargetMethods : Attribute { } [AttributeUsage(AttributeTargets.Method)] public class HarmonyPrefix : Attribute { } [AttributeUsage(AttributeTargets.Method)] public class HarmonyPostfix : Attribute { } [AttributeUsage(AttributeTargets.Method)] public class HarmonyTranspiler : Attribute { } [AttributeUsage(AttributeTargets.Method)] public class HarmonyFinalizer : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true)] public class HarmonyArgument : Attribute { public string OriginalName { get; private set; } public int Index { get; private set; } public string NewName { get; private set; } public HarmonyArgument(string originalName) : this(originalName, null) { } public HarmonyArgument(int index) : this(index, null) { } public HarmonyArgument(string originalName, string newName) { OriginalName = originalName; Index = -1; NewName = newName; } public HarmonyArgument(int index, string name) { OriginalName = null; Index = index; NewName = name; } } [AttributeUsage(AttributeTargets.Method)] public class ParameterByRefAttribute : Attribute { public int[] ParameterIndices { get; } public ParameterByRefAttribute(params int[] parameterIndices) { ParameterIndices = parameterIndices; } } public class InvalidHarmonyPatchArgumentException : Exception { public MethodBase Original { get; } public MethodInfo Patch { get; } public override string Message => "(" + Extensions.GetID((MethodBase)Patch, (string)null, (string)null, true, false, false) + "): " + base.Message; public InvalidHarmonyPatchArgumentException(string message, MethodBase original, MethodInfo patch) : base(message) { Original = original; Patch = patch; } } public class MemberNotFoundException : Exception { public MemberNotFoundException(string message) : base(message) { } } public class Harmony { [Obsolete("No longer used, subscribe to Logger.LogChannel.Info")] public static bool DEBUG; [Obsolete("Not supported by HarmonyX", true)] public static bool SELF_PATCHING; public string Id { get; private set; } public Harmony(string id) { if (string.IsNullOrEmpty(id)) { throw new ArgumentException("id cannot be null or empty"); } Logger.Log(Logger.LogChannel.Info, delegate { Assembly assembly = typeof(Harmony).Assembly; Version version = assembly.GetName().Version; string text = assembly.Location; if (string.IsNullOrEmpty(text)) { text = new Uri(assembly.CodeBase).LocalPath; } MethodBase outsideCaller = AccessTools.GetOutsideCaller(); Assembly assembly2 = outsideCaller.DeclaringType?.Assembly; string text2 = assembly2?.Location; if (string.IsNullOrEmpty(text2)) { text2 = ((assembly2 != null) ? new Uri(assembly2.CodeBase).LocalPath : string.Empty); } return $"Created Harmony instance id={id}, version={version}, location={text} - Started from {Extensions.GetID(outsideCaller, (string)null, (string)null, true, false, false)} location={text2}"; }); Id = id; } public void PatchAll() { MethodBase method = new StackTrace().GetFrame(1).GetMethod(); Assembly assembly = method.ReflectedType.Assembly; PatchAll(assembly); } public PatchProcessor ProcessorForAnnotatedClass(Type type) { List<HarmonyMethod> fromType = HarmonyMethodExtensions.GetFromType(type); if (fromType != null && fromType.Any()) { HarmonyMethod attributes = HarmonyMethod.Merge(fromType); return new PatchProcessor(this, type, attributes); } return null; } public void PatchAll(Assembly assembly) { if (assembly == null) { throw new ArgumentNullException("assembly"); } List<PatchProcessor> list = (from x in assembly.GetTypes().Select(ProcessorForAnnotatedClass) where x != null select x).ToList(); foreach (PatchProcessor item in list) { item.Patch(); } if (list.Count == 0) { Logger.Log(Logger.LogChannel.Warn, () => "Could not find any valid Harmony patches inside of assembly " + assembly.FullName); } } public DynamicMethod Patch(MethodBase original, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null, HarmonyMethod finalizer = null) { PatchProcessor patchProcessor = new PatchProcessor(this, original); patchProcessor.AddPrefix(prefix); patchProcessor.AddPostfix(postfix); patchProcessor.AddTranspiler(transpiler); patchProcessor.AddFinalizer(finalizer); return patchProcessor.Patch().FirstOrDefault(); } public MethodInfo ReversePatch(MethodBase original, HarmonyMethod standin, MethodInfo transpiler = null) { return null; } public ReversePatcher CreateReversePatcher(MethodBase original, MethodInfo standin) { return new ReversePatcher(this, original, standin); } public void UnpatchAll(string harmonyID = null) { List<MethodBase> list = GetAllPatchedMethods().ToList(); foreach (MethodBase item in list) { Patches patchInfo = GetPatchInfo(item); UnpatchAllId(item, patchInfo.Prefixes); UnpatchAllId(item, patchInfo.Postfixes); UnpatchAllId(item, patchInfo.Transpilers); UnpatchAllId(item, patchInfo.Finalizers); } void UnpatchAllId(MethodBase original, IEnumerable<Patch> patches) { foreach (Patch patch in patches) { if (harmonyID == null || patch.owner == harmonyID) { Unpatch(original, patch.patch); } } } } public void Unpatch(MethodBase original, HarmonyPatchType type, string harmonyID = null) { PatchProcessor patchProcessor = new PatchProcessor(this, original); patchProcessor.Unpatch(type, harmonyID); } public void Unpatch(MethodBase original, MethodInfo patch) { PatchProcessor patchProcessor = new PatchProcessor(this, original); patchProcessor.Unpatch(patch); } public static bool HasAnyPatches(string harmonyID) { return GetAllPatchedMethods().Select(GetPatchInfo).Any((Patches info) => info.Owners.Contains(harmonyID)); } public static Patches GetPatchInfo(MethodBase method) { return PatchProcessor.GetPatchInfo(method); } public IEnumerable<MethodBase> GetPatchedMethods() { return from original in GetAllPatchedMethods() where GetPatchInfo(original).Owners.Contains(Id) select original; } public static IEnumerable<MethodBase> GetAllPatchedMethods() { return GlobalPatchState.GetPatchedMethods(); } public static Dictionary<string, Version> VersionInfo(out Version currentVersion) { return PatchProcessor.VersionInfo(out currentVersion); } public void PatchAll(Type type) { if (type == null) { throw new ArgumentNullException("type"); } MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { List<HarmonyMethod> fromMethod = HarmonyMethodExtensions.GetFromMethod(methodInfo); if (fromMethod != null && fromMethod.Any()) { object[] customAttributes = methodInfo.GetCustomAttributes(inherit: true); HarmonyMethod combinedInfo = HarmonyMethod.Merge(fromMethod); List<HarmonyMethod> list = fromMethod.Where(IsMethodComplete).ToList(); if (fromMethod.All((HarmonyMethod x) => x.declaringType != combinedInfo.declaringType && x.methodName != combinedInfo.methodName)) { list.Add(combinedInfo); } List<MethodBase> list2 = new List<MethodBase>(); foreach (HarmonyMethod item in list) { foreach (int item2 in customAttributes.OfType<ParameterByRefAttribute>().SelectMany((ParameterByRefAttribute x) => x.ParameterIndices)) { if (!item.argumentTypes[item2].IsByRef) { item.argumentTypes[item2] = item.argumentTypes[item2].MakeByRefType(); } } if (!item.methodType.HasValue) { item.methodType = MethodType.Normal; } if (item.method == null) { item.method = methodInfo; } MethodBase originalMethod = PatchProcessor.GetOriginalMethod(item); if (originalMethod != null) { list2.Add(originalMethod); } } PatchProcessor patchProcessor = new PatchProcessor(this); foreach (MethodBase item3 in list2) { patchProcessor.AddOriginal(item3); } if (customAttributes.Any((object x) => x is HarmonyPrefix)) { patchProcessor.AddPrefix(new HarmonyMethod(methodInfo)); } if (customAttributes.Any((object x) => x is HarmonyTranspiler)) { patchProcessor.AddTranspiler(new HarmonyMethod(methodInfo)); } if (customAttributes.Any((object x) => x is HarmonyPostfix)) { patchProcessor.AddPostfix(new HarmonyMethod(methodInfo)); } if (customAttributes.Any((object x) => x is HarmonyFinalizer)) { patchProcessor.AddFinalizer(new HarmonyMethod(methodInfo)); } patchProcessor.Patch(); } else if ((Logger.ChannelFilter & Logger.LogChannel.Warn) != 0 && methodInfo.GetCustomAttributes(typeof(HarmonyAttribute), inherit: true).Any()) { Logger.LogText(Logger.LogChannel.Warn, "Method " + methodInfo.FullDescription() + " has an invalid combination of Harmony attributes and will be ignored"); } } static bool IsMethodComplete(HarmonyMethod m) { return m.declaringType != null && (m.methodName != null || m.methodType.GetValueOrDefault() == MethodType.Constructor || m.methodType.GetValueOrDefault() == MethodType.StaticConstructor); } } public static Harmony CreateAndPatchAll(Type type, string harmonyInstanceId = null) { Harmony harmony = new Harmony(harmonyInstanceId ?? $"harmony-auto-{Guid.NewGuid()}"); harmony.PatchAll(type); return harmony; } public static Harmony CreateAndPatchAll(Assembly assembly, string harmonyInstanceId = null) { Harmony harmony = new Harmony(harmonyInstanceId ?? $"harmony-auto-{Guid.NewGuid()}"); harmony.PatchAll(assembly); return harmony; } } public class HarmonyMethod { public MethodInfo method; public Type declaringType; public string methodName; public MethodType? methodType; public Type[] argumentTypes; public int priority = -1; public string[] before; public string[] after; public HarmonyReversePatchType? reversePatchType; public HarmonyMethod() { } private void ImportMethod(MethodInfo theMethod) { method = theMethod; if (method != null) { List<HarmonyMethod> fromMethod = HarmonyMethodExtensions.GetFromMethod(method); if (fromMethod != null) { Merge(fromMethod).CopyTo(this); } } } public HarmonyMethod(MethodInfo method) { if (method == null) { throw new ArgumentNullException("method"); } ImportMethod(method); } public HarmonyMethod(Type type, string name, Type[] parameters = null) { MethodInfo methodInfo = AccessTools.Method(type, name, parameters); if (methodInfo == null) { throw new ArgumentException($"Cannot not find method for type {type} and name {name} and parameters {parameters?.Description()}"); } ImportMethod(methodInfo); } public static List<string> HarmonyFields() { return (from s in AccessTools.GetFieldNames(typeof(HarmonyMethod)) where s != "method" select s).ToList(); } public static HarmonyMethod Merge(List<HarmonyMethod> attributes) { HarmonyMethod harmonyMethod = new HarmonyMethod(); if (attributes == null) { return harmonyMethod; } Traverse resultTrv = Traverse.Create(harmonyMethod); attributes.ForEach(delegate(HarmonyMethod attribute) { Traverse trv = Traverse.Create(attribute); HarmonyFields().ForEach(delegate(string f) { object value = trv.Field(f).GetValue(); if (value != null) { HarmonyMethodExtensions.SetValue(resultTrv, f, value); } }); }); return harmonyMethod; } public override string ToString() { string result = "HarmonyMethod["; Traverse trv = Traverse.Create(this); HarmonyFields().ForEach(delegate(string f) { result += $"{f}{'='}{trv.Field(f).GetValue()}"; }); return result + "]"; } } public static class HarmonyMethodExtensions { internal static void SetValue(Traverse trv, string name, object val) { if (val != null) { Traverse traverse = trv.Field(name); if (name == "methodType" || name == "reversePatchType") { Type underlyingType = Nullable.GetUnderlyingType(traverse.GetValueType()); val = Enum.ToObject(underlyingType, (int)val); } traverse.SetValue(val); } } public static void CopyTo(this HarmonyMethod from, HarmonyMethod to) { if (to == null) { return; } Traverse fromTrv = Traverse.Create(from); Traverse toTrv = Traverse.Create(to); HarmonyMethod.HarmonyFields().ForEach(delegate(string f) { object value = fromTrv.Field(f).GetValue(); if (value != null) { SetValue(toTrv, f, value); } }); } public static HarmonyMethod Clone(this HarmonyMethod original) { HarmonyMethod harmonyMethod = new HarmonyMethod(); original.CopyTo(harmonyMethod); return harmonyMethod; } public static HarmonyMethod Merge(this HarmonyMethod master, HarmonyMethod detail) { if (detail == null) { return master; } HarmonyMethod harmonyMethod = new HarmonyMethod(); Traverse resultTrv = Traverse.Create(harmonyMethod); Traverse masterTrv = Traverse.Create(master); Traverse detailTrv = Traverse.Create(detail); HarmonyMethod.HarmonyFields().ForEach(delegate(string f) { object value = masterTrv.Field(f).GetValue(); object value2 = detailTrv.Field(f).GetValue(); SetValue(resultTrv, f, value2 ?? value); }); return harmonyMethod; } private static HarmonyMethod GetHarmonyMethodInfo(object attribute) { FieldInfo field = attribute.GetType().GetField("info", AccessTools.all); if (field == null) { return null; } if (field.FieldType.Name != "HarmonyMethod") { return null; } object value = field.GetValue(attribute); return AccessTools.MakeDeepCopy<HarmonyMethod>(value); } public static List<HarmonyMethod> GetFromType(Type type) { if (type == null) { throw new ArgumentNullException("type"); } return (from attr in type.GetCustomAttributes(inherit: true) select GetHarmonyMethodInfo(attr) into info where info != null select info).ToList(); } public static HarmonyMethod GetMergedFromType(Type type) { return HarmonyMethod.Merge(GetFromType(type)); } public static HarmonyMethod GetMergedFromMethod(MethodBase method) { return HarmonyMethod.Merge(GetFromMethod(method)); } public static List<HarmonyMethod> GetFromMethod(MethodBase method) { return (from attr in method.GetCustomAttributes(inherit: true) select GetHarmonyMethodInfo(attr) into info where info != null select info).ToList(); } } [Obsolete("Exists for legacy support", true)] internal static class HarmonySharedState { [Obsolete("Exists for legacy support", true)] public static PatchInfo GetPatchInfo(MethodBase method) { return method.ToPatchInfo(); } [Obsolete("Exists for legacy support", true)] public static IEnumerable<MethodBase> GetPatchedMethods() { return GlobalPatchState.GetPatchedMethods(); } [Obsolete("Exists for legacy support", true)] public static void UpdatePatchInfo(MethodBase methodBase, PatchInfo patchInfo) { } } [Obsolete("Exists for legacy support", true)] internal static class PatchFunctions { [Obsolete("Exists for legacy support", true)] public static DynamicMethod UpdateWrapper(MethodBase original, PatchInfo info, string id) { original.GetMethodPatcher().Apply(); return null; } } public class PatchInfo { public Patch[] prefixes; public Patch[] postfixes; public Patch[] transpilers; public Patch[] finalizers; public PatchInfo() { prefixes = new Patch[0]; postfixes = new Patch[0]; transpilers = new Patch[0]; finalizers = new Patch[0]; } private void AddPatch(ref Patch[] list, string owner, HarmonyMethod info) { if (!(info?.method == null)) { int priority = ((info.priority == -1) ? 400 : info.priority); string[] before = info.before ?? new string[0]; string[] after = info.after ?? new string[0]; AddPatch(ref list, info.method, owner, priority, before, after); } } private void AddPatch(ref Patch[] list, MethodInfo patch, string owner, int priority, string[] before, string[] after) { List<Patch> list2 = list.ToList(); list2.Add(new Patch(patch, prefixes.Count() + 1, owner, priority, before, after)); list = list2.ToArray(); } private void RemovePatch(ref Patch[] list, string owner) { if (owner == "*") { list = new Patch[0]; return; } list = list.Where((Patch patch) => patch.owner != owner).ToArray(); } public void AddPrefix(MethodInfo patch, string owner, int priority, string[] before, string[] after) { AddPatch(ref prefixes, patch, owner, priority, before, after); } public void AddPrefix(string owner, HarmonyMethod info) { AddPatch(ref prefixes, owner, info); } public void RemovePrefix(string owner) { RemovePatch(ref prefixes, owner); } public void AddPostfix(MethodInfo patch, string owner, int priority, string[] before, string[] after) { AddPatch(ref postfixes, patch, owner, priority, before, after); } public void AddPostfix(string owner, HarmonyMethod info) { AddPatch(ref postfixes, owner, info); } public void RemovePostfix(string owner) { RemovePatch(ref postfixes, owner); } public void AddTranspiler(MethodInfo patch, string owner, int priority, string[] before, string[] after) { AddPatch(ref transpilers, patch, owner, priority, before, after); } public void AddTranspiler(string owner, HarmonyMethod info) { AddPatch(ref transpilers, owner, info); } public void RemoveTranspiler(string owner) { RemovePatch(ref transpilers, owner); } public void AddFinalizer(MethodInfo patch, string owner, int priority, string[] before, string[] after) { AddPatch(ref finalizers, patch, owner, priority, before, after); } public void AddFinalizer(string owner, HarmonyMethod info) { AddPatch(ref finalizers, owner, info); } public void RemoveFinalizer(string owner) { RemovePatch(ref finalizers, owner); } public void RemovePatch(MethodInfo patch) { lock (this) { prefixes = prefixes.Where((Patch p) => p.patch != patch).ToArray(); postfixes = postfixes.Where((Patch p) => p.patch != patch).ToArray(); transpilers = transpilers.Where((Patch p) => p.patch != patch).ToArray(); finalizers = finalizers.Where((Patch p) => p.patch != patch).ToArray(); } } } public class Patch : IComparable { public readonly int index; public readonly string owner; public readonly int priority; public readonly string[] before; public readonly string[] after; public MethodInfo patch; public MethodInfo PatchMethod { get { return patch; } set { patch = value; } } public Patch(MethodInfo patch, int index, string owner, int priority, string[] before, string[] after) { if (patch is DynamicMethod) { throw new ArgumentException("Cannot directly reference dynamic method \"" + Extensions.GetID((MethodBase)patch, (string)null, (string)null, true, false, false) + "\" in Harmony. Use a factory method instead that will return the dynamic method.", "patch"); } this.index = index; this.owner = owner; this.priority = priority; this.before = before; this.after = after; this.patch = patch; } public MethodInfo GetMethod(MethodBase original) { if (patch.ReturnType != typeof(DynamicMethod) && patch.ReturnType != typeof(MethodInfo)) { return patch; } if (!patch.IsStatic) { return patch; } ParameterInfo[] parameters = patch.GetParameters(); if (parameters.Count() != 1) { return patch; } if (parameters[0].ParameterType != typeof(MethodBase)) { return patch; } return patch.Invoke(null, new object[1] { original }) as MethodInfo; } public override bool Equals(object obj) { return obj is Patch patch && this.patch == patch.patch; } public int CompareTo(object obj) { if (!(obj is Patch patch)) { return 0; } if (patch.priority != priority) { return -priority.CompareTo(patch.priority); } return index.CompareTo(patch.index); } public override int GetHashCode() { return patch.GetHashCode(); } } public class Patches { public readonly ReadOnlyCollection<Patch> Prefixes; public readonly ReadOnlyCollection<Patch> Postfixes; public readonly ReadOnlyCollection<Patch> Transpilers; public readonly ReadOnlyCollection<Patch> Finalizers; public ReadOnlyCollection<string> Owners { get { HashSet<string> hashSet = new HashSet<string>(); hashSet.UnionWith(Prefixes.Select((Patch p) => p.owner)); hashSet.UnionWith(Postfixes.Select((Patch p) => p.owner)); hashSet.UnionWith(Transpilers.Select((Patch p) => p.owner)); hashSet.UnionWith(Finalizers.Select((Patch p) => p.owner)); return hashSet.ToList().AsReadOnly(); } } public Patches(Patch[] prefixes, Patch[] postfixes, Patch[] transpilers, Patch[] finalizers) { if (prefixes == null) { prefixes = new Patch[0]; } if (postfixes == null) { postfixes = new Patch[0]; } if (transpilers == null) { transpilers = new Patch[0]; } if (finalizers == null) { finalizers = new Patch[0]; } Prefixes = prefixes.ToList().AsReadOnly(); Postfixes = postfixes.ToList().AsReadOnly(); Transpilers = transpilers.ToList().AsReadOnly(); Finalizers = finalizers.ToList().AsReadOnly(); } } public class PatchProcessor { private readonly Harmony instance; private readonly Type container; private readonly HarmonyMethod containerAttributes; private readonly List<MethodBase> originals = new List<MethodBase>(); private HarmonyMethod prefix; private HarmonyMethod postfix; private HarmonyMethod transpiler; private HarmonyMethod finalizer; public PatchProcessor(Harmony instance, MethodBase original = null) { this.instance = instance; if (original != null) { originals.Add(original); } } public PatchProcessor(Harmony instance, Type type, HarmonyMethod attributes) { this.instance = instance; container = type; containerAttributes = attributes ?? new HarmonyMethod(); prefix = containerAttributes.Clone(); postfix = containerAttributes.Clone(); transpiler = containerAttributes.Clone(); finalizer = containerAttributes.Clone(); PrepareType(); } [Obsolete("Use other constructors and Add* methods")] public PatchProcessor(Harmony instance, List<MethodBase> originals, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null, HarmonyMethod finalizer = null) { this.instance = instance; this.originals = originals; this.prefix = prefix; this.postfix = postfix; this.transpiler = transpiler; this.finalizer = finalizer; } public PatchProcessor AddOriginal(MethodBase original) { if (!originals.Contains(original)) { originals.Add(original); } return this; } public PatchProcessor SetOriginals(List<MethodBase> originals) { this.originals.Clear(); this.originals.AddRange(originals); return this; } public PatchProcessor AddPrefix(HarmonyMethod prefix) { this.prefix = prefix; return this; } public PatchProcessor AddPrefix(MethodInfo fixMethod) { prefix = new HarmonyMethod(fixMethod); return this; } public PatchProcessor AddPostfix(HarmonyMethod postfix) { this.postfix = postfix; return this; } public PatchProcessor AddPostfix(MethodInfo fixMethod) { postfix = new HarmonyMethod(fixMethod); return this; } public PatchProcessor AddTranspiler(HarmonyMethod transpiler) { this.transpiler = transpiler; return this; } public PatchProcessor AddTranspiler(MethodInfo fixMethod) { transpiler = new HarmonyMethod(fixMethod); return this; } public PatchProcessor AddFinalizer(HarmonyMethod finalizer) { this.finalizer = finalizer; return this; } public PatchProcessor AddFinalizer(MethodInfo fixMethod) { finalizer = new HarmonyMethod(fixMethod); return this; } public static Patches GetPatchInfo(MethodBase method) { PatchInfo patchInfo = method.GetPatchInfo(); if (patchInfo == null) { return null; } lock (patchInfo) { return new Patches(patchInfo.prefixes, patchInfo.postfixes, patchInfo.transpilers, patchInfo.finalizers); } } public static Dictionary<string, Version> VersionInfo(out Version currentVersion) { currentVersion = typeof(Harmony).Assembly.GetName().Version; Dictionary<string, Assembly> assemblies = new Dictionary<string, Assembly>(); foreach (MethodBase allPatchedMethod in GetAllPatchedMethods()) { Patches patchInfo = GetPatchInfo(allPatchedMethod); AddAssemblies(patchInfo.Prefixes); AddAssemblies(patchInfo.Postfixes); AddAssemblies(patchInfo.Transpilers); AddAssemblies(patchInfo.Finalizers); } Dictionary<string, Version> dictionary = new Dictionary<string, Version>(); foreach (KeyValuePair<string, Assembly> item in assemblies) { AssemblyName assemblyName = item.Value.GetReferencedAssemblies().FirstOrDefault((AssemblyName a) => a.FullName.StartsWith("0Harmony, Version", StringComparison.Ordinal)); if (assemblyName != null) { dictionary[item.Key] = assemblyName.Version; } } return dictionary; void AddAssemblies(IEnumerable<Patch> patches) { foreach (Patch patch in patches) { assemblies[patch.owner] = patch.patch.DeclaringType?.Assembly; } } } public static List<CodeInstruction> GetOriginalInstructions(MethodBase original, ILGenerator generator = null) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown //IL_0024: Unknown result type (might be due to invalid IL or missing references) DynamicMethodDefinition val = new DynamicMethodDefinition(original); ILManipulator iLManipulator = new ILManipulator(val.Definition.Body); ILGenerator il = generator ?? ((ILGeneratorShim)new CecilILGenerator(val.GetILProcessor())).GetProxy(); return iLManipulator.GetInstructions(il); } public static List<CodeInstruction> GetOriginalInstructions(MethodBase original, out ILGenerator generator) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown //IL_0020: Unknown result type (might be due to invalid IL or missing references) DynamicMethodDefinition val = new DynamicMethodDefinition(original); ILManipulator iLManipulator = new ILManipulator(val.Definition.Body); generator = ((ILGeneratorShim)new CecilILGenerator(val.GetILProcessor())).GetProxy(); return iLManipulator.GetInstructions(generator); } [Obsolete("Use GetAllPatchedMethods instead")] public static IEnumerable<MethodBase> AllPatchedMethods() { return GlobalPatchState.GetPatchedMethods(); } public static IEnumerable<MethodBase> GetAllPatchedMethods() { return GlobalPatchState.GetPatchedMethods(); } public List<DynamicMethod> Patch() { Stopwatch sw = null; Logger.Log(Logger.LogChannel.Info, delegate { sw = Stopwatch.StartNew(); return "Patching " + instance.Id + "..."; }); List<DynamicMethod> result = new List<DynamicMethod>(); foreach (MethodBase original in originals) { if (original == null) { throw new NullReferenceException("Null method for " + instance.Id); } Logger.Log(Logger.LogChannel.Info, () => "Patching " + Extensions.GetID(original, (string)null, (string)null, true, false, false)); bool individualPrepareResult = RunMethod<HarmonyPrepare, bool>(defaultIfNotExisting: true, new object[1] { original }); Logger.Log(Logger.LogChannel.Info, () => $"HarmonyPrepare result: {individualPrepareResult}"); if (individualPrepareResult) { PatchInfo patchInfo = original.ToPatchInfo(); lock (patchInfo) { patchInfo.AddPrefix(instance.Id, prefix); patchInfo.AddPostfix(instance.Id, postfix); patchInfo.AddTranspiler(instance.Id, transpiler); patchInfo.AddFinalizer(instance.Id, finalizer); } original.GetMethodPatcher().Apply(); RunMethod<HarmonyCleanup>(new object[1] { original }); } } Logger.Log(Logger.LogChannel.Info, () => $"Patching {instance.Id} took {sw.ElapsedMilliseconds}ms"); return result; } public PatchProcessor Unpatch(HarmonyPatchType type, string harmonyID) { foreach (MethodBase original in originals) { PatchInfo patchInfo = original.ToPatchInfo(); lock (patchInfo) { if (type == HarmonyPatchType.All || type == HarmonyPatchType.Prefix) { patchInfo.RemovePrefix(harmonyID); } if (type == HarmonyPatchType.All || type == HarmonyPatchType.Postfix) { patchInfo.RemovePostfix(harmonyID); } if (type == HarmonyPatchType.All || type == HarmonyPatchType.Transpiler) { patchInfo.RemoveTranspiler(harmonyID); } if (type == HarmonyPatchType.All || type == HarmonyPatchType.Finalizer) { patchInfo.RemoveFinalizer(harmonyID); } } original.GetMethodPatcher().Apply(); } return this; } public PatchProcessor Unpatch(MethodInfo patch) { foreach (MethodBase original in originals) { PatchInfo patchInfo = original.ToPatchInfo(); patchInfo.RemovePatch(patch); original.GetMethodPatcher().Apply(); } return this; } private void PrepareType() { if (!RunMethod<HarmonyPrepare, bool>(defaultIfNotExisting: true, Array.Empty<object>())) { return; } MethodType? methodType = containerAttributes.methodType; if (!containerAttributes.methodType.HasValue) { containerAttributes.methodType = MethodType.Normal; } string reversePatchAttr = typeof(HarmonyReversePatch).FullName; List<MethodInfo> list = (from m in container.GetMethods(AccessTools.all) where m.GetCustomAttributes(inherit: true).Any((object a) => a.GetType().FullName == reversePatchAttr) select m).ToList(); foreach (MethodInfo item in list) { HarmonyMethod attribute = containerAttributes.Merge(new HarmonyMethod(item)); MethodBase originalMethod = GetOriginalMethod(attribute); ReversePatcher reversePatcher = instance.CreateReversePatcher(originalMethod, item); reversePatcher.Patch(); } IEnumerable<MethodBase> enumerable = RunMethod<HarmonyTargetMethods, IEnumerable<MethodBase>>(null, Array.Empty<object>()); if (enumerable != null) { originals.Clear(); originals.AddRange(enumerable); } else if (container.GetCustomAttributes(inherit: true).Any((object a) => a.GetType().FullName == typeof(HarmonyPatchAll).FullName)) { Type declaringType = containerAttributes.declaringType; originals.AddRange(AccessTools.GetDeclaredConstructors(declaringType).Cast<MethodBase>()); originals.AddRange(AccessTools.GetDeclaredMethods(declaringType).Cast<MethodBase>()); List<PropertyInfo> declaredProperties = AccessTools.GetDeclaredProperties(declaringType); originals.AddRange((from prop in declaredProperties select prop.GetGetMethod(nonPublic: true) into method where method != null select method).Cast<MethodBase>()); originals.AddRange((from prop in declaredProperties select prop.GetSetMethod(nonPublic: true) into method where method != null select method).Cast<MethodBase>()); } else { MethodBase methodBase = RunMethod<HarmonyTargetMethod, MethodBase>(null, Array.Empty<object>()) ?? GetOriginalMethod(containerAttributes); if (methodBase == null) { string text = "("; text += $"declaringType={containerAttributes.declaringType}, "; text = text + "methodName =" + containerAttributes.methodName + ", "; text += $"methodType={methodType}, "; text = text + "argumentTypes=" + containerAttributes.argumentTypes.Description(); text += ")"; throw new ArgumentException("No target method specified for class " + container.FullName + " " + text); } originals.Add(methodBase); } GetPatches(container, out var methodInfo, out var methodInfo2, out var methodInfo3, out var methodInfo4); if (prefix != null) { prefix.method = methodInfo; } if (postfix != null) { postfix.method = methodInfo2; } if (transpiler != null) { transpiler.method = methodInfo3; } if (finalizer != null) { finalizer.method = methodInfo4; } if (methodInfo != null) { if (!methodInfo.IsStatic) { throw new ArgumentException("Patch method " + Extensions.GetID((MethodBase)methodInfo, (string)null, (string)null, true, false, false) + " must be static"); } List<HarmonyMethod> fromMethod = HarmonyMethodExtensions.GetFromMethod(methodInfo); containerAttributes.Merge(HarmonyMethod.Merge(fromMethod)).CopyTo(prefix); } if (methodInfo2 != null) { if (!methodInfo2.IsStatic) { throw new ArgumentException("Patch method " + Extensions.GetID((MethodBase)methodInfo2, (string)null, (string)null, true, false, false) + " must be static"); } List<HarmonyMethod> fromMethod2 = HarmonyMethodExtensions.GetFromMethod(methodInfo2); containerAttributes.Merge(HarmonyMethod.Merge(fromMethod2)).CopyTo(postfix); } if (methodInfo3 != null) { if (!methodInfo3.IsStatic) { throw new ArgumentException("Patch method " + Extensions.GetID((MethodBase)methodInfo3, (string)null, (string)null, true, false, false) + " must be static"); } List<HarmonyMethod> fromMethod3 = HarmonyMethodExtensions.GetFromMethod(methodInfo3); containerAttributes.Merge(HarmonyMethod.Merge(fromMethod3)).CopyTo(transpiler); } if (methodInfo4 != null) { if (!methodInfo4.IsStatic) { throw new ArgumentException("Patch method " + Extensions.GetID((MethodBase)methodInfo4, (string)null, (string)null, true, false, false) + " must be static"); } List<HarmonyMethod> fromMethod4 = HarmonyMethodExtensions.GetFromMethod(methodInfo4); containerAttributes.Merge(HarmonyMethod.Merge(fromMethod4)).CopyTo(finalizer); } } internal static MethodBase GetOriginalMethod(HarmonyMethod attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } if (attribute.declaringType == null) { return MakeFailure("declaringType cannot be null"); } switch (attribute.methodType) { case MethodType.Normal: { if (string.IsNullOrEmpty(attribute.methodName)) { return MakeFailure("methodName can't be empty"); } if (attribute.methodName == ".ctor") { Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - MethodType.Constructor should be used instead of setting methodName to .ctor"); goto case MethodType.Constructor; } if (attribute.methodName == ".cctor") { Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - MethodType.StaticConstructor should be used instead of setting methodName to .cctor"); goto case MethodType.StaticConstructor; } if (attribute.methodName.StartsWith("get_") || attribute.methodName.StartsWith("set_")) { Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - MethodType.Getter and MethodType.Setter should be used instead adding get_ and set_ to property names"); } MethodInfo methodInfo = AccessTools.DeclaredMethod(attribute.declaringType, attribute.methodName, attribute.argumentTypes); if (methodInfo != null) { return methodInfo; } methodInfo = AccessTools.Method(attribute.declaringType, attribute.methodName, attribute.argumentTypes); if (methodInfo != null) { string text = GetPatchName(); object[] obj = new object[4] { attribute.methodName, null, null, null }; Type[] argumentTypes = attribute.argumentTypes; obj[1] = ((argumentTypes != null) ? argumentTypes.Length : 0); obj[2] = attribute.declaringType.FullDescription(); obj[3] = methodInfo.DeclaringType.FullDescription(); Logger.LogText(Logger.LogChannel.Warn, text + string.Format(" - Could not find method {0} with {1} parameters in type {2}, but it was found in base class of this type {3}", obj)); return methodInfo; } return MakeFailure("Could not find method " + attribute.methodName + " with " + attribute.argumentTypes.Description() + " parameters in type " + attribute.declaringType.FullDescription()); } case MethodType.Getter: { if (string.IsNullOrEmpty(attribute.methodName)) { return MakeFailure("methodName can't be empty"); } PropertyInfo propertyInfo2 = AccessTools.DeclaredProperty(attribute.declaringType, attribute.methodName); if (propertyInfo2 != null) { MethodInfo getMethod = propertyInfo2.GetGetMethod(nonPublic: true); if (getMethod == null) { return MakeFailure("Property " + attribute.methodName + " does not have a Getter"); } return getMethod; } propertyInfo2 = AccessTools.Property(attribute.declaringType, attribute.methodName); if (propertyInfo2 != null) { Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - Could not find property " + attribute.methodName + " in type " + attribute.declaringType.FullDescription() + ", but it was found in base class of this type: " + propertyInfo2.DeclaringType.FullDescription()); MethodInfo getMethod2 = propertyInfo2.GetGetMethod(nonPublic: true); if (getMethod2 == null) { return MakeFailure("Property " + attribute.methodName + " does not have a Getter"); } return getMethod2; } return MakeFailure("Could not find property " + attribute.methodName + " in type " + attribute.declaringType.FullDescription()); } case MethodType.Setter: { if (string.IsNullOrEmpty(attribute.methodName)) { return MakeFailure("methodName can't be empty"); } PropertyInfo propertyInfo = AccessTools.DeclaredProperty(attribute.declaringType, attribute.methodName); if (propertyInfo != null) { MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true); if (setMethod == null) { return MakeFailure("Property " + attribute.methodName + " does not have a Setter"); } return setMethod; } propertyInfo = AccessTools.Property(attribute.declaringType, attribute.methodName); if (propertyInfo != null) { Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - Could not find property " + attribute.methodName + " in type " + attribute.declaringType.FullDescription() + ", but it was found in base class of this type: " + propertyInfo.DeclaringType.FullDescription()); MethodInfo setMethod2 = propertyInfo.GetSetMethod(nonPublic: true); if (setMethod2 == null) { return MakeFailure("Property " + attribute.methodName + " does not have a Setter"); } return setMethod2; } return MakeFailure("Could not find property " + attribute.methodName + " in type " + attribute.declaringType.FullDescription()); } case MethodType.Constructor: { ConstructorInfo constructorInfo2 = AccessTools.DeclaredConstructor(attribute.declaringType, attribute.argumentTypes); if (constructorInfo2 != null) { return constructorInfo2; } return MakeFailure("Could not find constructor with " + attribute.argumentTypes.Description() + " parameters in type " + attribute.declaringType.FullDescription()); } case MethodType.StaticConstructor: { ConstructorInfo constructorInfo = AccessTools.GetDeclaredConstructors(attribute.declaringType).FirstOrDefault((ConstructorInfo c) => c.IsStatic); if (constructorInfo != null) { return constructorInfo; } return MakeFailure("Could not find static constructor in type " + attribute.declaringType.FullDescription()); } default: throw new ArgumentOutOfRangeException("methodType", attribute.methodType, "Unknown method type"); } string GetPatchName() { return attribute.method?.FullDescription() ?? "Unknown patch"; } MethodBase MakeFailure(string reason) { Logger.Log(Logger.LogChannel.Error, () => "Failed to process patch " + GetPatchName() + " - " + reason); return null; } } private T RunMethod<S, T>(T defaultIfNotExisting, params object[] parameters) { if (container == null) { return defaultIfNotExisting; } string name = typeof(S).Name.Replace("Harmony", ""); MethodInfo patchMethod = GetPatchMethod<S>(container, name); if (patchMethod != null) { if (typeof(T).IsAssignableFrom(patchMethod.ReturnType)) { object[] emptyTypes = Type.EmptyTypes; return (T)patchMethod.Invoke(null, emptyTypes); } object[] inputs = (parameters ?? new object[0]).Union(new object[1] { instance }).ToArray(); object[] parameters2 = AccessTools.ActualParameters(patchMethod, inputs); patchMethod.Invoke(null, parameters2); return defaultIfNotExisting; } return defaultIfNotExisting; } private void RunMethod<S>(params object[] parameters) { if (!(container == null)) { string name = typeof(S).Name.Replace("Harmony", ""); MethodInfo patchMethod = GetPatchMethod<S>(container, name); if (patchMethod != null) { object[] inputs = (parameters ?? new object[0]).Union(new object[1] { instance }).ToArray(); object[] parameters2 = AccessTools.ActualParameters(patchMethod, inputs); patchMethod.Invoke(null, parameters2); } } } private MethodInfo GetPatchMethod<T>(Type patchType, string name) { string attributeType = typeof(T).FullName; MethodInfo methodInfo = patchType.GetMethods(AccessTools.all).FirstOrDefault((MethodInfo m) => m.GetCustomAttributes(inherit: true).Any((object a) => a.GetType().FullName == attributeType)); if (methodInfo == null) { methodInfo = patchType.GetMethod(name, AccessTools.all); } return methodInfo; } private void GetPatches(Type patchType, out MethodInfo prefix, out MethodInfo postfix, out MethodInfo transpiler, out MethodInfo finalizer) { prefix = GetPatchMethod<HarmonyPrefix>(patchType, "Prefix"); postfix = GetPatchMethod<HarmonyPostfix>(patchType, "Postfix"); transpiler = GetPatchMethod<HarmonyTranspiler>(patchType, "Transpiler"); finalizer = GetPatchMethod<HarmonyFinalizer>(patchType, "Finalizer"); } } public class ReversePatcher { private readonly Harmony instance; private readonly MethodBase original; private readonly MethodInfo standin; private readonly ILHook ilHook; public ReversePatcher(Harmony instance, MethodBase original, MethodInfo standin) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Expected O, but got Unknown this.instance = instance; this.original = original; this.standin = standin; ilHook = new ILHook((MethodBase)standin, new Manipulator(ApplyReversePatch), new ILHookConfig { ManualApply = true }); } private void ApplyReversePatch(ILContext ctx) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Expected O, but got Unknown //IL_00ce: Unknown result type (might be due to invalid IL or missing references) DynamicMethodDefinition val = new DynamicMethodDefinition(original); ILManipulator iLManipulator = new ILManipulator(val.Definition.Body); ctx.Body.Variables.Clear(); Enumerator<VariableDefinition> enumerator = val.Definition.Body.Variables.GetEnumerator(); try { while (enumerator.MoveNext()) { VariableDefinition current = enumerator.Current; ctx.Body.Variables.Add(new VariableDefinition(ctx.Module.ImportReference(((VariableReference)current).VariableType))); } } finally { ((IDisposable)enumerator).Dispose(); } MethodInfo transpiler = GetTranspiler(standin); if (transpiler != null) { iLManipulator.AddTranspiler(transpiler); } iLManipulator.WriteTo(ctx.Body, standin); ctx.IL.Emit(OpCodes.Ret); } public void Patch(HarmonyReversePatchType type = HarmonyReversePatchType.Original) { if (original == null) { throw new NullReferenceException("Null method for " + instance.Id); } ilHook.Apply(); } private MethodInfo GetTranspiler(MethodInfo method) { string methodName = method.Name; Type declaringType = method.DeclaringType; List<MethodInfo> declaredMethods = AccessTools.GetDeclaredMethods(declaringType); Type ici = typeof(IEnumerable<CodeInstruction>); return declaredMethods.FirstOrDefault((MethodInfo m) => m.ReturnType == ici && m.Name.StartsWith("<" + methodName + ">")); } } public class CodeMatch { public string name; public List<OpCode> opcodes = new List<OpCode>(); public List<object> operands = new List<object>(); public List<Label> labels = new List<Label>(); public List<ExceptionBlock> blocks = new List<ExceptionBlock>(); public List<int> jumpsFrom = new List<int>(); public List<int> jumpsTo = new List<int>(); public Func<CodeInstruction, bool> predicate; public CodeMatch(OpCode? opcode = null, object operand = null, string name = null) { if (opcode.HasValue) { OpCode valueOrDefault = opcode.GetValueOrDefault(); if (true) { opcodes.Add(valueOrDefault); } } if (operand != null) { operands.Add(operand); } this.name = name; } public CodeMatch(CodeInstruction instruction, string name = null) : this(instruction.opcode, instruction.operand, name) { } public CodeMatch(Func<CodeInstruction, bool> predicate, string name = null) { this.predicate = predicate; this.name = name; } internal bool Matches(List<CodeInstruction> codes, CodeInstruction instruction) { if (predicate != null) { return predicate(instruction); } if (opcodes.Count > 0 && !opcodes.Contains(instruction.opcode)) { return false; } if (operands.Count > 0 && !operands.Contains(instruction.operand)) { return false; } if (labels.Count > 0 && !labels.Intersect(instruction.labels).Any()) { return false; } if (blocks.Count > 0 && !blocks.Intersect(instruction.blocks).Any()) { return false; } if (jumpsFrom.Count > 0 && !jumpsFrom.Select((int index) => codes[index].operand).OfType<Label>().Intersect(instruction.labels) .Any()) { return false; } if (jumpsTo.Count > 0) { object operand = instruction.operand; if (operand == null || operand.GetType() != typeof(Label)) { return false; } Label label = (Label)operand; IEnumerable<int> second = from idx in Enumerable.Range(0, codes.Count) where codes[idx].labels.Contains(label) select idx; if (!jumpsTo.Intersect(second).Any()) { return false; } } return true; } public override string ToString() { string text = "["; if (name != null) { text = text + name + ": "; } if (opcodes.Count > 0) { text = text + "opcodes=" + opcodes.Join() + " "; } if (operands.Count > 0) { text = text + "operands=" + operands.Join() + " "; } if (labels.Count > 0) { text = text + "labels=" + labels.Join() + " "; } if (blocks.Count > 0) { text = text + "blocks=" + blocks.Join() + " "; } if (jumpsFrom.Count > 0) { text = text + "jumpsFrom=" + jumpsFrom.Join() + " "; } if (jumpsTo.Count > 0) { text = text + "jumpsTo=" + jumpsTo.Join() + " "; } if (predicate != null) { text += "predicate=yes "; } return text.TrimEnd() + "]"; } } public class CodeMatcher { private readonly ILGenerator generator; private readonly List<CodeInstruction> codes = new List<CodeInstruction>(); private Dictionary<string, CodeInstruction> lastMatches = new Dictionary<string, CodeInstruction>(); private string lastError; private bool lastUseEnd; private CodeMatch[] lastCodeMatches; public int Pos { get; private set; } = -1; public int Length => codes.Count; public bool IsValid => Pos >= 0 && Pos < Length; public bool IsInvalid => Pos < 0 || Pos >= Length; public int Remaining => Length - Math.Max(0, Pos); public ref OpCode Opcode => ref codes[Pos].opcode; public ref object Operand => ref codes[Pos].operand; public ref List<Label> Labels => ref codes[Pos].labels; public ref List<ExceptionBlock> Blocks => ref codes[Pos].blocks; public CodeInstruction Instruction => codes[Pos]; private void FixStart() { Pos = Math.Max(0, Pos); } private void SetOutOfBounds(int direction) { Pos = ((direction > 0) ? Length : (-1)); } public CodeMatcher() { } public CodeMatcher(IEnumerable<CodeInstruction> instructions, ILGenerator generator = null) { this.generator = generator; codes = instructions.Select((CodeInstruction c) => new CodeInstruction(c)).ToList(); } public CodeMatcher Clone() { return new CodeMatcher(codes, generator) { Pos = Pos, lastMatches = lastMatches, lastError = lastError, lastUseEnd = lastUseEnd, lastCodeMatches = lastCodeMatches }; } public CodeInstruction InstructionAt(int offset) { return codes[Pos + offset]; } public List<CodeInstruction> Instructions() { return codes; } public IEnumerable<CodeInstruction> InstructionEnumeration() { return codes.AsEnumerable(); } public List<CodeInstruction> Instructions(int count) { return (from c in codes.GetRange(Pos, count) select new CodeInstruction(c)).ToList(); } public List<CodeInstruction> InstructionsInRange(int start, int end) { List<CodeInstruction> list = codes; if (start > end) { int num = start; start = end; end = num; } list = list.GetRange(start, end - start + 1); return list.Select((CodeInstruction c) => new CodeInstruction(c)).ToList(); } public List<CodeInstruction> InstructionsWithOffsets(int startOffset, int endOffset) { return InstructionsInRange(Pos + startOffset, Pos + endOffset); } public List<Label> DistinctLabels(IEnumerable<CodeInstruction> instructions) { return instructions.SelectMany((CodeInstruction instruction) => instruction.labels).Distinct().ToList(); } public bool ReportFailure(MethodBase method, Action<string> logger) { if (IsValid) { return false; } string arg = lastError ?? "Unexpected code"; logger($"{arg} in {method}"); return true; } public CodeMatcher SetInstruction(CodeInstruction instruction) { codes[Pos] = instruction; return this; } public CodeMatcher SetInstructionAndAdvance(CodeInstruction instruction) { SetInstruction(instruction); Pos++; return this; } public CodeMatcher Set(OpCode opcode, object operand) { Opcode = opcode; Operand = operand; return this; } public CodeMatcher SetAndAdvance(OpCode opcode, object operand) { Set(opcode, operand); Pos++; return this; } public CodeMatcher SetOpcodeAndAdvance(OpCode opcode) { Opcode = opcode; Pos++; return this; } public CodeMatcher SetOperandAndAdvance(object operand) { Operand = operand; Pos++; return this; } public CodeMatcher CreateLabel(out Label label) { label = generator.DefineLabel(); Labels.Add(label); return this; } public CodeMatcher CreateLabelAt(int position, out Label label) { label = generator.DefineLabel(); AddLabelsAt(position, new Label[1] { label }); return this; } public CodeMatcher AddLabels(IEnumerable<Label> labels) { Labels.AddRange(labels); return this; } public CodeMatcher AddLabelsAt(int position, IEnumerable<Label> labels) { codes[position].labels.AddRange(labels); return this; } public CodeMatcher SetJumpTo(OpCode opcode, int destination, out Label label) { CreateLabelAt(destination, out label); Set(opcode, label); return this; } public CodeMatcher Insert(params CodeInstruction[] instructions) { codes.InsertRange(Pos, instructions); return this; } public CodeMatcher Insert(IEnumerable<CodeInstruction> instructions) { codes.InsertRange(Pos, instructions); return this; } public CodeMatcher InsertBranch(OpCode opcode, int destination) { CreateLabelAt(destination, out var label); codes.Insert(Pos, new CodeInstruction(opcode, label)); return this; } public CodeMatcher InsertAndAdvance(params CodeInstruction[] instructions) { foreach (CodeInstruction codeInstruction in instructions) { Insert(codeInstruction); Pos++; } return this; } public CodeMatcher InsertAndAdvance(IEnumerable<CodeInstruction> instructions) { foreach (CodeInstruction instruction in instructions) { InsertAndAdvance(instruction); } return this; } public CodeMatcher InsertBranchAndAdvance(OpCode opcode, int destination) { InsertBranch(opcode, destination); Pos++; return this; } public CodeMatcher RemoveInstruction() { codes.RemoveAt(Pos); return this; } public CodeMatcher RemoveInstructions(int count) { codes.RemoveRange(Pos, count); return this; } public CodeMatcher RemoveInstructionsInRange(int start, int end) { if (start > end) { int num = start; start = end; end = num; } codes.RemoveRange(start, end - start + 1); return this; } public CodeMatcher RemoveInstructionsWithOffsets(int startOffset, int endOffset) { RemoveInstructionsInRange(Pos + startOffset, Pos + endOffset); return this; } public CodeMatcher Advance(int offset) { Pos += offset; if (!IsValid) { SetOutOfBounds(offset); } return this; } public CodeMatcher Start() { Pos = 0; return this; } public CodeMatcher End() { Pos = Length - 1; return this; } public CodeMatcher SearchForward(Func<CodeInstruction, bool> predicate) { return Search(predicate, 1); } public CodeMatcher SearchBack(Func<CodeInstruction, bool> predicate) { return Search(predicate, -1); } private CodeMatcher Search(Func<CodeInstruction, bool> predicate, int direction) { FixStart(); while (IsValid && !predicate(Instruction)) { Pos += direction; } lastError = (IsInvalid ? $"Cannot find {predicate}" : null); return this; } public CodeMatcher MatchForward(bool useEnd, params CodeMatch[] matches) { return Match(matches, 1, useEnd); } public CodeMatcher MatchBack(bool useEnd, params CodeMatch[] matches) { return Match(matches, -1, useEnd); } private CodeMatcher Match(CodeMatch[] matches, int direction, bool useEnd) { FixStart(); while (IsValid) { lastUseEnd = useEnd; lastCodeMatches = matches; if (MatchSequence(Pos, matches)) { if (useEnd) { Pos += matches.Count() - 1; } break; } Pos += direction; } lastError = (IsInvalid ? ("Cannot find " + matches.Join()) : null); return this; } public CodeMatcher Repeat(Action<CodeMatcher> matchAction, Action<string> notFoundAction = null) { int num = 0; if (lastCodeMatches == null) { throw new InvalidOperationException("No previous Match operation - cannot repeat"); } while (IsValid) { matchAction(this); MatchForward(lastUseEnd, lastCodeMatches); num++; } lastCodeMatches = null; if (num == 0) { notFoundAction?.Invoke(lastError); } return this; } public CodeInstruction NamedMatch(string name) { return lastMatches[name]; } private bool MatchSequence(int start, CodeMatch[] matches) { if (start < 0) { return false; } lastMatches = new Dictionary<string, CodeInstruction>(); foreach (CodeMatch codeMatch in matches) { if (start >= Length || !codeMatch.Matches(codes, codes[start])) { return false; } if (codeMatch.name != null) { lastMatches.Add(codeMatch.name, codes[start]); } start++; } return true; } } public static class CodeInstructionExtensions { private static readonly HashSet<OpCode> LoadVarCodes = new HashSet<OpCode> { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3, OpCodes.Ldloc, OpCodes.Ldloca, OpCodes.Ldloc_S, OpCodes.Ldloca_S }; private static readonly HashSet<OpCode> StoreVarCodes = new HashSet<OpCode> { OpCodes.Stloc_0, OpCodes.Stloc_1, OpCodes.Stloc_2, OpCodes.Stloc_3, OpCodes.Stloc, OpCodes.Stloc_S }; private static readonly HashSet<OpCode> BranchCodes = new HashSet<OpCode> { OpCodes.Br_S, OpCodes.Brfalse_S, OpCodes.Brtrue_S, OpCodes.Beq_S, OpCodes.Bge_S, OpCodes.Bgt_S, OpCodes.Ble_S, OpCodes.Blt_S, OpCodes.Bne_Un_S, OpCodes.Bge_Un_S, OpCodes.Bgt_Un_S, OpCodes.Ble_Un_S, OpCodes.Blt_Un_S, OpCodes.Br, OpCodes.Brfalse, OpCodes.Brtrue, OpCodes.Beq, OpCodes.Bge, OpCodes.Bgt, OpCodes.Ble, OpCodes.Blt, OpCodes.Bne_Un, OpCodes.Bge_Un, OpCodes.Bgt_Un, OpCodes.Ble_Un, OpCodes.Blt_Un }; private static readonly HashSet<OpCode> ConstantLoadingCodes = new HashSet<OpCode> { OpCodes.Ldc_I4_M1, OpCodes.Ldc_I4_0, OpCodes.Ldc_I4_1, OpCodes.Ldc_I4_2, OpCodes.Ldc_I4_3, OpCodes.Ldc_I4_4, OpCodes.Ldc_I4_5, OpCodes.Ldc_I4_6, OpCodes.Ldc_I4_7, OpCodes.Ldc_I4_8, OpCodes.Ldc_I4, OpCodes.Ldc_I4_S, OpCodes.Ldc_I8, OpCodes.Ldc_R4, OpCodes.Ldc_R8 }; public static bool OperandIs(this CodeInstruction code, object value) { if (value == null) { throw new ArgumentNullException("value"); } if (code.operand == null) { return false; } Type type = value.GetType(); Type type2 = code.operand.GetType(); if (AccessTools.IsInteger(type) && AccessTools.IsNumber(type2)) { return Convert.ToInt64(code.operand) == Convert.ToInt64(value); } if (AccessTools.IsFloatingPoint(type) && AccessTools.IsNumber(type2)) { return Convert.ToDouble(code.operand) == Convert.ToDouble(value); } return object.Equals(code.operand, value); } public static bool Is(this CodeInstruction code, OpCode opcode, object operand) { return code.opcode == opcode && code.OperandIs(operand); } public static bool IsLdarg(this CodeInstruction code, int? n = null) { if ((!n.HasValue || n.Value == 0) && code.opcode == OpCodes.Ldarg_0) { return true; } if ((!n.HasValue || n.Value == 1) && code.opcode == OpCodes.Ldarg_1) { return true; } if ((!n.HasValue || n.Value == 2) && code.opcode == OpCodes.Ldarg_2) { return true; } if ((!n.HasValue || n.Value == 3) && code.opcode == OpCodes.Ldarg_3) { return true; } if (code.opcode == OpCodes.Ldarg && (!n.HasValue || n.Value == Convert.ToInt32(code.operand))) { return true; } if (code.opcode == OpCodes.Ldarg_S && (!n.HasValue || n.Value == Convert.ToInt32(code.operand))) { return true; } return false; } public static bool IsLdarga(this CodeInstruction code, int? n = null) { if (code.opcode != OpCodes.Ldarga && code.opcode != OpCodes.Ldarga_S) { return false; } return !n.HasValue || n.Value == Convert.ToInt32(code.operand); } public static bool IsStarg(this CodeInstruction code, int? n = null) { if (code.opcode != OpCodes.Starg && code.opcode != OpCodes.Starg_S) { return false; } return !n.HasValue || n.Value == Convert.ToInt32(code.operand); } public static bool IsLdloc(this CodeInstruction code, LocalBuilder variable = null) { if (!LoadVarCodes.Contains(code.opcode)) { return false; } return variable == null || object.Equals(variable, code.operand); } public static bool IsStloc(this CodeInstruction code, LocalBuilder variable = null) { if (!StoreVarCodes.Contains(code.opcode)) { return false; } return variable == null || object.Equals(variable, code.operand); } public static bool Branches(this CodeInstruction code, out Label? label) { if (BranchCodes.Contains(code.opcode)) { label = (Label)code.operand; return true; } label = null; return false; } public static bool Calls(this CodeInstruction code, MethodInfo method) { if (method == null) { throw new ArgumentNullException("method"); } if (code.opcode != OpCodes.Call && code.opcode != OpCodes.Callvirt) { return false; } return object.Equals(code.operand, method); } public static bool LoadsConstant(this CodeInstruction code) { return ConstantLoadingCodes.Contains(code.opcode); } public static bool LoadsConstant(this CodeInstruction code, long number) { OpCode opcode = code.opcode; if (number == -1 && opcode == OpCodes.Ldc_I4_M1) { return true; } if (number == 0L && opcode == OpCodes.Ldc_I4_0) { return true; } if (number == 1 && opcode == OpCodes.Ldc_I4_1) { return true; } if (number == 2 && opcode == OpCodes.Ldc_I4_2) { return true; } if (number == 3 && opcode == OpCodes.Ldc_I4_3) { return true; } if (number == 4 && opcode == OpCodes.Ldc_I4_4) { return true; } if (number == 5 && opcode == OpCodes.Ldc_I4_5) { return true; } if (number == 6 && opcode == OpCodes.Ldc_I4_6) { return true; } if (number == 7 && opcode == OpCodes.Ldc_I4_7) { return true; } if (number == 8 && opcode == OpCodes.Ldc_I4_8) { return true; } if (opcode != OpCodes.Ldc_I4 && opcode != OpCodes.Ldc_I4_S && opcode != OpCodes.Ldc_I8) { return false; } return Convert.ToInt64(code.operand) == number; } public static bool LoadsConstant(this CodeInstruction code, double number) { if (code.opcode != OpCodes.Ldc_R4 && code.opcode != OpCodes.Ldc_R8) { return false; } double num = Convert.ToDouble(code.operand); return num == number; } public static bool LoadsConstant(this CodeInstruction code, Enum e) { return code.LoadsConstant(Convert.ToInt64(e)); } public static bool LoadsField(this CodeInstruction code, FieldInfo field, bool byAddress = false) { if (field == null) { throw new ArgumentNullException("field"); } OpCode opCode = (field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld); if (!byAddress && code.opcode == opCode && object.Equals(code.operand, field)) { return true; } OpCode opCode2 = (field.IsStatic ? OpCodes.Ldsflda : OpCodes.Ldflda); if (byAddress && code.opcode == opCode2 && object.Equals(code.operand, field)) { return true; } return false; } public static bool StoresField(this CodeInstruction code, FieldInfo field) { if (field == null) { throw new ArgumentNullException("field"); } OpCode opCode = (field.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld); return code.opcode == opCode && object.Equals(code.operand, field); } public static CodeInstruction WithLabels(this CodeInstruction code, params Label[] labels) { code.labels.AddRange(labels); return code; } public static CodeInstruction WithLabels(this CodeInstruction code, IEnumerable<Label> labels) { code.labels.AddRange(labels); return code; } public static List<Label> ExtractLabels(this CodeInstruction code) { List<Label> result = new List<Label>(code.labels); code.labels.Clear(); return result; } public static CodeInstruction MoveLabelsTo(this CodeInstruction code, CodeInstruction other) { other.WithLabels(code.ExtractLabels()); return code; } public static CodeInstruction MoveLabelsFrom(this CodeInstruction code, CodeInstruction other) { return code.WithLabels(other.ExtractLabels()); } public static CodeInstruction WithBlocks(this CodeInstruction code, params ExceptionBlock[] blocks) { code.blocks.AddRange(blocks); return code; } public static CodeInstruction WithBlocks(this CodeInstruction code, IEnumerable<ExceptionBlock> blocks) { code.blocks.AddRange(blocks); return code; } public static List<ExceptionBlock> ExtractBlocks(this CodeInstruction code) { List<ExceptionBlock> result = new List<ExceptionBlock>(code.blocks); code.blocks.Clear(); return result; } public static CodeInstruction MoveBlocksTo(this CodeInstruction code, CodeInstruction other) { other.WithBlocks(code.ExtractBlocks()); return code; } public static CodeInstruction MoveBlocksFrom(this CodeInstruction code, CodeInstruction other) { return code.WithBlocks(other.ExtractBlocks()); } } public static class CollectionExtensions { public static void Do<T>(this IEnumerable<T> sequence, Action<T> action) { if (sequence != null) { IEnumerator<T> enumerator = sequence.GetEnumerator(); while (enumerator.MoveNext()) { action(enumerator.Current); } } } public static void DoIf<T>(this IEnumerable<T> sequence, Func<T, bool> condition, Action<T> action) { sequence.Where(condition).Do(action); } public static IEnumerable<T> AddItem<T>(this IEnumerable<T> sequence, T item) { return (sequence ?? Enumerable.Empty<T>()).Concat(new T[1] { item }); } public static T[] AddToArray<T>(this T[] sequence, T item) { return sequence.AddItem(item).ToArray(); } public static T[] AddRangeToArray<T>(this T[] sequence, T[] items) { return (sequence ?? Enumerable.Empty<T>()).Concat(items).ToArray(); } } public static class GeneralExtensions { public static string Join<T>(this IEnumerable<T> enumeration, Func<T, string> converter = null, string delimiter = ", ") { if (converter == null) { converter = (T t) => t.ToString(); } return enumeration.Aggregate("", (string prev, T curr) => prev + ((prev != "") ? delimiter : "") + converter(curr)); } public static string Description(this Type[] parameters) { if (parameters == null) { return "NULL"; } return "(" + parameters.Join((Type p) => p.FullDescription()) + ")"; } public static string FullDescription(this Type type) { if (type == null) { return "null"; } string text = type.Namespace; if (!string.IsNullOrEmpty(text)) { text += "."; } string text2 = text + type.Name; if (type.IsGenericType) { text2 += "<"; Type[] genericArguments = type.GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { if (!text2.EndsWith("<", StringComparison.Ordinal)) { text2 += ", "; } text2 += genericArguments[i].FullDescription(); } text2 += ">"; } return text2; } public static string FullDescription(this MethodBase method) { if (method == null) { return "null"; } Type[] parameters = (from p in method.GetParameters() select p.ParameterType).ToArray(); Type returnedType = AccessTools.GetReturnedType(method); return returnedType.FullDescription() + " " + method.DeclaringType.FullDescription() + "." + method.Name + parameters.Description(); } public static Type[] Types(this ParameterInfo[] pinfo) { return pinfo.Select((ParameterInfo pi) => pi.ParameterType).ToArray(); } public static T GetValueSafe<S, T>(this Dictionary<S, T> dictionary, S key) { if (dictionary.TryGetValue(key, out var value)) { return value; } return default(T); } public static T GetTypedValue<T>(this Dictionary<string, object> dictionary, string key) { if (!dictionary.TryGetValue(key, out var value) || !(value is T result)) { return default(T); } return result; } } public static class SymbolExtensions { public static MethodInfo GetMethodInfo(Expression<Action> expression) { return GetMethodInfo((LambdaExpression)expression); } public static MethodInfo GetMethodInfo<T>(Expression<Action<T>> expression) { return GetMethodInfo((LambdaExpression)expression); } public static MethodInfo GetMethodInfo<T, TResult>(Expression<Func<T, TResult>> expression) { return GetMethodInfo((LambdaExpression)expression); } public static MethodInfo GetMethodInfo(LambdaExpression expression) { if (!(expression.Body is MethodCallExpression methodCallExpression)) { throw new ArgumentException("Invalid Expression. Expression should consist of a Method call only."); } MethodInfo method = methodCallExpression.Method; if (method == null) { throw new MemberNotFoundException($"Cannot find method for expression {expression}"); } return method; } } [Obsolete("Use HarmonyFileLog instead", true)] public static class FileLog { public static string logPath; public static char indentChar; public static int indentLevel; private static List<string> buffer; static FileLog() { indentChar = '\t'; buffer = new List<string>(); logPath = $"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}{Path.DirectorySeparatorChar}harmony.log.txt"; } private static string IndentString() { return new string(indentChar, indentLevel); } public static void ChangeIndent(int delta) { indentLevel = Math.Max(0, indentLevel + delta); } public static void LogBuffered(string str) { lock (logPath) { buffer.Add(IndentString() + str); } } public static void LogBuffered(List<string> strings) { lock (logPath) { buffer.AddRange(strings); } } public static List<string> GetBuffer(bool clear) { lock (logPath) { List<string> result = buffer; if (clear) { buffer = new List<string>(); } return result; } } public static void SetBuffer(List<string> buffer) { lock (logPath) { FileLog.buffer = buffer; } } public static void FlushBuffer() { lock (logPath) { if (buffer.Count <= 0) { return; } using (StreamWriter streamWriter = File.AppendText(logPath)) { foreach (string item in buffer) { streamWriter.WriteLine(item); } } buffer.Clear(); } } public static void Log(string str) { lock (logPath) { using StreamWriter streamWriter = File.AppendText(logPath); streamWriter.WriteLine(IndentString() + str); } } public static void Reset() { lock (logPath) { string path = $"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}{Path.DirectorySeparatorChar}harmony.log.txt"; File.Delete(path); } } public unsafe static void LogBytes(long ptr, int len) { lock (logPath) { byte* ptr2 = (byte*)ptr; string text = ""; for (int i = 1; i <= len; i++) { if (text == "") { text = "# "; } text = $"{text}{*ptr2:X2} "; if (i > 1 || len == 1) { if (i % 8 == 0 || i == len) { Log(text); text = ""; } else if (i % 4 == 0) { text += " "; } } ptr2++; } byte[] destination = new byte[len]; Marshal.Copy((IntPtr)ptr, destination, 0, len); MD5 mD = MD5.Create(); byte[] array = mD.ComputeHash(destination); StringBuilder stringBuilder = new StringBuilder(); for (int j = 0; j < array.Length; j++) { stringBuilder.Append(array[j].ToString("X2")); } Log($"HASH: {stringBuilder}"); } } } public static class AccessTools { public delegate ref U FieldRef<T, U>(T obj = default(T)); public delegate ref F FieldRef<F>(); public static BindingFlags all = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty; public static BindingFlags allDeclared = all | BindingFlags.DeclaredOnly; public static bool IsMonoRuntime { get; } = Type.GetType("Mono.Runtime") != null; public static Type TypeByName(string name) { if (name == null) { throw new ArgumentNullException("name"); } Type type = Type.GetType(name, throwOnError: false); if (type == null) { type = (from assembly in AppDomain.CurrentDomain.GetAssemblies() select assembly.GetType(name)).FirstOrDefault((Type t) => t != null); } if (type == null) { type = AppDomain.CurrentDomain.GetAssemblies().SelectMany((Assembly x) => x.GetTypes()).FirstOrDefault((Type x) => x.Name == name); } if (type == null) { Logger.Log(Logger.LogChannel.Warn, () => "AccessTools.TypeByName: Could not find type named " + name); } return type; } public static T FindIncludingBaseTypes<T>(Type type, Func<Type, T> func) where T : class { while (true) { T val = func(type); if (val != null) { return val; } if (type == typeof(object)) { break; } type = type.BaseType; } return null; } public static T FindIncludingInnerTypes<T>(Type type, Func<Type, T> func) where T : class { T val = func(type); if (val != null) { return val; } Type[] nestedTypes = type.GetNestedTypes(all); foreach (Type type2 in nestedTypes) { val = FindIncludingInnerTypes(type2, func); if (val != null) { break; } } return val; } public static FieldInfo DeclaredField(Type type, string name) { if (type == null) { throw new ArgumentNullException("type"); } if (name == null) { throw new ArgumentNullException("name"); } FieldInfo field = type.GetField(name, allDeclared); if (field == null) { Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.DeclaredField: Could not find field for type {type} and name {name}"); } return field; } public static FieldInfo Field(Type type, string name) { if (type == null) { throw new ArgumentNullException("type"); } if (name == null) { throw new ArgumentNullException("name"); } FieldInfo fieldInfo = FindIncludingBaseTypes(type, (Type t) => t.GetField(name, all)); if (fieldInfo == null) { Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.Field: Could not find field for type {type} and name {name}"); } return fieldInfo; } public static FieldInfo DeclaredField(Type type, int idx) { if (type == null) { throw new ArgumentNullException("type"); } FieldInfo fieldInfo = GetDeclaredFields(type).ElementAtOrDefault(idx); if (fieldInfo == null) { Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.DeclaredField: Could not find field for type {type} and idx {idx}"); } return fieldInfo; } public static PropertyInfo DeclaredProperty(Type type, string name) { if (type == null) { throw new ArgumentNullException("type"); } if (name == null) { throw new ArgumentNullException("name"); } try { PropertyInfo property = type.GetProperty(name, allDeclared); if (property == null) { Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.DeclaredProperty: Could not find property for type {type} and name {name}"); } return property; } catch (AmbiguousMatchException inner) { throw new AmbiguousMatchException($"Ambiguous match for property {type}::{name}", inner); } } public static MethodInfo DeclaredPropertyGetter(Type type, string name) { return DeclaredProperty(type, name)?.GetGetMethod(nonPublic: true); } public static MethodInfo DeclaredPropertySetter(Type type, string name) { return DeclaredProperty(type, name)?.GetSetMethod(nonPublic: true); } public static PropertyInfo Property(Type type, string name) { if (type == null) { throw new ArgumentNullException("type"); } if (name == null) { throw new ArgumentNullException("name"); } PropertyInfo propertyInfo = FindIncludingBaseTypes(type, (Type t) => t.GetProperty(name, all)); if (propertyInfo == null) { Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.Property: Could not find property for type {type} and name {name}"); } return propertyInfo; } public static MethodInfo PropertyGetter(Type type, string name) { return Property(type, name)?.GetGetMethod(nonPublic: true); } public static MethodInfo PropertySetter(Type type, string name) { return Property(type, name)?.GetSetMethod(nonPublic: true); } public static MethodInfo DeclaredMethod(Type type, string name, Type[] parameters = null, Type[] generics = null) { if (type == null) { throw new ArgumentNullException("type"); } if (name == null) { throw new ArgumentNullException("name"); } ParameterModifier[] modifiers = new ParameterModifier[0]; try { MethodInfo methodInfo = ((parameters != null) ? type.GetMethod(name, allDeclared, null, parameters, modifiers) : type.GetMethod(name, allDeclared)); if (methodInfo == null) { Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.DeclaredMethod: Could not find method for type {type} and name {name} and parameters {parameters?.Description()}"); return null; } if (generics != null) { methodInfo = methodInfo.MakeGenericMethod(generics); } return methodInfo; } catch (AmbiguousMatchException inner) { string text = ""; if (generics != null) { text = "<" + string.Join(", ", generics.Select((Type g) => g.FullName).ToArray()) + ">"; } string text2 = ""; if (parameters != null) { text2 = string.Join(", ", parameters.Select((Type p) => p.FullName).ToArray()); } throw new AmbiguousMatchException($"Ambiguous match for {type}::{name}{text}(${text2})", inner); } } public static MethodInfo Method(Type type, string name, Type[] parameters = null, Type[] generics = null) { if (type == null) { throw new ArgumentNullException("type"); } if (name == null) { throw new ArgumentNullException("name"); } try { ParameterModifier[] modifiers = new ParameterModifier[0]; MethodInfo methodInfo; if (parameters == null) { try { methodInfo = FindIncludingBaseTypes(type, (Type t) => t.GetMethod(name, all)); } catch (AmbiguousMatchException inner) { methodInfo = FindIncludingBaseTypes(type, (Type t) => t.GetMethod(name, all, null, new Type[0], modifiers)); if (methodInfo == null) { throw new AmbiguousMatchException($"Ambiguous match for {type}:{name}", inner); } } } else { methodInfo = FindIncludingBaseTypes(type, (Type t) => t.GetMethod(name, all, null, parameters, modifiers)); } if (methodInfo == null) { Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.Method: Could not find method for type {type} and name {name} and parameters {parameters?.Description()}"); return null; } if (generics != null) { methodInfo = methodInfo.MakeGenericMethod(generics); } return methodInfo; } catch (AmbiguousMatchException inner2) { string text = ""; if (generics != null) { text = "<" + string.Join(", ", generics.Select((Type g) => g.FullName).ToArray()) + ">"; } string text2 = ""; if (parameters != null) { text2 = string.Join(", ", parameters.Select((Type p) => p.FullName).ToArray()); } throw new AmbiguousMatchException($"Ambiguous match for {type}::{name}{text}(${text2})", inner2); } } public static MethodInfo Method(string typeColonMethodname, Type[] parameters = null, Type[] generics = null) { if (typeColonMethodname == null) { throw new ArgumentNullException("typeColonMethodname"); } string[] array = typeColonMethodname.Split(':'); if (array.Length != 2) { throw new ArgumentException("Method must be specified as 'Namespace.Type1.Type2:MethodName", "typeColonMethodname"); } Type type = TypeByName(array[0]); return Method(type, array[1], parameters, generics); } public static List<string> GetMethodNames(Type type) { if (type == null) { throw new ArgumentNullException("type"); } return (from m in GetDeclaredMethods(type) select m.Name).ToList(); } public static List<string> GetMethodNames(object instance) { if (instance == null) { throw new ArgumentNullException("instance"); } return GetMethodNames(instance.GetType()); } public static List<string> GetFieldNames(Type type) { if (type == null) { throw new ArgumentNullException("type"); } return (from f in GetDeclaredFields(type) select f.Name).ToList(); } public static List<string> GetFieldNames(object instance) { if (instance == null) { throw new ArgumentNullException("instance"); } return GetFieldNames(instance.GetType()); } public static List<string> GetPropertyNames(Type type) { if (type == null) { throw new ArgumentNullException("type"); } return (from f in GetDeclaredProperties(type) select f.Name).ToList(); } public static List<string> GetPropertyNames(object instance) { if (instance == null) { throw new ArgumentNullException("instance"); } return GetPropertyNames(instance.GetType()); } public static Type GetUnderlyingType(this MemberInfo member) { if (member == null) { throw new ArgumentNullException("member"); } return member.MemberType switch { MemberTypes.Event => ((EventInfo)member).EventHandlerType, MemberTypes.Field => ((FieldInfo)member).FieldType, MemberTypes.Method => ((MethodInfo)member).ReturnType, MemberTypes.Property => ((PropertyInfo)member).PropertyType, _ => throw new ArgumentException("Member must be of type EventInfo, FieldInfo, MethodInfo, or PropertyInfo"), }; } public static ConstructorInfo DeclaredConstructor(Type type, Type[] parameters = null) { if (type == null) { throw new ArgumentNullException("type"); } if (parameters == null) { parameters = new Type[0]; } return type.GetConstructor(allDeclared, null, parameters, new ParameterModifier[0]); } public static ConstructorInfo DeclaredConstructor(Type type, Type[] parameters, bool searchForStatic) { if (type == null) { throw new ArgumentNullException("type"); } if (parameters == null) { parameters = new Type[0]; } BindingFlags bindingFlags = (searchForStatic ? BindingFlags.Instance : BindingFlags.Static); return type.GetConstructor(allDeclared & ~bindingFlags, null, parameters, new ParameterModifier[0]); } public static ConstructorInfo Constructor(Type type, Type[] parameters = null) { if (type == null) { throw new ArgumentNullException("type"); } if (parameters == null) { parameters = new Type[0]; } return FindIncludingBaseTypes(type, (Type t) => t.GetConstructor(all, null, parameters, new ParameterModifier[0])); } public static ConstructorInfo Constructor(Type type, Type[] parameters, bool searchForStatic) { if (type == null) { throw new ArgumentNullException("type"); } if (parameters == null) { parameters = new Type[0]; } BindingFlags exclude = (searchForStatic ? BindingFlags.Instance : BindingFlags.Static); return FindIncludingBaseTypes(type, (Type t) => t.GetConstructor(all & ~exclude, null, parameters, new ParameterModifier[0])); } public static List<ConstructorInfo> GetDeclaredConstructors(Type type) { if (type == null) { throw new ArgumentNullException("type"); } return (from method in type.GetConstructors(allDeclared) where method.DeclaringType == type select method).ToList(); } public static List<ConstructorInfo> GetDeclaredConstructors(Type type, bool? searchForStatic) { if (type == null) { throw new ArgumentNullException("type"); } BindingFlags bindingFlags = BindingFlags.Default; if (searchForStatic.HasValue) { bindingFlags = (searchForStatic.Value ? BindingFlags.Instance : BindingFlags.Static); } return (from method in type.GetConstructors(allDeclared & ~bindingFlags) where method.DeclaringType == type select method).ToList(); } public static List<MethodInfo> GetDeclaredMethods(Type type) { if (type == null) { throw new ArgumentNullException("type"); } return type.GetMethods(allDeclared).ToList(); } public static List<PropertyInfo> GetDeclaredProperties(Type type) { if (type == null) { throw new ArgumentNullException("type"); } return type.GetProperties(allDeclared).ToList(); } public static List<FieldInfo> GetDeclaredFields(Type type) { if (type == null) { throw new ArgumentNullException("type"); } return type.GetFields(allDeclared).ToList(); } public static Type GetReturnedType(MethodBase methodOrConstructor) { if (methodOrConstructor == null) { throw new ArgumentNullException("methodOrConstructor"); } if (methodOrConstructor is ConstructorInfo) { return typeof(void); } return ((MethodInfo)methodOrConstructor).ReturnType; } public static Type Inner(Type type, string name) { if (type == null) { throw new ArgumentNullException("type"); } if (name == null) { throw new ArgumentNullException("name"); } return FindIncludingBaseTypes(type, (Type t) => t.GetNestedType(name, all)); } public static Type FirstInner(Type type, Func<Type, bool> predicate) { if (type == null) { throw new ArgumentNullException("type"); } if (predicate == null) { throw new ArgumentNullException("predicate"); } return type.GetNestedTypes(all).FirstOrDefault(predicate); } public static MethodInfo FirstMethod(Type type, Func<MethodInfo, bool> predicate) { if (type == null) { throw new ArgumentNullException("type"); } if (predicate == null) { throw new ArgumentNullException("predicate"); } return type.GetMethods(allDeclared).FirstOrDefault(predicate); } public static ConstructorInfo FirstConstructor(Type type, Func<ConstructorInfo, bool> predicate) { if (type == null) { throw new ArgumentNullException("type"); } if (predicate == null) { throw new ArgumentNullException("predicate"); } return type.GetConstructors(allDeclared).FirstOrDefault(predicate); } public static PropertyInfo FirstProperty(Type type, Func<PropertyInfo, bool> predicate) { if (type == null) { throw new ArgumentNullException("type"); } if (predicate == null) { throw new ArgumentNullException("predicate"); } return type.GetProperties(allDeclared).FirstOrDefault(predicate); } public static Type[] GetTypes(object[] parameters) { if (parameters == null) { return new Type[0]; } return parameters.Select((object p) => (p == null) ? typeof(object) : p.GetType()).ToArray(); } public static object[] ActualParameters(MethodBase method, object[] inputs) { if (method == null) { throw new ArgumentNullException("method"); } if (inputs == null) { throw new ArgumentNullException("inputs"); } List<Type> inputTypes = inputs.Select((object obj) => obj?.GetType()).ToList(); return (from p in method.GetParameters() select p.ParameterType).Select(delegate(Type pType) { int num = inputTypes.FindIndex((Type inType) => inputTypes != null && pType.IsAssignableFrom(inType)); return (num >= 0) ? inputs[num] : GetDefaultValue(pType); }).ToArray(); } public static FieldRef<T, U> FieldRefAccess<T, U>(string fieldName) { FieldInfo field = typeof(T).GetField(fieldName, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic); return FieldRefAccess<T, U>(field); } public static FieldRef<T, U> FieldRefAccess<T, U>(FieldInfo fieldInfo) { //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Expected O, but got Unknown if (fieldInfo == null) { throw new ArgumentNullException("fieldInfo"); } if (!typeof(U).IsAssignableFrom(fieldInfo.FieldType)) { throw new ArgumentException("FieldInfo type does not match FieldRefAccess return type."); } if (typeof(T) != typeof(object) && (fieldInfo.DeclaringType == null || !fieldInfo.DeclaringType.IsAssignableFrom(typeof(T)))) { throw new MissingFieldException(typeof(T).Name, fieldInfo.Name); } DynamicMethodDefinition val = new DynamicMethodDefinition("__refget_" + typeof(T).Name + "_fi_" + fieldInfo.Name, typeof(U).MakeByRefType(), new Type[1] { typeof(T) }); ILGenerator iLGenerator = val.GetILGenerator(); iLGenerator.Emit(OpCodes.Ldarg_0); iLGenerator.Emit(OpCodes.Ldflda, fieldInfo); iLGenerator.Emit(OpCodes.Ret); return Extensions.CreateDelegate<FieldRef<T, U>>((MethodBase)val.Generate()); } public static ref U FieldRefAccess<T, U>(T instance, string fieldName) { return ref FieldRefAccess<T, U>(fieldName)(instance); } public static FieldRef<object, F> FieldRefAccess<F>(Type type, string fieldName) { return FieldRefAccess<object, F>(Field(type, fieldName)); } public static ref F StaticFieldRefAccess<T, F>(string fieldName) { return ref StaticFieldRefAccess<F>(typeof(T), fieldName); } public static ref F StaticFieldRefAccess<T, F>(FieldInfo fieldInfo) { return ref StaticFieldRefAccess<F>(fieldInfo)(); } public static FieldRef<F> StaticFieldRefAccess<F>(FieldInfo fieldInfo) { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Expected O, but got Unknown if (fieldInfo == null) { throw new ArgumentNullException("fieldInfo"); } Type declaringType = fieldInfo.DeclaringType; DynamicMethodDefinition val = new DynamicMethodDefinition("__refget_" + declaringType.Name + "_static_fi_" + fieldInfo.Name, typeof(F).MakeByRefType(), new Type[0]); ILGenerator iLGenerator = val.GetILGenerator(); iLGenerator.Emit(OpCodes.Ldsflda, fieldInfo); iLGenerator.Emit(OpCodes.Ret); return Extensions.CreateDelegate<FieldRef<F>>((MethodBase)val.Generate()); } public static ref F StaticFieldRefAccess<F>(Type type, string fieldName) { FieldInfo field = type.GetField(fieldName, BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.NonPublic); return ref StaticFieldRefAccess<F>(field)(); } public static MethodBase GetOutsideCaller() { StackTrace stackTrace = new StackTrace(fNeedFileInfo: true); StackFrame[] frames = stackTrace.GetFrames(); foreach (StackFrame stackFrame in frames) { MethodBase method = stackFrame.GetMethod(); if (method.DeclaringType?.Namespace != typeof(Harmony).Namespace) { return method; } } throw new InvalidOperationException("Unexpected end of stack trace"); } public static void RethrowException(Exception exception) { ExceptionDispatchInfo.Capture(exception).Throw(); throw exception; } public static void ThrowMissingMemberException(Type type, params string[] names) { string text = string.Join(",", GetFieldNames(type).ToArray()); string text2 = string.Join(",", GetPropertyNa
BepInEx/core/BepInEx.dll
Decompiled a week ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.ConsoleUtil; using BepInEx.Logging; using BepInEx.Unix; using HarmonyLib; using HarmonyLib.Tools; using Microsoft.Win32.SafeHandles; using Mono.Cecil; using MonoMod.Utils; using UnityEngine; using UnityInjector.ConsoleUtil; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: ComVisible(false)] [assembly: Guid("4ffba620-f5ed-47f9-b90c-dad1316fd9b9")] [assembly: InternalsVisibleTo("BepInEx.Preloader")] [assembly: InternalsVisibleTo("BepInExTests")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("BepInEx")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyCopyright("Copyright © Bepis 2018")] [assembly: AssemblyDescription("Unity plugin injection framework")] [assembly: AssemblyFileVersion("5.4.23.2")] [assembly: AssemblyInformationalVersion("5.4.23.2+9cfc06ef463876e0f463f6f9a84c92d7ac346989")] [assembly: AssemblyProduct("BepInEx")] [assembly: AssemblyTitle("BepInEx")] [assembly: AssemblyVersion("5.4.23.2")] namespace UnityEngine { internal sealed class UnityLogWriter { [MethodImpl(MethodImplOptions.InternalCall)] public static extern void WriteStringToUnityLogImpl(string s); [MethodImpl(MethodImplOptions.InternalCall)] public static extern void WriteStringToUnityLog(string s); } } namespace UnityInjector.ConsoleUtil { internal static class SafeConsole { private delegate ConsoleColor GetColorDelegate(); private delegate void SetColorDelegate(ConsoleColor value); private delegate string GetStringDelegate(); private delegate void SetStringDelegate(string value); private static GetColorDelegate _getBackgroundColor; private static SetColorDelegate _setBackgroundColor; private static GetColorDelegate _getForegroundColor; private static SetColorDelegate _setForegroundColor; private static GetStringDelegate _getTitle; private static SetStringDelegate _setTitle; public static bool BackgroundColorExists { get; private set; } public static ConsoleColor BackgroundColor { get { return _getBackgroundColor(); } set { _setBackgroundColor(value); } } public static bool ForegroundColorExists { get; private set; } public static ConsoleColor ForegroundColor { get { return _getForegroundColor(); } set { _setForegroundColor(value); } } public static bool TitleExists { get; private set; } public static string Title { get { return _getTitle(); } set { _setTitle(value); } } static SafeConsole() { Type typeFromHandle = typeof(Console); InitColors(typeFromHandle); } private static void InitColors(Type tConsole) { MethodInfo method = tConsole.GetMethod("get_ForegroundColor", BindingFlags.Static | BindingFlags.Public); MethodInfo method2 = tConsole.GetMethod("set_ForegroundColor", BindingFlags.Static | BindingFlags.Public); MethodInfo method3 = tConsole.GetMethod("get_BackgroundColor", BindingFlags.Static | BindingFlags.Public); MethodInfo method4 = tConsole.GetMethod("set_BackgroundColor", BindingFlags.Static | BindingFlags.Public); MethodInfo method5 = tConsole.GetMethod("get_Title", BindingFlags.Static | BindingFlags.Public); MethodInfo method6 = tConsole.GetMethod("set_Title", BindingFlags.Static | BindingFlags.Public); _setForegroundColor = ((method2 != null) ? ((SetColorDelegate)Delegate.CreateDelegate(typeof(SetColorDelegate), method2)) : ((SetColorDelegate)delegate { })); _setBackgroundColor = ((method4 != null) ? ((SetColorDelegate)Delegate.CreateDelegate(typeof(SetColorDelegate), method4)) : ((SetColorDelegate)delegate { })); _getForegroundColor = ((method != null) ? ((GetColorDelegate)Delegate.CreateDelegate(typeof(GetColorDelegate), method)) : ((GetColorDelegate)(() => ConsoleColor.Gray))); _getBackgroundColor = ((method3 != null) ? ((GetColorDelegate)Delegate.CreateDelegate(typeof(GetColorDelegate), method3)) : ((GetColorDelegate)(() => ConsoleColor.Black))); _getTitle = ((method5 != null) ? ((GetStringDelegate)Delegate.CreateDelegate(typeof(GetStringDelegate), method5)) : ((GetStringDelegate)(() => string.Empty))); _setTitle = ((method6 != null) ? ((SetStringDelegate)Delegate.CreateDelegate(typeof(SetStringDelegate), method6)) : ((SetStringDelegate)delegate { })); BackgroundColorExists = _setBackgroundColor != null && _getBackgroundColor != null; ForegroundColorExists = _setForegroundColor != null && _getForegroundColor != null; TitleExists = _setTitle != null && _getTitle != null; } } internal class ConsoleEncoding : Encoding { private byte[] _byteBuffer = new byte[256]; private char[] _charBuffer = new char[256]; private byte[] _zeroByte = new byte[0]; private char[] _zeroChar = new char[0]; private readonly uint _codePage; public override int CodePage => (int)_codePage; public static Encoding OutputEncoding => new ConsoleEncoding(ConsoleCodePage); public static uint ConsoleCodePage { get { return GetConsoleOutputCP(); } set { SetConsoleOutputCP(value); } } private void ExpandByteBuffer(int count) { if (_byteBuffer.Length < count) { _byteBuffer = new byte[count]; } } private void ExpandCharBuffer(int count) { if (_charBuffer.Length < count) { _charBuffer = new char[count]; } } private void ReadByteBuffer(byte[] bytes, int index, int count) { for (int i = 0; i < count; i++) { bytes[index + i] = _byteBuffer[i]; } } private void ReadCharBuffer(char[] chars, int index, int count) { for (int i = 0; i < count; i++) { chars[index + i] = _charBuffer[i]; } } private void WriteByteBuffer(byte[] bytes, int index, int count) { ExpandByteBuffer(count); for (int i = 0; i < count; i++) { _byteBuffer[i] = bytes[index + i]; } } private void WriteCharBuffer(char[] chars, int index, int count) { ExpandCharBuffer(count); for (int i = 0; i < count; i++) { _charBuffer[i] = chars[index + i]; } } public static uint GetActiveCodePage() { return GetACP(); } private ConsoleEncoding(uint codePage) { _codePage = codePage; } public static ConsoleEncoding GetEncoding(uint codePage) { return new ConsoleEncoding(codePage); } public override int GetByteCount(char[] chars, int index, int count) { WriteCharBuffer(chars, index, count); return WideCharToMultiByte(_codePage, 0u, _charBuffer, count, _zeroByte, 0, IntPtr.Zero, IntPtr.Zero); } public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { int byteCount = GetByteCount(chars, charIndex, charCount); WriteCharBuffer(chars, charIndex, charCount); ExpandByteBuffer(byteCount); int result = WideCharToMultiByte(_codePage, 0u, chars, charCount, _byteBuffer, byteCount, IntPtr.Zero, IntPtr.Zero); ReadByteBuffer(bytes, byteIndex, byteCount); return result; } public override int GetCharCount(byte[] bytes, int index, int count) { WriteByteBuffer(bytes, index, count); return MultiByteToWideChar(_codePage, 0u, bytes, count, _zeroChar, 0); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { int charCount = GetCharCount(bytes, byteIndex, byteCount); WriteByteBuffer(bytes, byteIndex, byteCount); ExpandCharBuffer(charCount); int result = MultiByteToWideChar(_codePage, 0u, bytes, byteCount, _charBuffer, charCount); ReadCharBuffer(chars, charIndex, charCount); return result; } public override int GetMaxByteCount(int charCount) { return charCount * 2; } public override int GetMaxCharCount(int byteCount) { return byteCount; } [DllImport("kernel32.dll")] private static extern uint GetConsoleOutputCP(); [DllImport("kernel32.dll")] private static extern uint GetACP(); [DllImport("kernel32.dll", SetLastError = true)] private static extern int MultiByteToWideChar(uint codePage, uint dwFlags, [In][MarshalAs(UnmanagedType.LPArray)] byte[] lpMultiByteStr, int cbMultiByte, [Out][MarshalAs(UnmanagedType.LPWStr)] char[] lpWideCharStr, int cchWideChar); [DllImport("kernel32.dll")] private static extern IntPtr SetConsoleOutputCP(uint codepage); [DllImport("kernel32.dll", SetLastError = true)] private static extern int WideCharToMultiByte(uint codePage, uint dwFlags, [In][MarshalAs(UnmanagedType.LPWStr)] char[] lpWideCharStr, int cchWideChar, [Out][MarshalAs(UnmanagedType.LPArray)] byte[] lpMultiByteStr, int cbMultiByte, IntPtr lpDefaultChar, IntPtr lpUsedDefaultChar); } internal class ConsoleWindow { [UnmanagedFunctionPointer(CallingConvention.Winapi)] [return: MarshalAs(UnmanagedType.Bool)] private delegate bool SetForegroundWindowDelegate(IntPtr hWnd); [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate IntPtr GetForegroundWindowDelegate(); [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate IntPtr GetSystemMenuDelegate(IntPtr hwnd, bool bRevert); [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate bool DeleteMenuDelegate(IntPtr hMenu, uint uPosition, uint uFlags); private const uint SC_CLOSE = 61536u; private const uint MF_BYCOMMAND = 0u; private const uint LOAD_LIBRARY_SEARCH_SYSTEM32 = 2048u; public static IntPtr ConsoleOutHandle; public static IntPtr OriginalStdoutHandle; private static bool methodsInited; private static SetForegroundWindowDelegate setForeground; private static GetForegroundWindowDelegate getForeground; private static GetSystemMenuDelegate getSystemMenu; private static DeleteMenuDelegate deleteMenu; public static bool IsAttached { get; private set; } public static string Title { set { if (IsAttached) { if (value == null) { throw new ArgumentNullException("value"); } if (value.Length > 24500) { throw new InvalidOperationException("Console title too long"); } if (!SetConsoleTitle(value)) { throw new InvalidOperationException("Console title invalid"); } } } } public static void Attach() { if (!IsAttached) { Initialize(); if (OriginalStdoutHandle == IntPtr.Zero) { OriginalStdoutHandle = GetStdHandle(-11); } IntPtr hWnd = getForeground(); IntPtr consoleWindow = GetConsoleWindow(); if (GetConsoleWindow() == IntPtr.Zero && !AllocConsole()) { throw new Exception("AllocConsole() failed"); } setForeground(hWnd); ConsoleOutHandle = CreateFile("CONOUT$", 3221225472u, 2, IntPtr.Zero, 3, 0, IntPtr.Zero); Kon.conOut = ConsoleOutHandle; if (!SetStdHandle(-11, ConsoleOutHandle)) { throw new Exception("SetStdHandle() failed"); } if (OriginalStdoutHandle != IntPtr.Zero && ConsoleManager.ConfigConsoleOutRedirectType.Value == ConsoleManager.ConsoleOutRedirectType.ConsoleOut) { CloseHandle(OriginalStdoutHandle); } IsAttached = true; } } public static void PreventClose() { if (IsAttached) { Initialize(); IntPtr consoleWindow = GetConsoleWindow(); IntPtr intPtr = getSystemMenu(consoleWindow, bRevert: false); if (intPtr != IntPtr.Zero) { deleteMenu(intPtr, 61536u, 0u); } } } public static void Detach() { if (IsAttached) { if (!CloseHandle(ConsoleOutHandle)) { throw new Exception("CloseHandle() failed"); } ConsoleOutHandle = IntPtr.Zero; if (!FreeConsole()) { throw new Exception("FreeConsole() failed"); } if (!SetStdHandle(-11, OriginalStdoutHandle)) { throw new Exception("SetStdHandle() failed"); } IsAttached = false; } } private static void Initialize() { if (!methodsInited) { methodsInited = true; IntPtr hModule = LoadLibraryEx("user32.dll", IntPtr.Zero, 2048u); setForeground = DynDll.AsDelegate<SetForegroundWindowDelegate>(GetProcAddress(hModule, "SetForegroundWindow")); getForeground = DynDll.AsDelegate<GetForegroundWindowDelegate>(GetProcAddress(hModule, "GetForegroundWindow")); getSystemMenu = DynDll.AsDelegate<GetSystemMenuDelegate>(GetProcAddress(hModule, "GetSystemMenu")); deleteMenu = DynDll.AsDelegate<DeleteMenuDelegate>(GetProcAddress(hModule, "DeleteMenu")); } } [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetProcAddress(IntPtr hModule, string procName); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool AllocConsole(); [DllImport("kernel32.dll")] private static extern IntPtr GetConsoleWindow(); [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] private static extern bool CloseHandle(IntPtr handle); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr CreateFile(string fileName, uint desiredAccess, int shareMode, IntPtr securityAttributes, int creationDisposition, int flagsAndAttributes, IntPtr templateFile); [DllImport("kernel32.dll")] private static extern bool FreeConsole(); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetStdHandle(int nStdHandle); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool SetStdHandle(int nStdHandle, IntPtr hConsoleOutput); [DllImport("kernel32.dll", BestFitMapping = true, CharSet = CharSet.Auto, SetLastError = true)] private static extern bool SetConsoleTitle(string title); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr LoadLibraryEx(string lpLibFileName, IntPtr hFile, uint dwFlags); } } namespace BepInEx { internal static class ConsoleManager { public enum ConsoleOutRedirectType { [Description("Auto")] Auto, [Description("Console Out")] ConsoleOut, [Description("Standard Out")] StandardOut } private const uint SHIFT_JIS_CP = 932u; private static readonly bool? EnableConsoleArgOverride; private const string ENABLE_CONSOLE_ARG = "--enable-console"; public static readonly ConfigEntry<bool> ConfigConsoleEnabled; public static readonly ConfigEntry<bool> ConfigPreventClose; public static readonly ConfigEntry<bool> ConfigConsoleShiftJis; public static readonly ConfigEntry<ConsoleOutRedirectType> ConfigConsoleOutRedirectType; internal static IConsoleDriver Driver { get; set; } public static bool ConsoleActive => Driver?.ConsoleActive ?? false; public static TextWriter StandardOutStream => Driver?.StandardOut; public static TextWriter ConsoleStream => Driver?.ConsoleOut; public static bool ConsoleEnabled => EnableConsoleArgOverride ?? ConfigConsoleEnabled.Value; static ConsoleManager() { ConfigConsoleEnabled = ConfigFile.CoreConfig.Bind("Logging.Console", "Enabled", defaultValue: false, "Enables showing a console for log output."); ConfigPreventClose = ConfigFile.CoreConfig.Bind("Logging.Console", "PreventClose", defaultValue: false, "If enabled, will prevent closing the console (either by deleting the close button or in other platform-specific way)."); ConfigConsoleShiftJis = ConfigFile.CoreConfig.Bind("Logging.Console", "ShiftJisEncoding", defaultValue: false, "If true, console is set to the Shift-JIS encoding, otherwise UTF-8 encoding."); ConfigConsoleOutRedirectType = ConfigFile.CoreConfig.Bind("Logging.Console", "StandardOutType", ConsoleOutRedirectType.Auto, new StringBuilder().AppendLine("Hints console manager on what handle to assign as StandardOut. Possible values:").AppendLine("Auto - lets BepInEx decide how to redirect console output").AppendLine("ConsoleOut - prefer redirecting to console output; if possible, closes original standard output") .AppendLine("StandardOut - prefer redirecting to standard output; if possible, closes console out") .ToString()); try { string[] commandLineArgs = Environment.GetCommandLineArgs(); for (int i = 0; i < commandLineArgs.Length; i++) { string text = commandLineArgs[i]; if (text == "--enable-console" && i + 1 < commandLineArgs.Length && bool.TryParse(commandLineArgs[i + 1], out var result)) { EnableConsoleArgOverride = result; } } } catch (Exception) { } } public static void Initialize(bool alreadyActive) { if (PlatformHelper.Is((Platform)8)) { Driver = new LinuxConsoleDriver(); } else if (PlatformHelper.Is((Platform)37)) { Driver = new WindowsConsoleDriver(); } Driver.Initialize(alreadyActive); } private static void DriverCheck() { if (Driver == null) { throw new InvalidOperationException("Driver has not been initialized"); } } public static void CreateConsole() { if (!ConsoleActive) { DriverCheck(); uint codepage = (ConfigConsoleShiftJis.Value ? 932u : ((uint)Encoding.UTF8.CodePage)); Driver.CreateConsole(codepage); if (ConfigPreventClose.Value) { Driver.PreventClose(); } } } public static void DetachConsole() { if (ConsoleActive) { DriverCheck(); Driver.DetachConsole(); } } public static void SetConsoleTitle(string title) { DriverCheck(); Driver.SetConsoleTitle(title); } public static void SetConsoleColor(ConsoleColor color) { DriverCheck(); Driver.SetConsoleColor(color); } } internal interface IConsoleDriver { TextWriter StandardOut { get; } TextWriter ConsoleOut { get; } bool ConsoleActive { get; } bool ConsoleIsExternal { get; } void PreventClose(); void Initialize(bool alreadyActive); void CreateConsole(uint codepage); void DetachConsole(); void SetConsoleColor(ConsoleColor color); void SetConsoleTitle(string title); } internal class WindowsConsoleDriver : IConsoleDriver { private static readonly ConstructorInfo FileStreamCtor = new ConstructorInfo[2] { AccessTools.Constructor(typeof(FileStream), new Type[2] { typeof(SafeFileHandle), typeof(FileAccess) }, false), AccessTools.Constructor(typeof(FileStream), new Type[2] { typeof(IntPtr), typeof(FileAccess) }, false) }.FirstOrDefault((ConstructorInfo m) => m != null); public TextWriter StandardOut { get; private set; } public TextWriter ConsoleOut { get; private set; } public bool ConsoleActive { get; private set; } public bool ConsoleIsExternal => true; public void PreventClose() { ConsoleWindow.PreventClose(); } public void Initialize(bool alreadyActive) { ConsoleActive = alreadyActive; StandardOut = Console.Out; } private static FileStream OpenFileStream(IntPtr handle) { SafeFileHandle safeFileHandle = new SafeFileHandle(handle, ownsHandle: false); object[] args = AccessTools.ActualParameters((MethodBase)FileStreamCtor, new object[3] { safeFileHandle, safeFileHandle.DangerousGetHandle(), FileAccess.Write }); return (FileStream)Activator.CreateInstance(typeof(FileStream), args); } public void CreateConsole(uint codepage) { ConsoleWindow.Attach(); ConsoleEncoding.ConsoleCodePage = codepage; IntPtr outHandle = GetOutHandle(); if (outHandle == IntPtr.Zero) { StandardOut = TextWriter.Null; ConsoleOut = TextWriter.Null; return; } FileStream stream = OpenFileStream(outHandle); StandardOut = new StreamWriter(stream, Utility.UTF8NoBom) { AutoFlush = true }; FileStream stream2 = OpenFileStream(ConsoleWindow.ConsoleOutHandle); ConsoleOut = new StreamWriter(stream2, ConsoleEncoding.OutputEncoding) { AutoFlush = true }; ConsoleActive = true; } private IntPtr GetOutHandle() { return ConsoleManager.ConfigConsoleOutRedirectType.Value switch { ConsoleManager.ConsoleOutRedirectType.ConsoleOut => ConsoleWindow.ConsoleOutHandle, ConsoleManager.ConsoleOutRedirectType.StandardOut => ConsoleWindow.OriginalStdoutHandle, _ => (ConsoleWindow.OriginalStdoutHandle != IntPtr.Zero) ? ConsoleWindow.OriginalStdoutHandle : ConsoleWindow.ConsoleOutHandle, }; } public void DetachConsole() { ConsoleWindow.Detach(); ConsoleOut.Close(); ConsoleOut = null; ConsoleActive = false; } public void SetConsoleColor(ConsoleColor color) { SafeConsole.ForegroundColor = color; Kon.ForegroundColor = color; } public void SetConsoleTitle(string title) { ConsoleWindow.Title = title; } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class BepInPlugin : Attribute { public string GUID { get; protected set; } public string Name { get; protected set; } public Version Version { get; protected set; } public BepInPlugin(string GUID, string Name, string Version) { this.GUID = GUID; this.Name = Name; try { this.Version = new Version(Version); } catch { this.Version = null; } } internal static BepInPlugin FromCecilType(TypeDefinition td) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: 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_003f: 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) //IL_0058: Unknown result type (might be due to invalid IL or missing references) CustomAttribute val = MetadataHelper.GetCustomAttributes<BepInPlugin>(td, inherit: false).FirstOrDefault(); if (val == null) { return null; } CustomAttributeArgument val2 = val.ConstructorArguments[0]; string gUID = (string)((CustomAttributeArgument)(ref val2)).Value; val2 = val.ConstructorArguments[1]; string name = (string)((CustomAttributeArgument)(ref val2)).Value; val2 = val.ConstructorArguments[2]; return new BepInPlugin(gUID, name, (string)((CustomAttributeArgument)(ref val2)).Value); } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class BepInDependency : Attribute, ICacheable { [Flags] public enum DependencyFlags { HardDependency = 1, SoftDependency = 2 } public string DependencyGUID { get; protected set; } public DependencyFlags Flags { get; protected set; } public Version MinimumVersion { get; protected set; } public BepInDependency(string DependencyGUID, DependencyFlags Flags = DependencyFlags.HardDependency) { this.DependencyGUID = DependencyGUID; this.Flags = Flags; MinimumVersion = new Version(); } public BepInDependency(string DependencyGUID, string MinimumDependencyVersion) : this(DependencyGUID) { MinimumVersion = new Version(MinimumDependencyVersion); } internal static IEnumerable<BepInDependency> FromCecilType(TypeDefinition td) { IEnumerable<CustomAttribute> customAttributes = MetadataHelper.GetCustomAttributes<BepInDependency>(td, inherit: true); return customAttributes.Select(delegate(CustomAttribute customAttribute) { //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_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) CustomAttributeArgument val = customAttribute.ConstructorArguments[0]; string dependencyGUID = (string)((CustomAttributeArgument)(ref val)).Value; val = customAttribute.ConstructorArguments[1]; object value = ((CustomAttributeArgument)(ref val)).Value; return (value is string minimumDependencyVersion) ? new BepInDependency(dependencyGUID, minimumDependencyVersion) : new BepInDependency(dependencyGUID, (DependencyFlags)value); }).ToList(); } void ICacheable.Save(BinaryWriter bw) { bw.Write(DependencyGUID); bw.Write((int)Flags); bw.Write(MinimumVersion.ToString()); } void ICacheable.Load(BinaryReader br) { DependencyGUID = br.ReadString(); Flags = (DependencyFlags)br.ReadInt32(); MinimumVersion = new Version(br.ReadString()); } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class BepInIncompatibility : Attribute, ICacheable { public string IncompatibilityGUID { get; protected set; } public BepInIncompatibility(string IncompatibilityGUID) { this.IncompatibilityGUID = IncompatibilityGUID; } internal static IEnumerable<BepInIncompatibility> FromCecilType(TypeDefinition td) { IEnumerable<CustomAttribute> customAttributes = MetadataHelper.GetCustomAttributes<BepInIncompatibility>(td, inherit: true); return customAttributes.Select(delegate(CustomAttribute customAttribute) { //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) CustomAttributeArgument val = customAttribute.ConstructorArguments[0]; string incompatibilityGUID = (string)((CustomAttributeArgument)(ref val)).Value; return new BepInIncompatibility(incompatibilityGUID); }).ToList(); } void ICacheable.Save(BinaryWriter bw) { bw.Write(IncompatibilityGUID); } void ICacheable.Load(BinaryReader br) { IncompatibilityGUID = br.ReadString(); } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class BepInProcess : Attribute { public string ProcessName { get; protected set; } public BepInProcess(string ProcessName) { this.ProcessName = ProcessName; } internal static List<BepInProcess> FromCecilType(TypeDefinition td) { IEnumerable<CustomAttribute> customAttributes = MetadataHelper.GetCustomAttributes<BepInProcess>(td, inherit: true); return customAttributes.Select(delegate(CustomAttribute customAttribute) { //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) CustomAttributeArgument val = customAttribute.ConstructorArguments[0]; return new BepInProcess((string)((CustomAttributeArgument)(ref val)).Value); }).ToList(); } } public static class MetadataHelper { internal static IEnumerable<CustomAttribute> GetCustomAttributes<T>(TypeDefinition td, bool inherit) where T : Attribute { List<CustomAttribute> list = new List<CustomAttribute>(); Type type = typeof(T); TypeDefinition val = td; do { list.AddRange(((IEnumerable<CustomAttribute>)val.CustomAttributes).Where((CustomAttribute ca) => ((MemberReference)ca.AttributeType).FullName == type.FullName)); TypeReference baseType = val.BaseType; val = ((baseType != null) ? baseType.Resolve() : null); } while (inherit && ((val != null) ? ((MemberReference)val).FullName : null) != "System.Object"); return list; } public static BepInPlugin GetMetadata(Type pluginType) { object[] customAttributes = pluginType.GetCustomAttributes(typeof(BepInPlugin), inherit: false); if (customAttributes.Length == 0) { return null; } return (BepInPlugin)customAttributes[0]; } public static BepInPlugin GetMetadata(object plugin) { return GetMetadata(plugin.GetType()); } public static T[] GetAttributes<T>(Type pluginType) where T : Attribute { return (T[])pluginType.GetCustomAttributes(typeof(T), inherit: true); } public static IEnumerable<T> GetAttributes<T>(object plugin) where T : Attribute { return GetAttributes<T>(plugin.GetType()); } public static IEnumerable<BepInDependency> GetDependencies(Type plugin) { return plugin.GetCustomAttributes(typeof(BepInDependency), inherit: true).Cast<BepInDependency>(); } } internal class BuildInfoAttribute : Attribute { public string Info { get; } public BuildInfoAttribute(string info) { Info = info; } } public abstract class BaseUnityPlugin : MonoBehaviour { public PluginInfo Info { get; } protected ManualLogSource Logger { get; } public ConfigFile Config { get; } protected BaseUnityPlugin() { BepInPlugin metadata = MetadataHelper.GetMetadata(this); if (metadata == null) { throw new InvalidOperationException("Can't create an instance of " + ((object)this).GetType().FullName + " because it inherits from BaseUnityPlugin and the BepInPlugin attribute is missing."); } if (!Chainloader.IsEditor && Chainloader.PluginInfos.TryGetValue(metadata.GUID, out var value)) { Info = value; } else { Info = new PluginInfo { Metadata = metadata, Instance = this, Dependencies = MetadataHelper.GetDependencies(((object)this).GetType()), Processes = MetadataHelper.GetAttributes<BepInProcess>(((object)this).GetType()), Location = ((object)this).GetType().Assembly.Location }; } Logger = BepInEx.Logging.Logger.CreateLogSource(metadata.Name); string text = (Chainloader.IsEditor ? "." : Paths.ConfigPath); Config = new ConfigFile(Utility.CombinePaths(text, metadata.GUID + ".cfg"), saveOnInit: false, metadata); } } public class PluginInfo : ICacheable { public BepInPlugin Metadata { get; internal set; } public IEnumerable<BepInProcess> Processes { get; internal set; } public IEnumerable<BepInDependency> Dependencies { get; internal set; } public IEnumerable<BepInIncompatibility> Incompatibilities { get; internal set; } public string Location { get; internal set; } public BaseUnityPlugin Instance { get; internal set; } internal string TypeName { get; set; } internal Version TargettedBepInExVersion { get; set; } void ICacheable.Save(BinaryWriter bw) { bw.Write(TypeName); bw.Write(Metadata.GUID); bw.Write(Metadata.Name); bw.Write(Metadata.Version.ToString()); List<BepInProcess> list = Processes.ToList(); bw.Write(list.Count); foreach (BepInProcess item in list) { bw.Write(item.ProcessName); } List<BepInDependency> list2 = Dependencies.ToList(); bw.Write(list2.Count); foreach (BepInDependency item2 in list2) { ((ICacheable)item2).Save(bw); } List<BepInIncompatibility> list3 = Incompatibilities.ToList(); bw.Write(list3.Count); foreach (BepInIncompatibility item3 in list3) { ((ICacheable)item3).Save(bw); } bw.Write(TargettedBepInExVersion.ToString(4)); } void ICacheable.Load(BinaryReader br) { TypeName = br.ReadString(); Metadata = new BepInPlugin(br.ReadString(), br.ReadString(), br.ReadString()); int num = br.ReadInt32(); List<BepInProcess> list = new List<BepInProcess>(num); for (int i = 0; i < num; i++) { list.Add(new BepInProcess(br.ReadString())); } Processes = list; int num2 = br.ReadInt32(); List<BepInDependency> list2 = new List<BepInDependency>(num2); for (int j = 0; j < num2; j++) { BepInDependency bepInDependency = new BepInDependency(""); ((ICacheable)bepInDependency).Load(br); list2.Add(bepInDependency); } Dependencies = list2; int num3 = br.ReadInt32(); List<BepInIncompatibility> list3 = new List<BepInIncompatibility>(num3); for (int k = 0; k < num3; k++) { BepInIncompatibility bepInIncompatibility = new BepInIncompatibility(""); ((ICacheable)bepInIncompatibility).Load(br); list3.Add(bepInIncompatibility); } Incompatibilities = list3; TargettedBepInExVersion = new Version(br.ReadString()); } public override string ToString() { return $"{Metadata?.Name} {Metadata?.Version}"; } } public static class Paths { public static string[] DllSearchPaths { get; private set; } public static string BepInExAssemblyDirectory { get; private set; } public static string BepInExAssemblyPath { get; private set; } public static string BepInExRootPath { get; private set; } public static string ExecutablePath { get; private set; } public static string GameRootPath { get; private set; } public static string ManagedPath { get; private set; } public static string ConfigPath { get; private set; } public static string BepInExConfigPath { get; private set; } public static string CachePath { get; private set; } public static string PatcherPluginPath { get; private set; } public static string PluginPath { get; private set; } public static string ProcessName { get; private set; } internal static void SetExecutablePath(string executablePath, string bepinRootPath = null, string managedPath = null, string[] dllSearchPath = null) { ExecutablePath = executablePath; ProcessName = Path.GetFileNameWithoutExtension(executablePath); GameRootPath = (PlatformHelper.Is((Platform)73) ? Utility.ParentDirectory(executablePath, 4) : Path.GetDirectoryName(executablePath)); ManagedPath = managedPath ?? Utility.CombinePaths(GameRootPath, ProcessName + "_Data", "Managed"); BepInExRootPath = bepinRootPath ?? Path.Combine(GameRootPath, "BepInEx"); ConfigPath = Path.Combine(BepInExRootPath, "config"); BepInExConfigPath = Path.Combine(ConfigPath, "BepInEx.cfg"); PluginPath = Path.Combine(BepInExRootPath, "plugins"); PatcherPluginPath = Path.Combine(BepInExRootPath, "patchers"); BepInExAssemblyDirectory = Path.Combine(BepInExRootPath, "core"); BepInExAssemblyPath = Path.Combine(BepInExAssemblyDirectory, Assembly.GetExecutingAssembly().GetName().Name + ".dll"); CachePath = Path.Combine(BepInExRootPath, "cache"); DllSearchPaths = (dllSearchPath ?? new string[0]).Concat(new string[1] { ManagedPath }).Distinct().ToArray(); } internal static void SetManagedPath(string managedPath) { if (managedPath != null) { ManagedPath = managedPath; } } internal static void SetPluginPath(string pluginPath) { PluginPath = Utility.CombinePaths(BepInExRootPath, pluginPath); } } public sealed class ThreadingHelper : MonoBehaviour, ISynchronizeInvoke { private sealed class InvokeResult : IAsyncResult { internal bool ExceptionThrown; public bool IsCompleted { get; private set; } public WaitHandle AsyncWaitHandle { get; } public object AsyncState { get; private set; } public bool CompletedSynchronously { get; private set; } public InvokeResult() { AsyncWaitHandle = new EventWaitHandle(initialState: false, EventResetMode.ManualReset); } public void Finish(object result, bool completedSynchronously) { AsyncState = result; CompletedSynchronously = completedSynchronously; IsCompleted = true; ((EventWaitHandle)AsyncWaitHandle).Set(); } } private readonly object _invokeLock = new object(); private Action _invokeList; private Thread _mainThread; public static ThreadingHelper Instance { get; private set; } public static ISynchronizeInvoke SynchronizingObject => Instance; public bool InvokeRequired => _mainThread == null || _mainThread != Thread.CurrentThread; internal static void Initialize() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown GameObject val = new GameObject("BepInEx_ThreadingHelper"); if (Chainloader.ConfigHideBepInExGOs.Value) { ((Object)val).hideFlags = (HideFlags)61; } Object.DontDestroyOnLoad((Object)(object)val); Instance = val.AddComponent<ThreadingHelper>(); } public void StartSyncInvoke(Action action) { if (action == null) { throw new ArgumentNullException("action"); } lock (_invokeLock) { _invokeList = (Action)Delegate.Combine(_invokeList, action); } } private void Update() { if (_mainThread == null) { _mainThread = Thread.CurrentThread; } if (_invokeList == null) { return; } Action invokeList; lock (_invokeLock) { invokeList = _invokeList; _invokeList = null; } foreach (Action item in invokeList.GetInvocationList().Cast<Action>()) { try { item(); } catch (Exception ex) { LogInvocationException(ex); } } } public void StartAsyncInvoke(Func<Action> action) { if (!ThreadPool.QueueUserWorkItem(DoWork)) { throw new NotSupportedException("Failed to queue the action on ThreadPool"); } void DoWork(object _) { try { Action action2 = action(); if (action2 != null) { StartSyncInvoke(action2); } } catch (Exception ex) { LogInvocationException(ex); } } } private static void LogInvocationException(Exception ex) { Logger.Log(LogLevel.Error, ex); if (ex.InnerException != null) { Logger.Log(LogLevel.Error, "INNER: " + ex.InnerException); } } IAsyncResult ISynchronizeInvoke.BeginInvoke(Delegate method, object[] args) { InvokeResult result = new InvokeResult(); if (!InvokeRequired) { result.Finish(Invoke(), completedSynchronously: true); } else { StartSyncInvoke(delegate { result.Finish(Invoke(), completedSynchronously: false); }); } return result; object Invoke() { try { return method.DynamicInvoke(args); } catch (Exception result2) { result.ExceptionThrown = true; return result2; } } } object ISynchronizeInvoke.EndInvoke(IAsyncResult result) { InvokeResult invokeResult = (InvokeResult)result; invokeResult.AsyncWaitHandle.WaitOne(); if (invokeResult.ExceptionThrown) { throw (Exception)invokeResult.AsyncState; } return invokeResult.AsyncState; } object ISynchronizeInvoke.Invoke(Delegate method, object[] args) { IAsyncResult result = ((ISynchronizeInvoke)this).BeginInvoke(method, args); return ((ISynchronizeInvoke)this).EndInvoke(result); } } public static class ThreadingExtensions { public static IEnumerable<TOut> RunParallel<TIn, TOut>(this IEnumerable<TIn> data, Func<TIn, TOut> work, int workerCount = -1) { foreach (TOut item in data.ToList().RunParallel(work)) { yield return item; } } public static IEnumerable<TOut> RunParallel<TIn, TOut>(this IList<TIn> data, Func<TIn, TOut> work, int workerCount = -1) { if (workerCount < 0) { workerCount = Mathf.Max(2, Environment.ProcessorCount); } else if (workerCount == 0) { throw new ArgumentException("Need at least 1 worker", "workerCount"); } int perThreadCount = Mathf.CeilToInt((float)data.Count / (float)workerCount); int doneCount = 0; object lockObj = new object(); ManualResetEvent are = new ManualResetEvent(initialState: false); IEnumerable<TOut> doneItems = null; Exception exceptionThrown = null; for (int i = 0; i < workerCount; i++) { int first = i * perThreadCount; int last = Mathf.Min(first + perThreadCount, data.Count); ThreadPool.QueueUserWorkItem(delegate { List<TOut> list = new List<TOut>(perThreadCount); try { for (int j = first; j < last; j++) { if (exceptionThrown != null) { break; } list.Add(work(data[j])); } } catch (Exception ex) { exceptionThrown = ex; } lock (lockObj) { IEnumerable<TOut> enumerable; if (doneItems != null) { enumerable = list.Concat(doneItems); } else { IEnumerable<TOut> enumerable2 = list; enumerable = enumerable2; } doneItems = enumerable; int num = doneCount; doneCount = num + 1; are.Set(); } }); } while (true) { are.WaitOne(); IEnumerable<TOut> toOutput; bool isDone; lock (lockObj) { toOutput = doneItems; doneItems = null; isDone = doneCount == workerCount; } if (toOutput != null) { foreach (TOut item in toOutput) { yield return item; } } if (isDone) { break; } toOutput = null; } if (exceptionThrown != null) { throw new TargetInvocationException("An exception was thrown inside one of the threads", exceptionThrown); } } } public static class UnityInput { private static IInputSystem _current; public static IInputSystem Current { get { if (_current != null) { return _current; } try { try { Input.GetKeyDown((KeyCode)97); _current = new LegacyInputSystem(); Logger.LogDebug("[UnityInput] Using LegacyInputSystem"); } catch (InvalidOperationException) { _current = new NewInputSystem(); Logger.LogDebug("[UnityInput] Using NewInputSystem"); } } catch (Exception arg) { Logger.LogWarning($"[UnityInput] Failed to detect available input systems - {arg}"); _current = new NullInputSystem(); } return _current; } } public static bool LegacyInputSystemAvailable => Current is LegacyInputSystem; } public interface IInputSystem { Vector3 mousePosition { get; } Vector2 mouseScrollDelta { get; } bool mousePresent { get; } bool anyKey { get; } bool anyKeyDown { get; } IEnumerable<KeyCode> SupportedKeyCodes { get; } bool GetKey(string name); bool GetKey(KeyCode key); bool GetKeyDown(string name); bool GetKeyDown(KeyCode key); bool GetKeyUp(string name); bool GetKeyUp(KeyCode key); bool GetMouseButton(int button); bool GetMouseButtonDown(int button); bool GetMouseButtonUp(int button); void ResetInputAxes(); } internal class NewInputSystem : IInputSystem { private delegate bool GetButtonDelegate(KeyCode key); private delegate Vector2 GetMouseVectorDelegate(); private delegate bool GetMouseStateDelegate(); private static bool initialized; private static readonly Dictionary<KeyCode, int> keyCodeToIndex = new Dictionary<KeyCode, int>(); private static readonly Dictionary<string, string> keyToKeyCodeNameRemap = new Dictionary<string, string> { ["LeftCtrl"] = "LeftControl", ["RightCtrl"] = "RightControl", ["LeftMeta"] = "LeftApple", ["RightMeta"] = "RightApple", ["ContextMenu"] = "Menu", ["PrintScreen"] = "Print", ["Enter"] = "Return" }; private static GetButtonDelegate _getKey; private static GetButtonDelegate _getKeyDown; private static GetButtonDelegate _getKeyUp; private static GetButtonDelegate _getMouseButton; private static GetButtonDelegate _getMouseButtonDown; private static GetButtonDelegate _getMouseButtonUp; private static GetMouseVectorDelegate _getMousePosition; private static GetMouseVectorDelegate _getMouseScrollDelta; private static GetMouseStateDelegate _getMousePresent; private static GetMouseStateDelegate _getKeyboardAnyKeyIsPressed; private static GetMouseStateDelegate _getKeyboardAnyKeyWasPressedThisFrame; public Vector3 mousePosition => Vector2.op_Implicit(_getMousePosition()); public Vector2 mouseScrollDelta => _getMouseScrollDelta(); public bool mousePresent => _getMousePresent(); public bool anyKey { get { if (_getKeyboardAnyKeyIsPressed()) { return true; } return GetMouseButton(0) || GetMouseButton(1) || GetMouseButton(2) || GetMouseButton(3) || GetMouseButton(4); } } public bool anyKeyDown { get { if (_getKeyboardAnyKeyWasPressedThisFrame()) { return true; } return GetMouseButtonDown(0) || GetMouseButtonDown(1) || GetMouseButtonDown(2) || GetMouseButtonDown(3) || GetMouseButtonDown(4); } } public IEnumerable<KeyCode> SupportedKeyCodes => keyCodeToIndex.Keys.ToArray(); public NewInputSystem() { Init(); } private static void Init() { //IL_02d3: Unknown result type (might be due to invalid IL or missing references) //IL_02da: Expected O, but got Unknown //IL_00d7: Unknown result type (might be due to invalid IL or missing references) if (initialized) { return; } Assembly assembly = Assembly.Load("Unity.InputSystem"); Type type = assembly.GetType("UnityEngine.InputSystem.Key"); foreach (object value3 in Enum.GetValues(type)) { string text = value3.ToString(); int value = (int)value3; string value2; if (text.StartsWith("Numpad")) { text = text.Replace("Numpad", "Keypad"); } else if (text.StartsWith("Digit")) { text = text.Replace("Digit", "Alpha"); } else if (keyToKeyCodeNameRemap.TryGetValue(text, out value2)) { text = value2; } if (TryEnumParse<KeyCode>(text, out var val)) { keyCodeToIndex[val] = value; } else { Logger.LogDebug("[UnityInput] Unknown key name: " + text + ", skipping remapping"); } } FieldInfo keyCodeToIndexField = AccessTools.Field(typeof(NewInputSystem), "keyCodeToIndex"); MethodInfo tryGetValueMethod = AccessTools.Method(typeof(Dictionary<KeyCode, int>), "TryGetValue", (Type[])null, (Type[])null); Type type2 = assembly.GetType("UnityEngine.InputSystem.Keyboard"); MethodInfo currentProperty = AccessTools.PropertyGetter(type2, "current"); MethodInfo indexer = AccessTools.Method(type2, "get_Item", new Type[1] { type }, (Type[])null); Type buttonControlType = assembly.GetType("UnityEngine.InputSystem.Controls.ButtonControl"); _getKey = GenerateKeyGetter("InputSystemGetKey", "isPressed"); _getKeyDown = GenerateKeyGetter("InputSystemGetKeyDown", "wasPressedThisFrame"); _getKeyUp = GenerateKeyGetter("InputSystemGetKeyUp", "wasReleasedThisFrame"); Type mouseType = assembly.GetType("UnityEngine.InputSystem.Mouse"); MethodInfo mouseCurrentProperty = AccessTools.PropertyGetter(mouseType, "current"); string[] source = new string[5] { "leftButton", "rightButton", "middleButton", "backButton", "forwardButton" }; MethodInfo[] buttonPropertyGetters = source.Select((string p) => AccessTools.PropertyGetter(mouseType, p)).ToArray(); _getMouseButton = GenerateMouseGetter("InputSystemGetMouseButton", "isPressed"); _getMouseButtonDown = GenerateMouseGetter("InputSystemGetMouseButtonDown", "wasPressedThisFrame"); _getMouseButtonUp = GenerateMouseGetter("InputSystemGetMouseButtonUp", "wasReleasedThisFrame"); _getMousePosition = GetPositionDelegate("InputSystemGetMousePosition", "position"); _getMouseScrollDelta = GetPositionDelegate("InputSystemGetMouseScrollDelta", "scroll"); DynamicMethodDefinition val2 = new DynamicMethodDefinition("InputSystemGetMouseEnabled", typeof(bool), Type.EmptyTypes); ILGenerator iLGenerator = val2.GetILGenerator(); iLGenerator.Emit(OpCodes.Call, mouseCurrentProperty); iLGenerator.Emit(OpCodes.Callvirt, AccessTools.PropertyGetter(mouseType, "enabled")); iLGenerator.Emit(OpCodes.Ret); _getMousePresent = Extensions.CreateDelegate<GetMouseStateDelegate>((MethodBase)val2.Generate()); MethodInfo anyKeyProperty = AccessTools.PropertyGetter(type2, "anyKey"); _getKeyboardAnyKeyIsPressed = GetAnyKeyDelegate("InputSystemGetKeyboardAnyKeyIsPressed", "isPressed"); _getKeyboardAnyKeyWasPressedThisFrame = GetAnyKeyDelegate("InputSystemGetKeyboardAnyKeyWasPressedThisFrame", "wasPressedThisFrame"); initialized = true; GetButtonDelegate GenerateKeyGetter(string name, string property) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown MethodInfo meth4 = AccessTools.PropertyGetter(buttonControlType, property); DynamicMethodDefinition val6 = new DynamicMethodDefinition(name, typeof(bool), new Type[1] { typeof(KeyCode) }); ILGenerator iLGenerator4 = val6.GetILGenerator(); LocalBuilder local = iLGenerator4.DeclareLocal(typeof(int)); Label label2 = iLGenerator4.DefineLabel(); iLGenerator4.Emit(OpCodes.Ldsfld, keyCodeToIndexField); iLGenerator4.Emit(OpCodes.Ldarg_0); iLGenerator4.Emit(OpCodes.Ldloca, local); iLGenerator4.Emit(OpCodes.Callvirt, tryGetValueMethod); iLGenerator4.Emit(OpCodes.Brfalse, label2); iLGenerator4.Emit(OpCodes.Call, currentProperty); iLGenerator4.Emit(OpCodes.Ldloc, local); iLGenerator4.Emit(OpCodes.Callvirt, indexer); iLGenerator4.Emit(OpCodes.Callvirt, meth4); iLGenerator4.Emit(OpCodes.Ret); iLGenerator4.MarkLabel(label2); iLGenerator4.Emit(OpCodes.Ldc_I4_0); iLGenerator4.Emit(OpCodes.Ret); return Extensions.CreateDelegate<GetButtonDelegate>((MethodBase)val6.Generate()); } GetButtonDelegate GenerateMouseGetter(string name, string property) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown MethodInfo meth3 = AccessTools.PropertyGetter(buttonControlType, property); DynamicMethodDefinition val5 = new DynamicMethodDefinition(name, typeof(bool), new Type[1] { typeof(KeyCode) }); ILGenerator il = val5.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldc_I4, 323); il.Emit(OpCodes.Sub); Label[] array = buttonPropertyGetters.Select((MethodInfo _) => il.DefineLabel()).ToArray(); Label label = il.DefineLabel(); il.Emit(OpCodes.Switch, array); il.Emit(OpCodes.Br, label); for (int i = 0; i < array.Length; i++) { il.MarkLabel(array[i]); il.Emit(OpCodes.Call, mouseCurrentProperty); il.Emit(OpCodes.Callvirt, buttonPropertyGetters[i]); il.Emit(OpCodes.Callvirt, meth3); il.Emit(OpCodes.Ret); } il.MarkLabel(label); il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Ret); return Extensions.CreateDelegate<GetButtonDelegate>((MethodBase)val5.Generate()); } GetMouseStateDelegate GetAnyKeyDelegate(string name, string property) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown MethodInfo meth = AccessTools.PropertyGetter(buttonControlType, property); DynamicMethodDefinition val3 = new DynamicMethodDefinition(name, typeof(bool), Type.EmptyTypes); ILGenerator iLGenerator2 = val3.GetILGenerator(); iLGenerator2.Emit(OpCodes.Call, currentProperty); iLGenerator2.Emit(OpCodes.Callvirt, anyKeyProperty); iLGenerator2.Emit(OpCodes.Callvirt, meth); iLGenerator2.Emit(OpCodes.Ret); return Extensions.CreateDelegate<GetMouseStateDelegate>((MethodBase)val3.Generate()); } GetMouseVectorDelegate GetPositionDelegate(string name, string property) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown MethodInfo methodInfo = AccessTools.PropertyGetter(mouseType, property); MethodInfo meth2 = AccessTools.Method(methodInfo.ReturnType, "ReadValue", (Type[])null, (Type[])null); DynamicMethodDefinition val4 = new DynamicMethodDefinition(name, typeof(Vector2), Type.EmptyTypes); ILGenerator iLGenerator3 = val4.GetILGenerator(); iLGenerator3.Emit(OpCodes.Call, mouseCurrentProperty); iLGenerator3.Emit(OpCodes.Callvirt, methodInfo); iLGenerator3.Emit(OpCodes.Callvirt, meth2); iLGenerator3.Emit(OpCodes.Ret); return Extensions.CreateDelegate<GetMouseVectorDelegate>((MethodBase)val4.Generate()); } } public bool GetKey(string name) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return _getKey(GetKeyCode(name)); } public bool GetKey(KeyCode key) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) return _getKey(key); } public bool GetKeyDown(string name) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return _getKeyDown(GetKeyCode(name)); } public bool GetKeyDown(KeyCode key) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) return _getKeyDown(key); } public bool GetKeyUp(string name) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return _getKeyUp(GetKeyCode(name)); } public bool GetKeyUp(KeyCode key) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) return _getKeyUp(key); } public bool GetMouseButton(int button) { return _getMouseButton((KeyCode)(323 + button)); } public bool GetMouseButtonDown(int button) { return _getMouseButtonDown((KeyCode)(323 + button)); } public bool GetMouseButtonUp(int button) { return _getMouseButtonUp((KeyCode)(323 + button)); } public void ResetInputAxes() { } private static KeyCode GetKeyCode(string name) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) return (KeyCode)Enum.Parse(typeof(KeyCode), name, ignoreCase: true); } private static bool TryEnumParse<T>(string name, out T val) { try { val = (T)Enum.Parse(typeof(T), name, ignoreCase: true); return true; } catch (Exception) { val = default(T); return false; } } } internal class LegacyInputSystem : IInputSystem { public Vector3 mousePosition => Input.mousePosition; public Vector2 mouseScrollDelta => Input.mouseScrollDelta; public bool mousePresent => Input.mousePresent; public bool anyKey => Input.anyKey; public bool anyKeyDown => Input.anyKeyDown; public IEnumerable<KeyCode> SupportedKeyCodes { get; } = (KeyCode[])Enum.GetValues(typeof(KeyCode)); public bool GetKey(string name) { return Input.GetKey(name); } public bool GetKey(KeyCode key) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return Input.GetKey(key); } public bool GetKeyDown(string name) { return Input.GetKeyDown(name); } public bool GetKeyDown(KeyCode key) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return Input.GetKeyDown(key); } public bool GetKeyUp(string name) { return Input.GetKeyUp(name); } public bool GetKeyUp(KeyCode key) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return Input.GetKeyUp(key); } public bool GetMouseButton(int button) { return Input.GetMouseButton(button); } public bool GetMouseButtonDown(int button) { return Input.GetMouseButtonDown(button); } public bool GetMouseButtonUp(int button) { return Input.GetMouseButtonUp(button); } public void ResetInputAxes() { Input.ResetInputAxes(); } } internal class NullInputSystem : IInputSystem { private static readonly KeyCode[] NoKeys = (KeyCode[])(object)new KeyCode[0]; public Vector3 mousePosition => Vector3.zero; public Vector2 mouseScrollDelta => Vector2.zero; public bool mousePresent => false; public bool anyKey => false; public bool anyKeyDown => false; public IEnumerable<KeyCode> SupportedKeyCodes => NoKeys; public bool GetKey(string name) { return false; } public bool GetKey(KeyCode key) { return false; } public bool GetKeyDown(string name) { return false; } public bool GetKeyDown(KeyCode key) { return false; } public bool GetKeyUp(string name) { return false; } public bool GetKeyUp(KeyCode key) { return false; } public bool GetMouseButton(int button) { return false; } public bool GetMouseButtonDown(int button) { return false; } public bool GetMouseButtonUp(int button) { return false; } public void ResetInputAxes() { } } public static class Utility { private static bool? sreEnabled; public static bool CLRSupportsDynamicAssemblies => CheckSRE(); public static Encoding UTF8NoBom { get; } = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); private static bool CheckSRE() { if (sreEnabled.HasValue) { return sreEnabled.Value; } try { new CustomAttributeBuilder(null, new object[0]); } catch (PlatformNotSupportedException) { sreEnabled = false; return sreEnabled.Value; } catch (ArgumentNullException) { } sreEnabled = true; return sreEnabled.Value; } public static bool TryDo(Action action, out Exception exception) { exception = null; try { action(); return true; } catch (Exception ex) { exception = ex; return false; } } public static string CombinePaths(params string[] parts) { return parts.Aggregate(Path.Combine); } public static string ParentDirectory(string path, int levels = 1) { for (int i = 0; i < levels; i++) { path = Path.GetDirectoryName(path); } return path; } public static bool SafeParseBool(string input, bool defaultValue = false) { bool result; return bool.TryParse(input, out result) ? result : defaultValue; } public static string ConvertToWWWFormat(string path) { return "file://" + path.Replace('\\', '/'); } public static bool IsNullOrWhiteSpace(this string self) { return self?.All(char.IsWhiteSpace) ?? true; } public static IEnumerable<TNode> TopologicalSort<TNode>(IEnumerable<TNode> nodes, Func<TNode, IEnumerable<TNode>> dependencySelector) { List<TNode> sorted_list = new List<TNode>(); HashSet<TNode> visited = new HashSet<TNode>(); HashSet<TNode> sorted = new HashSet<TNode>(); foreach (TNode node in nodes) { Stack<TNode> stack2 = new Stack<TNode>(); if (!Visit(node, stack2)) { throw new Exception("Cyclic Dependency:\r\n" + stack2.Select((TNode x) => $" - {x}").Aggregate((string a, string b) => a + "\r\n" + b)); } } return sorted_list; bool Visit(TNode node, Stack<TNode> stack) { if (visited.Contains(node)) { if (!sorted.Contains(node)) { return false; } } else { visited.Add(node); stack.Push(node); foreach (TNode item in dependencySelector(node)) { if (!Visit(item, stack)) { return false; } } sorted.Add(node); sorted_list.Add(node); stack.Pop(); } return true; } } private static bool TryResolveDllAssembly<T>(AssemblyName assemblyName, string directory, Func<string, T> loader, out T assembly) where T : class { assembly = null; List<string> list = new List<string> { directory }; list.AddRange(Directory.GetDirectories(directory, "*", SearchOption.AllDirectories)); foreach (string item in list) { string text = Path.Combine(item, assemblyName.Name + ".dll"); if (!File.Exists(text)) { continue; } try { assembly = loader(text); } catch (Exception) { continue; } return true; } return false; } public static bool IsSubtypeOf(this TypeDefinition self, Type td) { if (((MemberReference)self).FullName == td.FullName) { return true; } int result; if (((MemberReference)self).FullName != "System.Object") { TypeReference baseType = self.BaseType; result = (((baseType == null) ? null : baseType.Resolve()?.IsSubtypeOf(td)).GetValueOrDefault() ? 1 : 0); } else { result = 0; } return (byte)result != 0; } public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, out Assembly assembly) { return TryResolveDllAssembly(assemblyName, directory, (Func<string, Assembly>)Assembly.LoadFile, out assembly); } public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, ReaderParameters readerParameters, out AssemblyDefinition assembly) { return TryResolveDllAssembly(assemblyName, directory, (Func<string, AssemblyDefinition>)((string s) => AssemblyDefinition.ReadAssembly(s, readerParameters)), out assembly); } public static bool TryOpenFileStream(string path, FileMode mode, out FileStream fileStream, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read) { try { fileStream = new FileStream(path, mode, access, share); return true; } catch (IOException) { fileStream = null; return false; } } public static bool TryParseAssemblyName(string fullName, out AssemblyName assemblyName) { try { assemblyName = new AssemblyName(fullName); return true; } catch (Exception) { assemblyName = null; return false; } } public static IEnumerable<string> GetUniqueFilesInDirectories(IEnumerable<string> directories, string pattern = "*") { Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); foreach (string directory in directories) { string[] files = Directory.GetFiles(directory, pattern); foreach (string text in files) { string fileName = Path.GetFileName(text); if (!dictionary.ContainsKey(fileName)) { dictionary[fileName] = text; } } } return dictionary.Values; } } } namespace BepInEx.Logging { public class ConsoleLogListener : ILogListener, IDisposable { private static readonly ConfigEntry<LogLevel> ConfigConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind("Logging.Console", "LogLevels", LogLevel.Fatal | LogLevel.Error | LogLevel.Warning | LogLevel.Message | LogLevel.Info, "Which log levels to show in the console output."); internal bool WriteUnityLogs { get; set; } = true; public void LogEvent(object sender, LogEventArgs eventArgs) { if ((WriteUnityLogs || !(sender is UnityLogSource)) && (eventArgs.Level & ConfigConsoleDisplayedLevel.Value) != 0) { ConsoleManager.SetConsoleColor(eventArgs.Level.GetConsoleColor()); ConsoleManager.ConsoleStream?.Write(eventArgs.ToStringLine()); ConsoleManager.SetConsoleColor(ConsoleColor.Gray); } } public void Dispose() { } } public class DiskLogListener : ILogListener, IDisposable { public LogLevel DisplayedLogLevel { get; set; } public TextWriter LogWriter { get; protected set; } public Timer FlushTimer { get; protected set; } public bool WriteFromUnityLog { get; set; } public string FileFullPath { get; protected set; } public DiskLogListener(string localPath, LogLevel displayedLogLevel = LogLevel.Info, bool appendLog = false, bool includeUnityLog = false) { WriteFromUnityLog = includeUnityLog; DisplayedLogLevel = displayedLogLevel; int num = 1; string text = Path.Combine(Paths.BepInExRootPath, localPath); FileStream fileStream; while (!Utility.TryOpenFileStream(text, appendLog ? FileMode.Append : FileMode.Create, out fileStream, FileAccess.Write)) { if (num == 5) { Logger.LogError("Couldn't open a log file for writing. Skipping log file creation"); return; } Logger.LogWarning("Couldn't open log file '" + localPath + "' for writing, trying another..."); localPath = $"LogOutput.log.{num++}"; text = Path.Combine(Paths.BepInExRootPath, localPath); } LogWriter = TextWriter.Synchronized(new StreamWriter(fileStream, Utility.UTF8NoBom)); FileFullPath = text; FlushTimer = new Timer(delegate { LogWriter?.Flush(); }, null, 2000, 2000); } public void LogEvent(object sender, LogEventArgs eventArgs) { if ((WriteFromUnityLog || !(eventArgs.Source is UnityLogSource)) && (eventArgs.Level & DisplayedLogLevel) != 0) { LogWriter.WriteLine(eventArgs.ToString()); } } public void Dispose() { FlushTimer?.Dispose(); LogWriter?.Flush(); LogWriter?.Dispose(); } ~DiskLogListener() { Dispose(); } } internal class HarmonyLogSource : ILogSource, IDisposable { private static readonly ConfigEntry<LogChannel> LogChannels = ConfigFile.CoreConfig.Bind<LogChannel>("Harmony.Logger", "LogChannels", (LogChannel)24, "Specifies which Harmony log channels to listen to.\nNOTE: IL channel dumps the whole patch methods, use only when needed!"); private static readonly Dictionary<LogChannel, LogLevel> LevelMap = new Dictionary<LogChannel, LogLevel> { [(LogChannel)2] = LogLevel.Info, [(LogChannel)8] = LogLevel.Warning, [(LogChannel)16] = LogLevel.Error, [(LogChannel)4] = LogLevel.Debug }; public string SourceName { get; } = "HarmonyX"; public event EventHandler<LogEventArgs> LogEvent; public HarmonyLogSource() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) Logger.ChannelFilter = LogChannels.Value; Logger.MessageReceived += HandleHarmonyMessage; } private void HandleHarmonyMessage(object sender, LogEventArgs e) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) if (LevelMap.TryGetValue(e.LogChannel, out var value)) { this.LogEvent?.Invoke(this, new LogEventArgs(e.Message, value, this)); } } public void Dispose() { Logger.MessageReceived -= HandleHarmonyMessage; } } public interface ILogListener : IDisposable { void LogEvent(object sender, LogEventArgs eventArgs); } public interface ILogSource : IDisposable { string SourceName { get; } event EventHandler<LogEventArgs> LogEvent; } public class LogEventArgs : EventArgs { public object Data { get; protected set; } public LogLevel Level { get; protected set; } public ILogSource Source { get; protected set; } public LogEventArgs(object data, LogLevel level, ILogSource source) { Data = data; Level = level; Source = source; } public override string ToString() { return $"[{Level,-7}:{Source.SourceName,10}] {Data}"; } public string ToStringLine() { return ToString() + Environment.NewLine; } } public static class Logger { private sealed class LogSourceCollection : ThreadSafeCollection<ILogSource>, ICollection<ILogSource>, IEnumerable<ILogSource>, IEnumerable { public override void Add(ILogSource item) { if (item == null) { throw new ArgumentNullException("item", "Log sources cannot be null when added to the source list."); } lock (Lock) { item.LogEvent += InternalLogEvent; List<ILogSource> list = new List<ILogSource>(BaseList.Count + 1); list.AddRange(BaseList); list.Add(item); BaseList = list; } } public override void Clear() { if (base.Count == 0) { return; } lock (Lock) { for (int i = 0; i < BaseList.Count; i++) { BaseList[i].LogEvent -= InternalLogEvent; } BaseList = new List<ILogSource>(0); } } public override bool Remove(ILogSource item) { if (item == null) { return false; } lock (Lock) { bool flag = base.Remove(item); if (flag) { item.LogEvent -= InternalLogEvent; } return flag; } } } private sealed class LogListenerCollection : ThreadSafeCollection<ILogListener> { public void SendLogEvent(object sender, LogEventArgs eventArgs) { List<ILogListener> baseList = BaseList; for (int i = 0; i < baseList.Count; i++) { baseList[i].LogEvent(sender, eventArgs); } } } private class ThreadSafeCollection<T> : ICollection<T>, IEnumerable<T>, IEnumerable where T : class { protected readonly object Lock = new object(); protected List<T> BaseList = new List<T>(0); public int Count => BaseList.Count; public bool IsReadOnly => false; public IEnumerator<T> GetEnumerator() { return BaseList.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return BaseList.GetEnumerator(); } public virtual void Add(T item) { if (item == null) { throw new ArgumentNullException("item", "item can't be null"); } lock (Lock) { List<T> list = new List<T>(BaseList.Count + 1); list.AddRange(BaseList); list.Add(item); BaseList = list; } } public virtual void Clear() { if (Count == 0) { return; } lock (Lock) { BaseList = new List<T>(0); } } public bool Contains(T item) { return BaseList.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { BaseList.CopyTo(array, arrayIndex); } public virtual bool Remove(T item) { if (item == null) { return false; } lock (Lock) { List<T> list = new List<T>(BaseList.Count); bool result = false; for (int i = 0; i < BaseList.Count; i++) { T val = BaseList[i]; if (val.Equals(item)) { result = true; } else { list.Add(val); } } BaseList = list; return result; } } } private static readonly LogListenerCollection _Listeners = new LogListenerCollection(); private static readonly ManualLogSource InternalLogSource = CreateLogSource("BepInEx"); private static bool internalLogsInitialized; public static ICollection<ILogListener> Listeners => _Listeners; public static ICollection<ILogSource> Sources { get; } = new LogSourceCollection(); internal static void InitializeInternalLoggers() { if (!internalLogsInitialized) { Sources.Add(new HarmonyLogSource()); internalLogsInitialized = true; } } internal static void InternalLogEvent(object sender, LogEventArgs eventArgs) { _Listeners.SendLogEvent(sender, eventArgs); } internal static void Log(LogLevel level, object data) { InternalLogSource.Log(level, data); } internal static void LogFatal(object data) { Log(LogLevel.Fatal, data); } internal static void LogError(object data) { Log(LogLevel.Error, data); } internal static void LogWarning(object data) { Log(LogLevel.Warning, data); } internal static void LogMessage(object data) { Log(LogLevel.Message, data); } internal static void LogInfo(object data) { Log(LogLevel.Info, data); } internal static void LogDebug(object data) { Log(LogLevel.Debug, data); } public static ManualLogSource CreateLogSource(string sourceName) { ManualLogSource manualLogSource = new ManualLogSource(sourceName); Sources.Add(manualLogSource); return manualLogSource; } } [Flags] public enum LogLevel { None = 0, Fatal = 1, Error = 2, Warning = 4, Message = 8, Info = 0x10, Debug = 0x20, All = 0x3F } public static class LogLevelExtensions { public static LogLevel GetHighestLevel(this LogLevel levels) { Array values = Enum.GetValues(typeof(LogLevel)); Array.Sort(values); foreach (LogLevel item in values) { if ((levels & item) != 0) { return item; } } return LogLevel.None; } public static ConsoleColor GetConsoleColor(this LogLevel level) { level = level.GetHighestLevel(); return level switch { LogLevel.Fatal => ConsoleColor.Red, LogLevel.Error => ConsoleColor.DarkRed, LogLevel.Warning => ConsoleColor.Yellow, LogLevel.Message => ConsoleColor.White, LogLevel.Debug => ConsoleColor.DarkGray, _ => ConsoleColor.Gray, }; } } public class ManualLogSource : ILogSource, IDisposable { public string SourceName { get; } public event EventHandler<LogEventArgs> LogEvent; public ManualLogSource(string sourceName) { SourceName = sourceName; } public void Log(LogLevel level, object data) { this.LogEvent?.Invoke(this, new LogEventArgs(data, level, this)); } public void LogFatal(object data) { Log(LogLevel.Fatal, data); } public void LogError(object data) { Log(LogLevel.Error, data); } public void LogWarning(object data) { Log(LogLevel.Warning, data); } public void LogMessage(object data) { Log(LogLevel.Message, data); } public void LogInfo(object data) { Log(LogLevel.Info, data); } public void LogDebug(object data) { Log(LogLevel.Debug, data); } public void Dispose() { } } public class TraceLogSource : TraceListener { private static TraceLogSource traceListener; public static bool IsListening { get; protected set; } protected ManualLogSource LogSource { get; } public static ILogSource CreateSource() { if (traceListener == null) { traceListener = new TraceLogSource(); Trace.Listeners.Add(traceListener); IsListening = true; } return traceListener.LogSource; } protected TraceLogSource() { LogSource = new ManualLogSource("Trace"); } public override void Write(string message) { LogSource.LogInfo(message); } public override void WriteLine(string message) { LogSource.LogInfo(message); } public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args) { TraceEvent(eventCache, source, eventType, id, string.Format(format, args)); } public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { LogSource.Log(eventType switch { TraceEventType.Critical => LogLevel.Fatal, TraceEventType.Error => LogLevel.Error, TraceEventType.Warning => LogLevel.Warning, TraceEventType.Information => LogLevel.Info, _ => LogLevel.Debug, }, (message ?? "").Trim()); } } public class UnityLogListener : ILogListener, IDisposable { internal static readonly Action<string> WriteStringToUnityLog; private ConfigEntry<bool> LogConsoleToUnity = ConfigFile.CoreConfig.Bind("Logging", "LogConsoleToUnityLog", defaultValue: false, new StringBuilder().AppendLine("If enabled, writes Standard Output messages to Unity log").AppendLine("NOTE: By default, Unity does so automatically. Only use this option if no console messages are visible in Unity log").ToString()); static UnityLogListener() { MethodInfo[] methods = typeof(UnityLogWriter).GetMethods(BindingFlags.Static | BindingFlags.Public); foreach (MethodInfo methodInfo in methods) { try { methodInfo.Invoke(null, new object[1] { "" }); } catch { continue; } WriteStringToUnityLog = (Action<string>)Delegate.CreateDelegate(typeof(Action<string>), methodInfo); break; } if (WriteStringToUnityLog == null) { Logger.LogError("Unable to start Unity log writer"); } } public void LogEvent(object sender, LogEventArgs eventArgs) { if (!(eventArgs.Source is UnityLogSource) && (LogConsoleToUnity.Value || eventArgs.Source.SourceName != "Console")) { WriteStringToUnityLog?.Invoke(eventArgs.ToStringLine()); } } public void Dispose() { } } public class UnityLogSource : ILogSource, IDisposable { private bool disposed = false; public string SourceName { get; } = "Unity Log"; public event EventHandler<LogEventArgs> LogEvent; private static event EventHandler<LogEventArgs> InternalUnityLogMessage; public UnityLogSource() { InternalUnityLogMessage += UnityLogMessageHandler; } private void UnityLogMessageHandler(object sender, LogEventArgs eventArgs) { LogEventArgs e = new LogEventArgs(eventArgs.Data, eventArgs.Level, this); this.LogEvent?.Invoke(this, e); } public void Dispose() { if (!disposed) { InternalUnityLogMessage -= UnityLogMessageHandler; disposed = true; } } static UnityLogSource() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown LogCallback val = new LogCallback(OnUnityLogMessageReceived); EventInfo @event = typeof(Application).GetEvent("logMessageReceived", BindingFlags.Static | BindingFlags.Public); if (@event != null) { @event.AddEventHandler(null, (Delegate?)(object)val); return; } MethodInfo method = typeof(Application).GetMethod("RegisterLogCallback", BindingFlags.Static | BindingFlags.Public); method.Invoke(null, new object[1] { val }); } private static void OnUnityLogMessageReceived(string message, string stackTrace, LogType type) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected I4, but got Unknown //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Invalid comparison between Unknown and I4 LogLevel level; switch ((int)type) { case 0: case 1: case 4: level = LogLevel.Error; break; case 2: level = LogLevel.Warning; break; default: level = LogLevel.Info; break; } if ((int)type == 4) { message = message + "\nStack trace:\n" + stackTrace; } UnityLogSource.InternalUnityLogMessage?.Invoke(null, new LogEventArgs(message, level, null)); } } } namespace BepInEx.ConsoleUtil { internal class Kon { private struct CONSOLE_SCREEN_BUFFER_INFO { internal COORD dwSize; internal COORD dwCursorPosition; internal short wAttributes; internal SMALL_RECT srWindow; internal COORD dwMaximumWindowSize; } private struct COORD { internal short X; internal short Y; } private struct SMALL_RECT { internal short Left; internal short Top; internal short Right; internal short Bottom; } private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); internal static IntPtr conOut = IntPtr.Zero; public static ConsoleColor ForegroundColor { get { return GetConsoleColor(isBackground: false); } set { SetConsoleColor(isBackground: false, value); } } public static ConsoleColor BackgroundColor { get { return GetConsoleColor(isBackground: true); } set { SetConsoleColor(isBackground: true, value); } } [DllImport("kernel32.dll", SetLastError = true)] private static extern bool GetConsoleScreenBufferInfo(IntPtr hConsoleOutput, out CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput, short attributes); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetStdHandle(int nStdHandle); private static short ConsoleColorToColorAttribute(short color, bool isBackground) { if (((uint)color & 0xFFFFFFF0u) != 0) { throw new ArgumentException("Arg_InvalidConsoleColor"); } if (isBackground) { color <<= 4; } return color; } private static CONSOLE_SCREEN_BUFFER_INFO GetBufferInfo(bool throwOnNoConsole, out bool succeeded) { succeeded = false; if (!(conOut == INVALID_HANDLE_VALUE)) { if (!GetConsoleScreenBufferInfo(conOut, out var lpConsoleScreenBufferInfo)) { bool consoleScreenBufferInfo = GetConsoleScreenBufferInfo(GetStdHandle(-12), out lpConsoleScreenBufferInfo); if (!consoleScreenBufferInfo) { consoleScreenBufferInfo = GetConsoleScreenBufferInfo(GetStdHandle(-10), out lpConsoleScreenBufferInfo); } if (!consoleScreenBufferInfo && Marshal.GetLastWin32Error() == 6 && !throwOnNoConsole) { return default(CONSOLE_SCREEN_BUFFER_INFO); } } succeeded = true; return lpConsoleScreenBufferInfo; } if (!throwOnNoConsole) { return default(CONSOLE_SCREEN_BUFFER_INFO); } throw new Exception("IO.IO_NoConsole"); } private static void SetConsoleColor(bool isBackground, ConsoleColor c) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) ((CodeAccessPermission)new UIPermission((UIPermissionWindow)2)).Demand(); short num = ConsoleColorToColorAttribute((short)c, isBackground); bool succeeded; CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo(throwOnNoConsole: false, out succeeded); if (succeeded) { short wAttributes = bufferInfo.wAttributes; wAttributes &= (short)(isBackground ? (-241) : (-16)); wAttributes = (short)((ushort)wAttributes | (ushort)num); SetConsoleTextAttribute(conOut, wAttributes); } } private static ConsoleColor GetConsoleColor(bool isBackground) { bool succeeded; CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo(throwOnNoConsole: false, out succeeded); if (!succeeded) { return (!isBackground) ? ConsoleColor.Gray : ConsoleColor.Black; } return ColorAttributeToConsoleColor((short)(bufferInfo.wAttributes & 0xF0)); } private static ConsoleColor ColorAttributeToConsoleColor(short c) { if ((short)((uint)c & 0xFFu) != 0) { c >>= 4; } return (ConsoleColor)c; } public static void ResetConsoleColor() { SetConsoleColor(isBackground: true, ConsoleColor.Black); SetConsoleColor(isBackground: false, ConsoleColor.Gray); } } } namespace BepInEx.Unix { internal static class ConsoleWriter { private static Func<Stream, Encoding, bool, StreamWriter> cStreamWriterConstructor; private static Func<Stream, Encoding, bool, StreamWriter> CStreamWriterConstructor { get { if (cStreamWriterConstructor != null) { return cStreamWriterConstructor; } Type cStreamWriter = AccessTools.TypeByName("System.IO.CStreamWriter"); int[][] source = new int[2][] { new int[3] { 0, 1, 2 }, new int[2] { 0, 1 } }; cStreamWriterConstructor = source.Select(GetCtor).FirstOrDefault((Func<Stream, Encoding, bool, StreamWriter> f) => f != null); if (cStreamWriterConstructor == null) { throw new AmbiguousMatchException("Failed to find suitable constructor for CStreamWriter"); } return cStreamWriterConstructor; Func<Stream, Encoding, bool, StreamWriter> GetCtor(int[] perm) { Type[] parameters = new Type[3] { typeof(Stream), typeof(Encoding), typeof(bool) }; ConstructorInfo ctor = AccessTools.Constructor(cStreamWriter, perm.Select((int i) => parameters[i]).ToArray(), false); if (ctor != null) { return delegate(Stream stream, Encoding encoding, bool l) { object[] vals = new object[3] { stream, encoding, l }; return (StreamWriter)ctor.Invoke(perm.Select((int i) => vals[i]).ToArray()); }; } return null; } } } public static TextWriter CreateConsoleStreamWriter(Stream stream, Encoding encoding, bool leaveOpen) { StreamWriter streamWriter = CStreamWriterConstructor(stream, encoding, leaveOpen); streamWriter.AutoFlush = true; return streamWriter; } } internal class LinuxConsoleDriver : IConsoleDriver { private static readonly ConfigEntry<bool> ForceCustomTtyDriverConfig; public static bool UseMonoTtyDriver { get; } public TextWriter StandardOut { get; private set; } public TextWriter ConsoleOut { get; private set; } public bool ConsoleActive { get; private set; } public bool ConsoleIsExternal => false; public bool StdoutRedirected { get; private set; } public TtyInfo TtyInfo { get; private set; } static LinuxConsoleDriver() { ForceCustomTtyDriverConfig = ConfigFile.CoreConfig.Bind("Logging.Console", "ForceBepInExTTYDriver", defaultValue: false, "If enabled, forces to use custom BepInEx TTY driver for handling terminal output on unix."); UseMonoTtyDriver = false; if (!ForceCustomTtyDriverConfig.Value) { Type type = typeof(Console).Assembly.GetType("System.ConsoleDriver"); if (type != null) { UseMonoTtyDriver = typeof(Console).Assembly.GetType("System.ParameterizedStrings") != null; } } } public void PreventClose() { } public void Initialize(bool alreadyActive) { ConsoleActive = true; StdoutRedirected = UnixStreamHelper.isatty(1) != 1; Stream stream = UnixStreamHelper.CreateDuplicateStream(1); if (UseMonoTtyDriver && !StdoutRedirected) { TextWriter textWriter = ConsoleWriter.CreateConsoleStreamWriter(stream, Console.Out.Encoding, leaveOpen: true); StandardOut = TextWriter.Synchronized(textWriter); object value = AccessTools.Field(AccessTools.TypeByName("System.ConsoleDriver"), "driver").GetValue(null); AccessTools.Field(AccessTools.TypeByName("System.TermInfoDriver"), "stdout").SetValue(value, textWriter); } else { StreamWriter streamWriter = new StreamWriter(stream, Console.Out.Encoding); streamWriter.AutoFlush = true; StandardOut = TextWriter.Synchronized(streamWriter); TtyInfo = TtyHandler.GetTtyInfo(); } ConsoleOut = StandardOut; } public void CreateConsole(uint codepage) { Logger.LogWarning("An external console currently cannot be spawned on a Unix platform."); } public void DetachConsole() { throw new PlatformNotSupportedException("Cannot detach console on a Unix platform"); } public void SetConsoleColor(ConsoleColor color) { if (!StdoutRedirected) { if (UseMonoTtyDriver) { SafeConsole.ForegroundColor = color; } else { ConsoleOut.Write(TtyInfo.GetAnsiCode(color)); } } } public void SetConsoleTitle(string title) { if (!StdoutRedirected) { if (UseMonoTtyDriver && SafeConsole.TitleExists) { SafeConsole.Title = title; } else { ConsoleOut.Write("\u001b]2;" + title.Replace("\\", "\\\\") + "\a"); } } } } internal class TtyInfo { public string TerminalType { get; set; } = "default"; public int MaxColors { get; set; } public string[] ForegroundColorStrings { get; set; } public static TtyInfo Default { get; } = new TtyInfo { MaxColors = 0 }; public string GetAnsiCode(ConsoleColor color) { if (MaxColors <= 0 || ForegroundColorStrings == null) { return string.Empty; } int num = (int)color % MaxColors; return ForegroundColorStrings[num]; } } internal static class TtyHandler { private static readonly string[] ncursesLocations = new string[4] { "/usr/share/terminfo", "/etc/terminfo", "/usr/lib/terminfo", "/lib/terminfo" }; private static string TryTermInfoDir(string dir, string term) { string text = $"{dir}/{(int)term[0]:x}/{term}"; if (File.Exists(text)) { return text; } text = Utility.CombinePaths(dir, term.Substring(0, 1), term); if (File.Exists(text)) { return text; } return null; } private static string FindTermInfoPath(string term) { if (string.IsNullOrEmpty(term)) { return null; } string environmentVariable = Environment.GetEnvironmentVariable("TERMINFO"); if (environmentVariable != null && Directory.Exists(environmentVariable)) { string text = TryTermInfoDir(environmentVariable, term); if (text != null) { return text; } } string[] array = ncursesLocations; foreach (string text2 in array) { if (Directory.Exists(text2)) { string text3 = TryTermInfoDir(text2, term); if (text3 != null) { return text3; } } } return null; } public static TtyInfo GetTtyInfo(string terminal = null) { terminal = terminal ?? Environment.GetEnvironmentVariable("TERM"); string text = FindTermInfoPath(terminal); if (text == null) { return TtyInfo.Default; } byte[] buffer = File.ReadAllBytes(text); TtyInfo ttyInfo = TtyInfoParser.Parse(buffer); ttyInfo.TerminalType = terminal; return ttyInfo; } } internal static class TtyInfoParser { internal enum TermInfoNumbers { MaxColors = 13 } internal enum TermInfoStrings { SetAForeground = 359 } private static readonly int[] ansiColorMapping = new int[16] { 0, 4, 2, 6, 1, 5, 3, 7, 8, 12, 10, 14, 9, 13, 11, 15 }; public static TtyInfo Parse(byte[] buffer) { int num; switch (GetInt16(buffer, 0)) { case 282: num = 2; break; case 542: num = 4; break; default: return TtyInfo.Default; } int @int = GetInt16(buffer, 4); int int2 = GetInt16(buffer, 6); int int3 = GetInt16(buffer, 8); int num2 = 12 + GetString(buffer, 12).Length + 1; num2 += @int; num2 += num2 % 2; int offset = num2 + num * 13; TtyInfo ttyInfo = new TtyInfo(); ttyInfo.MaxColors = GetInteger(num, buffer, offset); ttyInfo.ForegroundColorStrings = ansiColorMapping.Select((int x) => $"\u001b[{((x > 7) ? (82 + x) : (30 + x))}m").ToArray(); return ttyInfo; } private static int GetInt32(byte[] buffer, int offset) { return buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24); } private static short GetInt16(byte[] buffer, int offset) { return (short)(buffer[offset] | (buffer[offset + 1] << 8)); } private static int GetInteger(int intSize, byte[] buffer, int offset) { return (intSize == 2) ? GetInt16(buffer, offset) : GetInt32(buffer, offset); } private static string GetString(byte[] buffer, int offset) { int i; for (i = 0; buffer[offset + i] != 0; i++) { } return Encoding.ASCII.GetString(buffer, offset, i); } } internal class UnixStream : Stream { public override bool CanRead => Access == FileAccess.Read || Access == FileAccess.ReadWrite; public override bool CanSeek => false; public override bool CanWrite => Access == FileAccess.Write || Access == FileAccess.ReadWrite; public override long Length { get { throw new InvalidOperationException(); } } public override long Position { get { throw new InvalidOperationException(); } set { throw new InvalidOperationException(); } } public FileAccess Access { get; } public IntPtr FileHandle { get; } public UnixStream(int fileDescriptor, FileAccess access) { Access = access; int fd = UnixStreamHelper.dup(fileDescriptor); FileHandle = UnixStreamHelper.fdopen(fd, (access == FileAccess.Write) ? "w" : "r"); } public override void Flush() { UnixStreamHelper.fflush(FileHandle); } public override long Seek(long offset, SeekOrigin origin) { throw new InvalidOperationException(); } public override void SetLength(long value) { throw new InvalidOperationException(); } public override int Read(byte[] buffer, int offset, int count) { GCHandle gCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); IntPtr intPtr = UnixStreamHelper.fread(new IntPtr(gCHandle.AddrOfPinnedObject().ToInt64() + offset), (IntPtr)count, (IntPtr)1, FileHandle); gCHandle.Free(); return intPtr.ToInt32(); } public override void Write(byte[] buffer, int offset, int count) { GCHandle gCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); UnixStreamHelper.fwrite(new IntPtr(gCHandle.AddrOfPinnedObject().ToInt64() + offset), (IntPtr)count, (IntPtr)1, FileHandle); gCHandle.Free(); } private void ReleaseUnmanagedResources() { UnixStreamHelper.fclose(FileHandle); } protected override void Dispose(bool disposing) { ReleaseUnmanagedResources(); base.Dispose(disposing); } ~UnixStream() { Dispose(disposing: false); } } internal static class UnixStreamHelper { public delegate int dupDelegate(int fd); public delegate IntPtr fdopenDelegate(int fd, string mode); public delegate IntPtr freadDelegate(IntPtr ptr, IntPtr size, IntPtr nmemb, IntPtr stream); public delegate int fwriteDelegate(IntPtr ptr, IntPtr size, IntPtr nmemb, IntPtr stream); public delegate int fcloseDelegate(IntPtr stream); public delegate int fflushDelegate(IntPtr stream); public delegate int isattyDelegate(int fd); [DynDllImport("libc", new string[] { })] public static dupDelegate dup; [DynDllImport("libc", new string[] { })] public static fdopenDelegate fdopen; [DynDllImport("libc", new string[] { })] public static freadDelegate fread; [DynDllImport("libc", new string[] { })] public static fwriteDelegate fwrite; [DynDllImport("libc", new string[] { })] public static fcloseDelegate fclose; [DynDllImport("libc", new string[] { })] public static fflushDelegate fflush; [DynDllImport("libc", new string[] { })] public static isattyDelegate isatty; static UnixStreamHelper() { Dictionary<string, List<DynDllMapping>> dictionary = new Dictionary<string, List<DynDllMapping>> { ["libc"] = new List<DynDllMapping> { DynDllMapping.op_Implicit("libc.so.6"), DynDllMapping.op_Implicit("libc"), DynDllMapping.op_Implicit("/usr/lib/libSystem.dylib") } }; DynDll.ResolveDynDllImports(typeof(UnixStreamHelper), dictionary); } public static Stream CreateDuplicateStream(int fileDescriptor) { int fileDescriptor2 = dup(fileDescriptor); return new UnixStream(fileDescriptor2, FileAccess.Write); } } } namespace BepInEx.Configuration { public abstract class AcceptableValueBase { public Type ValueType { get; } protected AcceptableValueBase(Type valueType) { ValueType = valueType; } public abstract object Clamp(object value); public abstract bool IsValid(object value); public abstract string ToDescriptionString(); } public class AcceptableValueList<T> : AcceptableValueBase where T : IEquatable<T> { public virtual T[] AcceptableValues { get; } public AcceptableValueList(params T[] acceptableValues) : base(typeof(T)) { if (acceptableValues == null) { throw new ArgumentNullException("acceptableValues"); } if (acceptableValues.Length == 0) { throw new ArgumentException("At least one acceptable value is needed", "acceptableValues"); } AcceptableValues = acceptableValues; } public override object Clamp(object value) { if (IsValid(value)) { return value; } return AcceptableValues[0]; } public override bool IsValid(object value) { int result; if (value is T) { T v = (T)value; result = (AcceptableValues.Any((T x) => x.Equals(v)) ? 1 : 0); } else { result = 0; } return (byte)result != 0; } public override string ToDescriptionString() { return "# Acceptable values: " + string.Join(", ", AcceptableValues.Select((T x) => x.ToString()).ToArray()); } } public class AcceptableValueRange<T> : AcceptableValueBase where T : IComparable { public virtual T MinValue { get; } public virtual T MaxValue { get; } public AcceptableValueRange(T minValue, T maxValue) : base(typeof(T)) { if (maxValue == null) { throw new ArgumentNullException("maxValue"); } if (minValue == null) { throw new ArgumentNullException("minValue"); } if (minValue.CompareTo(maxValue) >= 0) { throw new ArgumentException("minValue has to be lower than maxValue"); } MinValue = minValue; MaxValue = maxValue; } public override object Clamp(object value) { if (MinValue.CompareTo(value) > 0) { return MinValue; } if (MaxValue.CompareTo(value) < 0) { return MaxValue; } return value; } public override bool IsValid(object value) { return MinValue.CompareTo(value) <= 0 && MaxValue.CompareTo(value) >= 0; } public override string ToDescriptionString() { return $"# Acceptable value range: From {MinValue} to {MaxValue}"; } } public class ConfigDefinition : IEquatable<ConfigDefinition> { private static readonly char[] _invalidConfigChars = new char[8] { '=', '\n', '\t', '\\', '"', '\'', '[', ']' }; public string Section { get; } public string Key { get; } public ConfigDefinition(string section, string key) { CheckInvalidConfigChars(section, "section"); CheckInvalidConfigChars(key, "key"); Key = key; Section = section; } private static void CheckInvalidConfigChars(string val, string name) { if (val == null) { throw new ArgumentNullException(name); } if (val != val.Trim()) { throw new ArgumentException("Cannot use whitespace characters at start or end of section and key names", name); } if (val.Any((char c) => _invalidConfigChars.Contains(c))) { throw new ArgumentException("Cannot use any of the following characters in section and key names: = \\n \\t \\ \" ' [ ]", name); } } [Obsolete("description argument is no longer used, put it in a ConfigDescription instead")] public ConfigDefinition(string section, string key, string description) { Key = key ?? ""; Section = section ?? ""; } public bool Equals(ConfigDefinition other) { if (other == null) { return false; } return string.Equals(Key, other.Key) && string.Equals(Section, other.Section); } public override bool Equals(object obj) { if (obj == null) { return false; } if (this == obj) { return true; } return Equals(obj as ConfigDefinition); } public override int GetHashCode() { int num = ((Key != null) ? Key.GetHashCode() : 0); return (num * 397) ^ ((Section != null) ? Section.GetHashCode() : 0); } public static bool operator ==(ConfigDefinition left, ConfigDefinition right) { return object.Equals(left, right); } public static bool operator !=(ConfigDefinition left, ConfigDefinition right) { return !object.Equals(left, right); } public override string ToString() { return Section + "." + Key; } } public class ConfigDescription { public string Description { get; } public AcceptableValueBase AcceptableValues { get; } public object[] Tags { get; } public static ConfigDescription Empty { get; } = new ConfigDescription("", null); public ConfigDescription(string description, AcceptableValueBase acceptableValues = null, params object[] tags) { AcceptableValues = acceptableValues; Tags = tags; Description = description ?? throw new ArgumentNullException("description"); } } public sealed class ConfigEntry<T> : ConfigEntryBase { private T _typedValue; public T Value { get { return _typedValue; } set { value = ClampValue(value); if (!object.Equals(_typedValue, value)) { _typedValue = value; OnSettingChanged(this); } } } public override object BoxedValue { get { return Value; } set { Value = (T)value; } } public event EventHandler SettingChanged; internal ConfigEntry(ConfigFile configFile, ConfigDefinition definition, T defaultValue, ConfigDescription configDescription) : base(configFile, definition, typeof(T), defaultValue, configDescription) { configFile.SettingChanged += delegate(object sender, SettingChangedEventArgs args) { if (args.ChangedSetting == this) { this.SettingChanged?.Invoke(sender, args); } }; } } public abstract class ConfigEntryBase { public ConfigFile ConfigFile { get; } public ConfigDefinition Definition { get; } public ConfigDescription Description { get; } public Type SettingType { get; } public object DefaultValue { get; } public abstract object BoxedValue { get; set; } internal ConfigEntryBase(ConfigFile configFile, ConfigDefinition definition, Type settingType, object defaultValue, ConfigDescription configDescription) { ConfigFile = configFile ?? throw new ArgumentNullException("configFile"); Definition = definition ?? throw new ArgumentNullException("definition"); SettingType = settingType ?? throw new ArgumentNullException("settingType"); Description = configDescription ?? ConfigDescription.Empty; if (Description.AcceptableValues != null && !SettingType.IsAssignableFrom(Description.AcceptableValues.ValueType)) { throw new ArgumentException("configDescription.AcceptableValues is for a different type than the type of this setting"); } DefaultValue = defaultValue; BoxedValue = defaultValue; } public string GetSerializedValue() { return TomlTypeConverter.ConvertToString(BoxedValue, SettingType); } public void SetSerializedValue(string value) { try { object boxedValue = TomlTypeConverter.ConvertToValue(value, SettingType); BoxedValue = boxedValue; } catch (Exception ex) { Logger.Log(LogLevel.Warning, $"Config value of setting \"{Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } } protected T ClampValue<T>(T value) { if (Description.AcceptableValues != null) { return (T)Description.AcceptableValues.Clamp(value); } return value; } protected void OnSettingChanged(object sender) { ConfigFile.OnSettingChanged(sender, this); } public void WriteDescription(StreamWriter writer) { if (!string.IsNullOrEmpty(Description.Description)) { writer.WriteLine("## " + Description.Description.Replace("\n", "\n## ")); } writer.WriteLine("# Setting type: " + SettingType.Name); writer.WriteLine("# Default value: " + TomlTypeConverter.ConvertToString(DefaultValue, SettingType)); if (Description.AcceptableValues != null) { writer.WriteLine(Description.AcceptableValues.ToDescriptionString()); } else if (SettingType.IsEnum) { writer.WriteLine("# Acceptable values: " + string.Join(", ", Enum.GetNames(SettingType))); if (SettingType.GetCustomAttributes(typeof(FlagsAttribute), inherit: true).Any()) { writer.WriteLine("# Multiple values can be set at the same time by separating them with , (e.g. Debug, Warning)"); } } } } public class ConfigFile : IDictionary<ConfigDefinition, ConfigEntryBase>, ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>, IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>, IEnumerable { private readonly BepInPlugin _ownerMetadata;
BepInEx/core/BepInEx.Harmony.dll
Decompiled a week agousing System; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using HarmonyLib; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: ComVisible(false)] [assembly: Guid("54161cfe-ff42-4dde-b161-3a49545db5cd")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("BepInEx.Harmony")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyCopyright("Copyright © Bepis 2019")] [assembly: AssemblyDescription("Harmony wrapper for BepInEx")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.0.0.0+6830e686c7931164a4e34595a34cbfa15846d1d4")] [assembly: AssemblyProduct("BepInEx.Harmony")] [assembly: AssemblyTitle("BepInEx.Harmony")] [assembly: AssemblyVersion("2.0.0.0")] namespace BepInEx.Harmony; [AttributeUsage(AttributeTargets.Method)] [Obsolete("Use HarmonyLib.ParameterByRefAttribute directly", true)] public class ParameterByRefAttribute : ParameterByRefAttribute { public int[] ParameterIndices => ((ParameterByRefAttribute)this).ParameterIndices; public ParameterByRefAttribute(params int[] parameterIndices) : base(parameterIndices) { } } public static class HarmonyExtensions { [Obsolete("Use HarmonyLib.Harmony.PatchAll directly", true)] public static void PatchAll(this Harmony harmonyInstance, Type type) { HarmonyWrapper.PatchAll(type, harmonyInstance); } } public class HarmonyWrapper { [Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll or HarmonyLib.Harmony.PatchAll", true)] public static Harmony PatchAll(Type type, Harmony harmonyInstance = null) { if (harmonyInstance == null) { return Harmony.CreateAndPatchAll(type, (string)null); } harmonyInstance.PatchAll(type); return harmonyInstance; } [Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll", true)] public static Harmony PatchAll(Type type, string harmonyInstanceId) { return Harmony.CreateAndPatchAll(type, harmonyInstanceId); } [Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll or HarmonyLib.Harmony.PatchAll", true)] public static Harmony PatchAll(Assembly assembly, Harmony harmonyInstance = null) { return assembly.GetTypes().Aggregate(harmonyInstance, (Harmony current, Type type) => PatchAll(type, current)); } [Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll", true)] public static Harmony PatchAll(Assembly assembly, string harmonyInstanceId) { return Harmony.CreateAndPatchAll(assembly, harmonyInstanceId); } [Obsolete("Use HarmonyLib.Harmony.PatchAll with no arguments", true)] public static Harmony PatchAll(Harmony harmonyInstance = null) { return PatchAll(Assembly.GetCallingAssembly(), harmonyInstance); } [Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), ...)", true)] public static Harmony PatchAll(string harmonyInstanceId) { return PatchAll(Assembly.GetCallingAssembly(), harmonyInstanceId); } [Obsolete("Use HarmonyLib.Transpilers.EmitDelegate instead", true)] public static CodeInstruction EmitDelegate<T>(T action) where T : Delegate { return Transpilers.EmitDelegate<T>(action); } }
BepInEx/core/BepInEx.Preloader.dll
Decompiled a week agousing System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using BepInEx.Preloader; using BepInEx.Preloader.Patching; using BepInEx.Preloader.RuntimeFixes; using Doorstop; using HarmonyLib; using HarmonyXInterop; using Mono.Cecil; using Mono.Cecil.Cil; using MonoMod.RuntimeDetour; using MonoMod.RuntimeDetour.Platforms; using MonoMod.Utils; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: ComVisible(false)] [assembly: Guid("f7abbe07-c02f-4f7c-bf6e-c6656bf588ca")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("BepInEx.Preloader")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyCopyright("Copyright © Bepis 2019")] [assembly: AssemblyFileVersion("5.4.23.2")] [assembly: AssemblyInformationalVersion("5.4.23.2+9cfc06ef463876e0f463f6f9a84c92d7ac346989")] [assembly: AssemblyProduct("BepInEx.Preloader")] [assembly: AssemblyTitle("BepInEx.Preloader")] [assembly: AssemblyVersion("5.4.23.2")] namespace Doorstop { internal static class Entrypoint { private static string preloaderPath; public static void Start() { string text = $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"; try { EnvVars.LoadVars(); string path = Path.GetDirectoryName(EnvVars.DOORSTOP_PROCESS_PATH) ?? "."; text = Path.Combine(path, text); preloaderPath = Path.GetDirectoryName(Path.GetFullPath(EnvVars.DOORSTOP_INVOKE_DLL_PATH)); AppDomain.CurrentDomain.AssemblyResolve += ResolveCurrentDirectory; typeof(Entrypoint).Assembly.GetType("BepInEx.Preloader.PreloaderRunner")?.GetMethod("PreloaderPreMain")?.Invoke(null, null); } catch (Exception ex) { File.WriteAllText(text, ex.ToString()); } finally { AppDomain.CurrentDomain.AssemblyResolve -= ResolveCurrentDirectory; } } internal static Assembly ResolveCurrentDirectory(object sender, ResolveEventArgs args) { AssemblyName assemblyName = new AssemblyName(args.Name); try { return Assembly.LoadFile(Path.Combine(preloaderPath, assemblyName.Name + ".dll")); } catch (Exception) { return null; } } } } namespace BepInEx.Preloader { internal static class PreloaderRunner { private static readonly string[] CriticalAssemblies = new string[7] { "Mono.Cecil.dll", "Mono.Cecil.Mdb.dll", "Mono.Cecil.Pdb.dll", "Mono.Cecil.Rocks.dll", "MonoMod.Utils.dll", "MonoMod.RuntimeDetour.dll", "0Harmony.dll" }; private static void LoadCriticalAssemblies() { string[] criticalAssemblies = CriticalAssemblies; foreach (string path in criticalAssemblies) { try { Assembly.LoadFile(Path.Combine(Paths.BepInExAssemblyDirectory, path)); } catch (Exception) { } } } public static void PreloaderPreMain() { PlatformUtils.SetPlatform(); string text = Utility.ParentDirectory(Path.GetFullPath(EnvVars.DOORSTOP_INVOKE_DLL_PATH), 2); Paths.SetExecutablePath(EnvVars.DOORSTOP_PROCESS_PATH, text, EnvVars.DOORSTOP_MANAGED_FOLDER_DIR, EnvVars.DOORSTOP_DLL_SEARCH_DIRS); LoadCriticalAssemblies(); AppDomain.CurrentDomain.AssemblyResolve += LocalResolve; AppDomain.CurrentDomain.AssemblyResolve -= Entrypoint.ResolveCurrentDirectory; PreloaderMain(); } private static void PreloaderMain() { if (Preloader.ConfigApplyRuntimePatches.Value) { XTermFix.Apply(); ConsoleSetOutFix.Apply(); } Preloader.Run(); } private static Assembly LocalResolve(object sender, ResolveEventArgs args) { AssemblyName assemblyName = default(AssemblyName); if (!Utility.TryParseAssemblyName(args.Name, ref assemblyName)) { return null; } AssemblyName assemblyName2 = default(AssemblyName); var source = (from a in AppDomain.CurrentDomain.GetAssemblies() select new { assembly = a, name = (Utility.TryParseAssemblyName(a.FullName, ref assemblyName2) ? assemblyName2 : null) } into a where a.name != null && a.name.Name == assemblyName.Name orderby a.name.Version descending select a).ToList(); Assembly assembly = (source.FirstOrDefault(a => a.name.Version == assemblyName.Version) ?? source.FirstOrDefault())?.assembly; if (assembly != null) { return assembly; } if (Utility.TryResolveDllAssembly(assemblyName, Paths.BepInExAssemblyDirectory, ref assembly) || Utility.TryResolveDllAssembly(assemblyName, Paths.PatcherPluginPath, ref assembly) || Utility.TryResolveDllAssembly(assemblyName, Paths.PluginPath, ref assembly)) { return assembly; } return null; } } public static class EnvVars { public static string DOORSTOP_INVOKE_DLL_PATH { get; private set; } public static string DOORSTOP_MANAGED_FOLDER_DIR { get; private set; } public static string DOORSTOP_PROCESS_PATH { get; private set; } public static string[] DOORSTOP_DLL_SEARCH_DIRS { get; private set; } internal static void LoadVars() { DOORSTOP_INVOKE_DLL_PATH = Environment.GetEnvironmentVariable("DOORSTOP_INVOKE_DLL_PATH"); DOORSTOP_MANAGED_FOLDER_DIR = Environment.GetEnvironmentVariable("DOORSTOP_MANAGED_FOLDER_DIR"); DOORSTOP_PROCESS_PATH = Environment.GetEnvironmentVariable("DOORSTOP_PROCESS_PATH"); DOORSTOP_DLL_SEARCH_DIRS = Environment.GetEnvironmentVariable("DOORSTOP_DLL_SEARCH_DIRS")?.Split(Path.PathSeparator) ?? new string[0]; } } public class PreloaderConsoleListener : ILogListener, IDisposable { private static readonly ConfigEntry<LogLevel> ConfigConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind<LogLevel>("Logging.Console", "LogLevels", (LogLevel)31, "Which log levels to show in the console output."); public static List<LogEventArgs> LogEvents { get; } = new List<LogEventArgs>(); public void LogEvent(object sender, LogEventArgs eventArgs) { //IL_0002: 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_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Invalid comparison between Unknown and I4 if ((eventArgs.Level & ConfigConsoleDisplayedLevel.Value) != 0) { LogEvents.Add(eventArgs); } } public void Dispose() { } } internal static class PlatformUtils { [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct utsname_osx { private const int osx_utslen = 256; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string sysname; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string nodename; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string release; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string version; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string machine; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct utsname_linux { private const int linux_utslen = 65; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] public string sysname; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] public string nodename; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] public string release; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] public string version; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] public string machine; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] public string domainname; } [DllImport("libc.so.6", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "uname")] private static extern IntPtr uname_linux(ref utsname_linux utsname); [DllImport("/usr/lib/libSystem.dylib", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "uname")] private static extern IntPtr uname_osx(ref utsname_osx utsname); public static void SetPlatform() { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_017d: 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_016c: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_0263: 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_026a: Unknown result type (might be due to invalid IL or missing references) //IL_026c: Unknown result type (might be due to invalid IL or missing references) //IL_022f: Unknown result type (might be due to invalid IL or missing references) //IL_0235: Unknown result type (might be due to invalid IL or missing references) //IL_0236: Unknown result type (might be due to invalid IL or missing references) Platform val = (Platform)17; PropertyInfo property = typeof(Environment).GetProperty("Platform", BindingFlags.Static | BindingFlags.NonPublic); string text = ((!(property != null)) ? Environment.OSVersion.Platform.ToString() : property.GetValue(null, new object[0]).ToString()); text = text.ToLowerInvariant(); if (text.Contains("win")) { val = (Platform)37; } else if (text.Contains("mac") || text.Contains("osx")) { val = (Platform)73; } else if (text.Contains("lin") || text.Contains("unix")) { val = (Platform)137; } if (Is(val, (Platform)137) && Directory.Exists("/data") && File.Exists("/system/build.prop")) { val = (Platform)393; } else if (Is(val, (Platform)8) && Directory.Exists("/System/Library/AccessibilityBundles")) { val = (Platform)585; } MethodInfo methodInfo = typeof(Environment).GetProperty("Is64BitOperatingSystem")?.GetGetMethod(); val = (Platform)((!(methodInfo != null)) ? (val | ((IntPtr.Size >= 8) ? 2 : 0)) : (val | (((bool)methodInfo.Invoke(null, new object[0])) ? 2 : 0))); if ((Is(val, (Platform)73) || Is(val, (Platform)137)) && Type.GetType("Mono.Runtime") != null) { IntPtr intPtr; string machine; if (Is(val, (Platform)73)) { utsname_osx utsname = default(utsname_osx); intPtr = uname_osx(ref utsname); machine = utsname.machine; } else { utsname_linux utsname2 = default(utsname_linux); intPtr = uname_linux(ref utsname2); machine = utsname2.machine; } if (intPtr == IntPtr.Zero && (machine.StartsWith("aarch") || machine.StartsWith("arm"))) { val = (Platform)(val | 0x10000); } } else { typeof(object).Module.GetPEKind(out var _, out var machine2); if (machine2 == ImageFileMachine.ARM) { val = (Platform)(val | 0x10000); } } PlatformHelper.Current = val; } private static bool Is(Platform current, Platform expected) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0004: Unknown result type (might be due to invalid IL or missing references) return (Platform)(current & expected) == expected; } } internal static class Preloader { private enum MonoModBackend { [Description("Auto")] auto, [Description("DynamicMethod")] dynamicmethod, [Description("MethodBuilder")] methodbuilder, [Description("Cecil")] cecil } private static readonly ConfigEntry<string> ConfigEntrypointAssembly = ConfigFile.CoreConfig.Bind<string>("Preloader.Entrypoint", "Assembly", IsPostUnity2017 ? "UnityEngine.CoreModule.dll" : "UnityEngine.dll", "The local filename of the assembly to target."); private static readonly ConfigEntry<string> ConfigEntrypointType = ConfigFile.CoreConfig.Bind<string>("Preloader.Entrypoint", "Type", "Application", "The name of the type in the entrypoint assembly to search for the entrypoint method."); private static readonly ConfigEntry<string> ConfigEntrypointMethod = ConfigFile.CoreConfig.Bind<string>("Preloader.Entrypoint", "Method", ".cctor", "The name of the method in the specified entrypoint assembly and type to hook and load Chainloader from."); internal static readonly ConfigEntry<bool> ConfigApplyRuntimePatches = ConfigFile.CoreConfig.Bind<bool>("Preloader", "ApplyRuntimePatches", true, "Enables or disables runtime patches.\nThis should always be true, unless you cannot start the game due to a Harmony related issue (such as running .NET Standard runtime) or you know what you're doing."); private static readonly ConfigEntry<MonoModBackend> HarmonyBackend = ConfigFile.CoreConfig.Bind<MonoModBackend>("Preloader", "HarmonyBackend", MonoModBackend.auto, "Specifies which MonoMod backend to use for Harmony patches. Auto uses the best available backend.\nThis setting should only be used for development purposes (e.g. debugging in dnSpy). Other code might override this setting."); private static PreloaderConsoleListener PreloaderLog { get; set; } public static bool IsPostUnity2017 { get; } = File.Exists(Path.Combine(Paths.ManagedPath, "UnityEngine.CoreModule.dll")); public static void Run() { //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Expected O, but got Unknown try { InitializeHarmony(); HarmonyInteropFix.Apply(); ConsoleManager.Initialize(false); AllocateConsole(); Exception ex = default(Exception); Utility.TryDo((Action)delegate { if (ConfigApplyRuntimePatches.Value) { UnityPatches.Apply(); } }, ref ex); Logger.InitializeInternalLoggers(); Logger.Sources.Add(TraceLogSource.CreateSource()); PreloaderLog = new PreloaderConsoleListener(); Logger.Listeners.Add((ILogListener)(object)PreloaderLog); Version version = typeof(Paths).Assembly.GetName().Version; string text = $"BepInEx {version} - {Paths.ProcessName}"; if (ConsoleManager.ConsoleActive) { ConsoleManager.SetConsoleTitle(text); } Logger.LogMessage((object)$"{text} ({File.GetLastWriteTime(Paths.ExecutablePath)})"); object[] customAttributes = typeof(BuildInfoAttribute).Assembly.GetCustomAttributes(typeof(BuildInfoAttribute), inherit: false); if (customAttributes.Length != 0) { BuildInfoAttribute val = (BuildInfoAttribute)customAttributes[0]; Logger.LogMessage((object)val.Info); } Logger.LogInfo((object)("Running under Unity v" + GetUnityVersion())); Logger.LogInfo((object)$"CLR runtime version: {Environment.Version}"); Logger.LogInfo((object)$"Supports SRE: {Utility.CLRSupportsDynamicAssemblies}"); Logger.LogInfo((object)$"System platform: {PlatformHelper.Current}"); if (ex != null) { Logger.LogWarning((object)("Failed to apply runtime patches for Mono. See more info in the output log. Error message: " + ex.Message)); } Logger.LogMessage((object)"Preloader started"); PatcherPlugin patcherPlugin = new PatcherPlugin(); patcherPlugin.TargetDLLs = () => new string[1] { ConfigEntrypointAssembly.Value }; patcherPlugin.Patcher = PatchEntrypoint; patcherPlugin.TypeName = "BepInEx.Chainloader"; AssemblyPatcher.AddPatcher(patcherPlugin); Logger.Log((LogLevel)16, (object)$"Loaded 1 patcher method from [BepInEx.Preloader {version}]"); AssemblyPatcher.AddPatchersFromDirectory(Paths.PatcherPluginPath); Logger.LogInfo((object)string.Format("{0} patcher plugin{1} loaded", AssemblyPatcher.PatcherPlugins.Count, (AssemblyPatcher.PatcherPlugins.Count == 1) ? "" : "s")); AssemblyPatcher.PatchAndLoad(Paths.DllSearchPaths); AssemblyPatcher.DisposePatchers(); Logger.LogMessage((object)"Preloader finished"); Logger.Listeners.Remove((ILogListener)(object)PreloaderLog); PreloaderLog.Dispose(); } catch (Exception ex2) { try { Logger.LogFatal((object)"Could not run preloader!"); Logger.LogFatal((object)ex2); if (!ConsoleManager.ConsoleActive) { AllocateConsole(); Console.Write(PreloaderLog); } } catch { } string text2 = string.Empty; try { text2 = string.Join("\r\n", PreloaderConsoleListener.LogEvents.Select((LogEventArgs x) => ((object)x).ToString()).ToArray()); text2 += "\r\n"; PreloaderLog?.Dispose(); PreloaderLog = null; } catch { } File.WriteAllText(Path.Combine(Paths.GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"), text2 + ex2); } } public static void PatchEntrypoint(ref AssemblyDefinition assembly) { //IL_0207: Unknown result type (might be due to invalid IL or missing references) //IL_020e: Expected O, but got Unknown //IL_022e: 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_02de: Unknown result type (might be due to invalid IL or missing references) //IL_02f4: Unknown result type (might be due to invalid IL or missing references) //IL_032a: Unknown result type (might be due to invalid IL or missing references) //IL_0342: Unknown result type (might be due to invalid IL or missing references) if (((IEnumerable<AssemblyNameReference>)assembly.MainModule.AssemblyReferences).Any((AssemblyNameReference x) => x.Name.Contains("BepInEx"))) { throw new Exception("BepInEx has been detected to be patched! Please unpatch before using a patchless variant!"); } string entrypointType = ConfigEntrypointType.Value; string entrypointMethod = ConfigEntrypointMethod.Value; bool flag = Utility.IsNullOrWhiteSpace(entrypointMethod) || entrypointMethod == ".cctor"; TypeDefinition val = ((IEnumerable<TypeDefinition>)assembly.MainModule.Types).FirstOrDefault((Func<TypeDefinition, bool>)((TypeDefinition x) => ((MemberReference)x).Name == entrypointType)); if (val == null) { throw new Exception("The entrypoint type is invalid! Please check your config/BepInEx.cfg file"); } AssemblyDefinition val2 = AssemblyDefinition.ReadAssembly(Paths.BepInExAssemblyPath); try { MethodDefinition val3 = ((IEnumerable<MethodDefinition>)((IEnumerable<TypeDefinition>)val2.MainModule.Types).First((TypeDefinition x) => ((MemberReference)x).Name == "Chainloader").Methods).First((MethodDefinition x) => ((MemberReference)x).Name == "Initialize"); MethodDefinition val4 = ((IEnumerable<MethodDefinition>)((IEnumerable<TypeDefinition>)val2.MainModule.Types).First((TypeDefinition x) => ((MemberReference)x).Name == "Chainloader").Methods).First((MethodDefinition x) => ((MemberReference)x).Name == "Start"); MethodReference val5 = assembly.MainModule.ImportReference((MethodReference)(object)val3); MethodReference val6 = assembly.MainModule.ImportReference((MethodReference)(object)val4); List<MethodDefinition> list = new List<MethodDefinition>(); if (flag) { MethodDefinition val7 = ((IEnumerable<MethodDefinition>)val.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => m.IsConstructor && m.IsStatic)); if (val7 == null) { val7 = new MethodDefinition(".cctor", (MethodAttributes)6289, assembly.MainModule.ImportReference(typeof(void))); val.Methods.Add(val7); ILProcessor iLProcessor = val7.Body.GetILProcessor(); iLProcessor.Append(iLProcessor.Create(OpCodes.Ret)); } list.Add(val7); } else { list.AddRange(((IEnumerable<MethodDefinition>)val.Methods).Where((MethodDefinition x) => ((MemberReference)x).Name == entrypointMethod)); } if (!list.Any()) { throw new Exception("The entrypoint method is invalid! Please check your config.ini"); } foreach (MethodDefinition item in list) { ILProcessor iLProcessor2 = item.Body.GetILProcessor(); Instruction val8 = ((IEnumerable<Instruction>)iLProcessor2.Body.Instructions).First(); iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Ldnull)); iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Ldc_I4_0)); iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Call, assembly.MainModule.ImportReference((MethodBase)AccessTools.PropertyGetter(typeof(PreloaderConsoleListener), "LogEvents")))); iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Call, val5)); iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Call, val6)); } } finally { ((IDisposable)val2)?.Dispose(); } } public static void AllocateConsole() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown if (!ConsoleManager.ConsoleEnabled) { return; } try { ConsoleManager.CreateConsole(); Logger.Listeners.Add((ILogListener)new ConsoleLogListener()); } catch (Exception ex) { Logger.LogError((object)"Failed to allocate console!"); Logger.LogError((object)ex); } } public static string GetUnityVersion() { if (PlatformHelper.Is((Platform)37)) { return FileVersionInfo.GetVersionInfo(Paths.ExecutablePath).FileVersion; } return "Unknown (" + (IsPostUnity2017 ? "post" : "pre") + "-2017)"; } private static void InitializeHarmony() { switch (HarmonyBackend.Value) { case MonoModBackend.auto: break; case MonoModBackend.dynamicmethod: case MonoModBackend.methodbuilder: case MonoModBackend.cecil: Environment.SetEnvironmentVariable("MONOMOD_DMD_TYPE", HarmonyBackend.Value.ToString()); break; default: throw new ArgumentOutOfRangeException("HarmonyBackend", HarmonyBackend.Value, "Unknown backend"); } } } } namespace BepInEx.Preloader.RuntimeFixes { internal static class ConsoleSetOutFix { private static LoggedTextWriter loggedTextWriter; internal static ManualLogSource ConsoleLogSource = Logger.CreateLogSource("Console"); public static void Apply() { loggedTextWriter = new LoggedTextWriter { Parent = Console.Out }; Console.SetOut(loggedTextWriter); Harmony.CreateAndPatchAll(typeof(ConsoleSetOutFix), (string)null); } [HarmonyPatch(typeof(Console), "SetOut")] [HarmonyPrefix] private static bool OnSetOut(TextWriter newOut) { loggedTextWriter.Parent = newOut; return false; } } internal class LoggedTextWriter : TextWriter { public override Encoding Encoding { get; } = Encoding.UTF8; public TextWriter Parent { get; set; } public override void Flush() { Parent.Flush(); } public override void Write(string value) { ConsoleSetOutFix.ConsoleLogSource.LogInfo((object)value); Parent.Write(value); } public override void WriteLine(string value) { ConsoleSetOutFix.ConsoleLogSource.LogInfo((object)value); Parent.WriteLine(value); } } internal static class HarmonyInteropFix { public static void Apply() { HarmonyInterop.Initialize(Paths.CachePath); Harmony.CreateAndPatchAll(typeof(HarmonyInteropFix), "org.bepinex.fixes.harmonyinterop"); } [HarmonyReversePatch(/*Could not decode attribute arguments.*/)] [HarmonyPatch(typeof(Assembly), "LoadFile", new Type[] { typeof(string) })] private static Assembly LoadFile(string path) { return null; } [HarmonyPatch(typeof(Assembly), "LoadFile", new Type[] { typeof(string) })] [HarmonyPatch(typeof(Assembly), "LoadFrom", new Type[] { typeof(string) })] [HarmonyPrefix] private static bool OnAssemblyLoad(ref Assembly __result, string __0) { HarmonyInterop.TryShim(__0, Paths.GameRootPath, (Action<string>)Logger.LogWarning, TypeLoader.ReaderParameters); __result = LoadFile(__0); return true; } } internal static class TraceFix { private static Type TraceImplType; private static object ListenersSyncRoot; private static TraceListenerCollection Listeners; private static PropertyInfo prop_AutoFlush; private static bool AutoFlush => (bool)prop_AutoFlush.GetValue(null, null); public static void ApplyFix() { //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Expected O, but got Unknown //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Expected O, but got Unknown TraceImplType = AppDomain.CurrentDomain.GetAssemblies().First((Assembly x) => x.GetName().Name == "System").GetTypes() .FirstOrDefault((Type x) => x.Name == "TraceImpl"); if (!(TraceImplType == null)) { ListenersSyncRoot = AccessTools.Property(TraceImplType, "ListenersSyncRoot").GetValue(null, null); Listeners = (TraceListenerCollection)AccessTools.Property(TraceImplType, "Listeners").GetValue(null, null); prop_AutoFlush = AccessTools.Property(TraceImplType, "AutoFlush"); Harmony val = new Harmony("com.bepis.bepinex.tracefix"); val.Patch((MethodBase)typeof(Trace).GetMethod("DoTrace", BindingFlags.Static | BindingFlags.NonPublic), new HarmonyMethod(typeof(TraceFix).GetMethod("DoTraceReplacement", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } private static bool DoTraceReplacement(string kind, Assembly report, string message) { string source = string.Empty; try { source = report.GetName().Name; } catch (MethodAccessException) { } TraceEventType eventType = (TraceEventType)Enum.Parse(typeof(TraceEventType), kind); lock (ListenersSyncRoot) { foreach (object listener in Listeners) { TraceListener traceListener = (TraceListener)listener; traceListener.TraceEvent(new TraceEventCache(), source, eventType, 0, message); if (AutoFlush) { traceListener.Flush(); } } } return false; } } internal static class UnityPatches { private static Harmony HarmonyInstance { get; set; } public static Dictionary<string, string> AssemblyLocations { get; } = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); public static void Apply() { HarmonyInstance = Harmony.CreateAndPatchAll(typeof(UnityPatches), (string)null); try { TraceFix.ApplyFix(); } catch { } } [HarmonyPostfix] [HarmonyPatch(/*Could not decode attribute arguments.*/)] public static void GetLocation(ref string __result, Assembly __instance) { if (AssemblyLocations.TryGetValue(__instance.FullName, out var value)) { __result = value; } } [HarmonyPostfix] [HarmonyPatch(/*Could not decode attribute arguments.*/)] public static void GetCodeBase(ref string __result, Assembly __instance) { if (AssemblyLocations.TryGetValue(__instance.FullName, out var value)) { __result = "file://" + value.Replace('\\', '/'); } } } internal static class XTermFix { public static int intOffset; public static void Apply() { //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0060: 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_0089: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Expected O, but got Unknown //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Expected O, but got Unknown //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Expected O, but got Unknown //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Expected O, but got Unknown if (!PlatformHelper.Is((Platform)37) && !(typeof(Console).Assembly.GetType("System.ConsoleDriver") == null) && !(AccessTools.Method("System.TermInfoReader:DetermineVersion", (Type[])null, (Type[])null) != null)) { DetourHelper.Native = (IDetourNativePlatform)new DetourNativeX86Platform(); Harmony val = new Harmony("com.bepinex.xtermfix"); val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:ReadHeader", (Type[])null, (Type[])null), new HarmonyMethod(typeof(XTermFix), "ReadHeaderPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:Get", new Type[1] { AccessTools.TypeByName("System.TermInfoNumbers") }, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(XTermFix), "GetTermInfoNumbersTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:Get", new Type[1] { AccessTools.TypeByName("System.TermInfoStrings") }, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(XTermFix), "GetTermInfoStringsTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:GetStringBytes", new Type[1] { AccessTools.TypeByName("System.TermInfoStrings") }, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(XTermFix), "GetTermInfoStringsTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null); DetourHelper.Native = null; } } public static int GetInt32(byte[] buffer, int offset) { int num = buffer[offset]; int num2 = buffer[offset + 1]; int num3 = buffer[offset + 2]; int num4 = buffer[offset + 3]; return num | (num2 << 8) | (num3 << 16) | (num4 << 24); } public static short GetInt16(byte[] buffer, int offset) { int num = buffer[offset]; int num2 = buffer[offset + 1]; return (short)(num | (num2 << 8)); } public static int GetInteger(byte[] buffer, int offset) { return (intOffset == 2) ? GetInt16(buffer, offset) : GetInt32(buffer, offset); } public static void DetermineVersion(short magic) { switch (magic) { case 282: intOffset = 2; break; case 542: intOffset = 4; break; default: throw new Exception($"Unknown xterm header format: {magic}"); } } public static bool ReadHeaderPrefix(byte[] buffer, ref int position, ref short ___boolSize, ref short ___numSize, ref short ___strOffsets) { short @int = GetInt16(buffer, position); position += 2; DetermineVersion(@int); position += 2; ___boolSize = GetInt16(buffer, position); position += 2; ___numSize = GetInt16(buffer, position); position += 2; ___strOffsets = GetInt16(buffer, position); position += 2; position += 2; return false; } public static IEnumerable<CodeInstruction> GetTermInfoNumbersTranspiler(IEnumerable<CodeInstruction> instructions) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected O, but got Unknown List<CodeInstruction> list = instructions.ToList(); list[31] = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(XTermFix), "intOffset")); list[36] = new CodeInstruction(OpCodes.Nop, (object)null); list[39] = new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(XTermFix), "GetInteger", (Type[])null, (Type[])null)); return list; } public static IEnumerable<CodeInstruction> GetTermInfoStringsTranspiler(IEnumerable<CodeInstruction> instructions) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown List<CodeInstruction> list = instructions.ToList(); list[32] = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(XTermFix), "intOffset")); return list; } } } namespace BepInEx.Preloader.Patching { public delegate void AssemblyPatcherDelegate(ref AssemblyDefinition assembly); public static class AssemblyPatcher { private const BindingFlags ALL = BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; private static readonly string DumpedAssembliesPath = Utility.CombinePaths(new string[3] { Paths.BepInExRootPath, "DumpedAssemblies", Paths.ProcessName }); private static readonly Dictionary<string, string> DumpedAssemblyPaths = new Dictionary<string, string>(); private static readonly ConfigEntry<bool> ConfigDumpAssemblies = ConfigFile.CoreConfig.Bind<bool>("Preloader", "DumpAssemblies", false, "If enabled, BepInEx will save patched assemblies into BepInEx/DumpedAssemblies.\nThis can be used by developers to inspect and debug preloader patchers."); private static readonly ConfigEntry<bool> ConfigLoadDumpedAssemblies = ConfigFile.CoreConfig.Bind<bool>("Preloader", "LoadDumpedAssemblies", false, "If enabled, BepInEx will load patched assemblies from BepInEx/DumpedAssemblies instead of memory.\nThis can be used to be able to load patched assemblies into debuggers like dnSpy.\nIf set to true, will override DumpAssemblies."); private static readonly ConfigEntry<bool> ConfigBreakBeforeLoadAssemblies = ConfigFile.CoreConfig.Bind<bool>("Preloader", "BreakBeforeLoadAssemblies", false, "If enabled, BepInEx will call Debugger.Break() once before loading patched assemblies.\nThis can be used with debuggers like dnSpy to install breakpoints into patched assemblies before they are loaded."); public static List<PatcherPlugin> PatcherPlugins { get; } = new List<PatcherPlugin>(); private static IEnumerable<PatcherPlugin> PatcherPluginsSafe => PatcherPlugins.ToList(); public static void AddPatcher(PatcherPlugin patcher) { PatcherPlugins.Add(patcher); } private static T CreateDelegate<T>(MethodInfo method) where T : class { return (method != null) ? (Delegate.CreateDelegate(typeof(T), method) as T) : null; } private static PatcherPlugin ToPatcherPlugin(TypeDefinition type) { if (type.IsInterface || (type.IsAbstract && !type.IsSealed)) { return null; } MethodDefinition val = ((IEnumerable<MethodDefinition>)type.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => ((MemberReference)m).Name.Equals("get_TargetDLLs", StringComparison.InvariantCultureIgnoreCase) && m.IsPublic && m.IsStatic)); if (val == null || ((MemberReference)((MethodReference)val).ReturnType).FullName != "System.Collections.Generic.IEnumerable`1<System.String>") { return null; } MethodDefinition val2 = ((IEnumerable<MethodDefinition>)type.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => ((MemberReference)m).Name.Equals("Patch") && m.IsPublic && m.IsStatic && ((MemberReference)((MethodReference)m).ReturnType).FullName == "System.Void" && ((MethodReference)m).Parameters.Count == 1 && (((MemberReference)((ParameterReference)((MethodReference)m).Parameters[0]).ParameterType).FullName == "Mono.Cecil.AssemblyDefinition&" || ((MemberReference)((ParameterReference)((MethodReference)m).Parameters[0]).ParameterType).FullName == "Mono.Cecil.AssemblyDefinition"))); if (val2 == null) { return null; } return new PatcherPlugin { TypeName = ((MemberReference)type).FullName }; } public static void AddPatchersFromDirectory(string directory) { if (!Directory.Exists(directory)) { return; } SortedDictionary<string, PatcherPlugin> sortedDictionary = new SortedDictionary<string, PatcherPlugin>(); Dictionary<string, List<PatcherPlugin>> dictionary = TypeLoader.FindPluginTypes<PatcherPlugin>(directory, (Func<TypeDefinition, PatcherPlugin>)ToPatcherPlugin, (Func<AssemblyDefinition, bool>)null, (string)null); foreach (KeyValuePair<string, List<PatcherPlugin>> item in dictionary) { string key = item.Key; List<PatcherPlugin> value = item.Value; if (value.Count == 0) { continue; } Assembly assembly = Assembly.LoadFile(key); foreach (PatcherPlugin item2 in value) { try { Type type = assembly.GetType(item2.TypeName); MethodInfo[] methods = type.GetMethods(BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); item2.Initializer = CreateDelegate<Action>(methods.FirstOrDefault((MethodInfo m) => m.Name.Equals("Initialize", StringComparison.InvariantCultureIgnoreCase) && m.GetParameters().Length == 0 && m.ReturnType == typeof(void))); item2.Finalizer = CreateDelegate<Action>(methods.FirstOrDefault((MethodInfo m) => m.Name.Equals("Finish", StringComparison.InvariantCultureIgnoreCase) && m.GetParameters().Length == 0 && m.ReturnType == typeof(void))); item2.TargetDLLs = CreateDelegate<Func<IEnumerable<string>>>(type.GetProperty("TargetDLLs", BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetGetMethod()); MethodInfo patcher = methods.FirstOrDefault((MethodInfo m) => m.Name.Equals("Patch", StringComparison.CurrentCultureIgnoreCase) && m.ReturnType == typeof(void) && m.GetParameters().Length == 1 && (m.GetParameters()[0].ParameterType == typeof(AssemblyDefinition) || m.GetParameters()[0].ParameterType == typeof(AssemblyDefinition).MakeByRefType())); item2.Patcher = delegate(ref AssemblyDefinition pAss) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown object[] array = new object[1] { pAss }; patcher.Invoke(null, array); pAss = (AssemblyDefinition)array[0]; }; sortedDictionary.Add(assembly.GetName().Name + "/" + type.FullName, item2); } catch (Exception ex) { Logger.LogError((object)("Failed to load patcher [" + item2.TypeName + "]: " + ex.Message)); if (ex is ReflectionTypeLoadException ex2) { Logger.LogDebug((object)TypeLoader.TypeLoadExceptionToString(ex2)); } else { Logger.LogDebug((object)ex.ToString()); } } } AssemblyName name = assembly.GetName(); Logger.Log((LogLevel)(value.Any() ? 16 : 32), (object)string.Format("Loaded {0} patcher method{1} from [{2} {3}]", value.Count, (value.Count == 1) ? "" : "s", name.Name, name.Version)); } foreach (KeyValuePair<string, PatcherPlugin> item3 in sortedDictionary) { AddPatcher(item3.Value); } } private static void InitializePatchers() { foreach (PatcherPlugin item in PatcherPluginsSafe) { try { item.Initializer?.Invoke(); } catch (Exception arg) { Logger.LogError((object)$"Failed to run Initializer of {item.TypeName}: {arg}"); } } } private static void FinalizePatching() { foreach (PatcherPlugin item in PatcherPluginsSafe) { try { item.Finalizer?.Invoke(); } catch (Exception arg) { Logger.LogError((object)$"Failed to run Finalizer of {item.TypeName}: {arg}"); } } } public static void DisposePatchers() { PatcherPlugins.Clear(); } private static string GetAssemblyName(string fullName) { AssemblyName assemblyName = default(AssemblyName); return Utility.TryParseAssemblyName(fullName, ref assemblyName) ? assemblyName.Name : fullName; } public static void PatchAndLoad(params string[] directories) { Dictionary<string, AssemblyDefinition> dictionary = new Dictionary<string, AssemblyDefinition>(StringComparer.InvariantCultureIgnoreCase); foreach (string uniqueFilesInDirectory in Utility.GetUniqueFilesInDirectories((IEnumerable<string>)directories, "*.dll")) { AssemblyDefinition val; try { val = AssemblyDefinition.ReadAssembly(uniqueFilesInDirectory); } catch (BadImageFormatException) { continue; } if (((AssemblyNameReference)val.Name).Name == "System" || ((AssemblyNameReference)val.Name).Name == "mscorlib") { val.Dispose(); continue; } if (UnityPatches.AssemblyLocations.ContainsKey(val.FullName)) { Logger.LogWarning((object)("Tried to load duplicate assembly " + Path.GetFileName(uniqueFilesInDirectory) + " from Managed folder! Skipping...")); continue; } dictionary.Add(Path.GetFileName(uniqueFilesInDirectory), val); UnityPatches.AssemblyLocations.Add(val.FullName, Path.GetFullPath(uniqueFilesInDirectory)); } InitializePatchers(); HashSet<string> patchedAssemblies = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase); Dictionary<string, string> dictionary2 = new Dictionary<string, string>(); HashSet<string> hashSet = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase); foreach (PatcherPlugin item in PatcherPluginsSafe) { foreach (string item2 in item.TargetDLLs()) { if (!dictionary.TryGetValue(item2, out var value) || hashSet.Contains(item2)) { continue; } Logger.LogInfo((object)("Patching [" + ((AssemblyNameReference)value.Name).Name + "] with [" + item.TypeName + "]")); try { item.Patcher?.Invoke(ref value); } catch (Exception arg) { Logger.LogError((object)$"Failed to run [{item.TypeName}] when patching [{((AssemblyNameReference)value.Name).Name}]. This assembly will not be patched. Error: {arg}"); patchedAssemblies.Remove(item2); hashSet.Add(item2); continue; } dictionary[item2] = value; patchedAssemblies.Add(item2); Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { string assemblyName = GetAssemblyName(assembly.FullName); if (!dictionary2.ContainsKey(assemblyName)) { dictionary2[assemblyName] = item.TypeName; } } } } HashSet<string> patchedAssemblyNames = new HashSet<string>(from kv in dictionary where patchedAssemblies.Contains(kv.Key) select ((AssemblyNameReference)kv.Value.Name).Name, StringComparer.InvariantCultureIgnoreCase); List<KeyValuePair<string, string>> list = dictionary2.Where((KeyValuePair<string, string> kv) => patchedAssemblyNames.Contains(kv.Key)).ToList(); if (list.Count != 0) { Logger.LogWarning((object)new StringBuilder().AppendLine("The following assemblies have been loaded too early and will not be patched by preloader:").AppendLine(string.Join(Environment.NewLine, list.Select((KeyValuePair<string, string> kv) => "* [" + kv.Key + "] (first loaded by [" + kv.Value + "])").ToArray())).AppendLine("Expect unexpected behavior and issues with plugins and patchers not being loaded.") .ToString()); } DumpedAssemblyPaths.Clear(); if (ConfigDumpAssemblies.Value || ConfigLoadDumpedAssemblies.Value) { if (!Directory.Exists(DumpedAssembliesPath)) { Directory.CreateDirectory(DumpedAssembliesPath); } FileStream fileStream = default(FileStream); foreach (KeyValuePair<string, AssemblyDefinition> item3 in dictionary) { string key = item3.Key; string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(key); string extension = Path.GetExtension(key); AssemblyDefinition value2 = item3.Value; if (!patchedAssemblies.Contains(key)) { continue; } int num = 0; string text2; while (true) { string text = ((num > 0) ? $"_{num}" : ""); text2 = Path.Combine(DumpedAssembliesPath, fileNameWithoutExtension + text + extension); if (Utility.TryOpenFileStream(text2, FileMode.Create, ref fileStream, FileAccess.ReadWrite, FileShare.Read)) { break; } num++; } value2.Write((Stream)fileStream); fileStream.Dispose(); DumpedAssemblyPaths[key] = text2; } } if (ConfigBreakBeforeLoadAssemblies.Value) { Logger.LogInfo((object)("BepInEx is about load the following assemblies:\n" + string.Join("\n", patchedAssemblies.ToArray()))); Logger.LogInfo((object)("The assemblies were dumped into " + DumpedAssembliesPath)); Logger.LogInfo((object)"Load any assemblies into the debugger, set breakpoints and continue execution."); Debugger.Break(); } foreach (KeyValuePair<string, AssemblyDefinition> item4 in dictionary) { string key2 = item4.Key; AssemblyDefinition value3 = item4.Value; if (patchedAssemblies.Contains(key2)) { Load(value3, key2); } value3.Dispose(); } FinalizePatching(); } public static void Load(AssemblyDefinition assembly, string filename) { if (ConfigLoadDumpedAssemblies.Value && DumpedAssemblyPaths.TryGetValue(filename, out var value)) { Assembly.LoadFile(value); return; } using MemoryStream memoryStream = new MemoryStream(); assembly.Write((Stream)memoryStream); Assembly.Load(memoryStream.ToArray()); } } public class PatcherPlugin : ICacheable { public Func<IEnumerable<string>> TargetDLLs { get; set; } = null; public Action Initializer { get; set; } = null; public Action Finalizer { get; set; } = null; public AssemblyPatcherDelegate Patcher { get; set; } = null; public string TypeName { get; set; } = string.Empty; public void Save(BinaryWriter bw) { bw.Write(TypeName); } public void Load(BinaryReader br) { TypeName = br.ReadString(); } } }
BepInEx/core/HarmonyXInterop.dll
Decompiled a week agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using HarmonyLib; using HarmonyLib.Public.Patching; using HarmonyLib.Tools; using Mono.Cecil; using MonoMod.Utils; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: ComVisible(false)] [assembly: Guid("160F7FE0-288D-435C-9E7E-497D3E0DE3A6")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("HarmonyXInterop")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0.0+6830e686c7931164a4e34595a34cbfa15846d1d4")] [assembly: AssemblyProduct("HarmonyXInterop")] [assembly: AssemblyTitle("HarmonyXInterop")] [assembly: AssemblyVersion("1.0.0.0")] namespace HarmonyXInterop; internal static class DMDUtil { public static MethodInfo GenerateWith<T>(this DynamicMethodDefinition dmd, object context = null) where T : DMDGenerator<T>, new() { return DMDGenerator<T>.Generate(dmd, context); } } public static class HarmonyInterop { private const string BACKUP_PATH = "BepInEx_Shim_Backup"; private static Version maxAvailableShimVersion; private static readonly SortedDictionary<Version, string> Assemblies = new SortedDictionary<Version, string>(); private static readonly HashSet<string> InteropAssemblyNames = new HashSet<string>(); private static readonly Func<MethodBase, PatchInfo, MethodInfo> UpdateWrapper = AccessTools.MethodDelegate<Func<MethodBase, PatchInfo, MethodInfo>>(AccessTools.Method(typeof(HarmonyManipulator).Assembly.GetType("HarmonyLib.PatchFunctions"), "UpdateWrapper", (Type[])null, (Type[])null), (object)null, true); private static readonly Action<LogChannel, Func<string>, bool> HarmonyLog = AccessTools.MethodDelegate<Action<LogChannel, Func<string>, bool>>(AccessTools.Method(typeof(Logger), "Log", (Type[])null, (Type[])null), (object)null, true); private static readonly Action<LogChannel, string, bool> HarmonyLogText = AccessTools.MethodDelegate<Action<LogChannel, string, bool>>(AccessTools.Method(typeof(Logger), "LogText", (Type[])null, (Type[])null), (object)null, true); private static readonly Dictionary<string, long> shimCache = new Dictionary<string, long>(); private static BinaryWriter cacheWriter; public static void Log(int channel, Func<string> message) { HarmonyLog((LogChannel)channel, message, arg3: false); } public static void LogText(int channel, string message) { HarmonyLogText((LogChannel)channel, message, arg3: false); } public static void Initialize(string cachePath) { Directory.CreateDirectory(cachePath); string path = Path.Combine(cachePath, "harmony_interop_cache.dat"); string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string[] files = Directory.GetFiles(directoryName, "0Harmony*.dll", SearchOption.AllDirectories); foreach (string text in files) { AssemblyDefinition val = AssemblyDefinition.ReadAssembly(text); try { if (((AssemblyNameReference)val.Name).Name != "0Harmony") { Assemblies.Add(((AssemblyNameReference)val.Name).Version, ((AssemblyNameReference)val.Name).Name); InteropAssemblyNames.Add(((AssemblyNameReference)val.Name).Name); } } finally { ((IDisposable)val)?.Dispose(); } } maxAvailableShimVersion = Assemblies.LastOrDefault().Key; if (File.Exists(path)) { try { using BinaryReader binaryReader = new BinaryReader(File.OpenRead(path)); while (true) { string key = binaryReader.ReadString(); long value = binaryReader.ReadInt64(); shimCache[key] = value; } } catch (Exception) { } } try { BinaryWriter binaryWriter = new BinaryWriter(File.Create(path)); cacheWriter = binaryWriter; foreach (KeyValuePair<string, long> item in shimCache) { cacheWriter.Write(item.Key); cacheWriter.Write(item.Value); } cacheWriter.Flush(); } catch (IOException) { } } public static byte[] TryShim(string path, string gameRootDirectory, Action<string> logMessage = null, ReaderParameters readerParameters = null) { HashSet<string> hashSet = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase); List<string> deps; byte[] result = TryShimInternal(path, gameRootDirectory, logMessage, readerParameters, out deps); foreach (string item in deps) { hashSet.Add(item); } while (hashSet.Count != 0) { string text = hashSet.First(); TryShimInternal(text, gameRootDirectory, logMessage, readerParameters, out deps); foreach (string item2 in deps) { hashSet.Add(item2); } hashSet.Remove(text); } return result; } private static bool NeedsShimming(string path, out long lastWriteTime, Action<string> logMessage = null) { lastWriteTime = 0L; try { if (!File.Exists(path)) { return false; } } catch (Exception arg) { logMessage?.Invoke($"Failed to read path {path}: {arg}"); return false; } lastWriteTime = File.GetLastWriteTimeUtc(path).Ticks; long value; return !shimCache.TryGetValue(path, out value) || value != lastWriteTime; } private static byte[] TryShimInternal(string path, string gameRootDirectory, Action<string> logMessage, ReaderParameters readerParameters, out List<string> deps) { //IL_0070: Unknown result type (might be due to invalid IL or missing references) deps = new List<string>(); if (!NeedsShimming(path, out var lastWriteTime, logMessage)) { return null; } byte[] result = null; try { string dir = Path.GetDirectoryName(path); byte[] array; try { array = File.ReadAllBytes(path); } catch (Exception) { return null; } using MemoryStream memoryStream = new MemoryStream(array); AssemblyDefinition val = AssemblyDefinition.ReadAssembly((Stream)memoryStream, (ReaderParameters)(((object)readerParameters) ?? ((object)new ReaderParameters()))); try { deps.AddRange(from a in (IEnumerable<AssemblyNameReference>)val.MainModule.AssemblyReferences select Path.Combine(dir, a.Name + ".dll") into p where NeedsShimming(p, out var _, logMessage) select p); AssemblyNameReference harmonyRef = ((IEnumerable<AssemblyNameReference>)val.MainModule.AssemblyReferences).FirstOrDefault((Func<AssemblyNameReference, bool>)((AssemblyNameReference a) => a.Name.StartsWith("0Harmony") && !InteropAssemblyNames.Contains(a.Name))); if (harmonyRef != null) { KeyValuePair<Version, string> keyValuePair = Assemblies.LastOrDefault((KeyValuePair<Version, string> kv) => VersionMatches(kv.Key, harmonyRef.Version)); if (keyValuePair.Value != null) { logMessage?.Invoke("Shimming " + path + " to use older version of Harmony (" + keyValuePair.Value + "). Please update the plugin if possible."); harmonyRef.Name = keyValuePair.Value; using MemoryStream memoryStream2 = new MemoryStream(); val.Write((Stream)memoryStream2); try { string path2 = Path.Combine(gameRootDirectory, "BepInEx_Shim_Backup"); string directoryName = Path.GetDirectoryName(Path.GetFullPath(path).Substring(gameRootDirectory.Length + 1)); string text = Path.Combine(path2, directoryName); Directory.CreateDirectory(text); File.WriteAllBytes(Path.Combine(text, Path.GetFileName(path)), array); File.WriteAllBytes(path, memoryStream2.ToArray()); lastWriteTime = File.GetLastWriteTimeUtc(path).Ticks; } catch (IOException) { lastWriteTime = 0L; } result = memoryStream2.ToArray(); } } shimCache[path] = lastWriteTime; if (cacheWriter != null) { cacheWriter.Write(path); cacheWriter.Write(lastWriteTime); cacheWriter.Flush(); } } finally { ((IDisposable)val)?.Dispose(); } } catch (Exception arg) { logMessage?.Invoke($"Failed to shim {path}: {arg}"); } return result; static bool VersionMatches(Version cmpV, Version refV) { return maxAvailableShimVersion != null && refV <= maxAvailableShimVersion && cmpV.Major == refV.Major && cmpV.Minor == refV.Minor && cmpV <= refV; } } public static void ApplyPatch(MethodBase target, PatchInfoWrapper add, PatchInfoWrapper remove) { PatchInfo val = PatchManager.ToPatchInfo(target); lock (val) { val.prefixes = Sync(add.prefixes, remove.prefixes, val.prefixes); val.postfixes = Sync(add.postfixes, remove.postfixes, val.postfixes); val.transpilers = Sync(WrapTranspilers(add.transpilers), WrapTranspilers(remove.transpilers), val.transpilers); val.finalizers = Sync(add.finalizers, remove.finalizers, val.finalizers); } UpdateWrapper(target, val); static PatchMethod[] WrapTranspilers(PatchMethod[] transpilers) { return transpilers.Select((PatchMethod p) => new PatchMethod { after = p.after, before = p.before, method = TranspilerInterop.WrapInterop(p.method), owner = p.owner, priority = p.priority }).ToArray(); } } private static Patch[] Sync(PatchMethod[] add, PatchMethod[] remove, Patch[] current) { if (add.Length == 0 && remove.Length == 0) { return current; } current = current.Where((Patch p) => !remove.Any((PatchMethod r) => r.method == p.PatchMethod && r.owner == p.owner)).ToArray(); int initialIndex = current.Length; return current.Concat(add.Where((PatchMethod method) => method != null).Select((Func<PatchMethod, int, Patch>)((PatchMethod method, int i) => new Patch(method.ToHarmonyMethod(), i + initialIndex, method.owner)))).ToArray(); } } public class PatchInfoWrapper { public PatchMethod[] finalizers; public PatchMethod[] postfixes; public PatchMethod[] prefixes; public PatchMethod[] transpilers; } public class PatchMethod { public string[] after; public string[] before; public MethodInfo method; public string owner; public int priority = -1; public HarmonyMethod ToHarmonyMethod() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown return new HarmonyMethod { after = after, before = before, method = method, priority = priority }; } } public class PatchMethodComparer : IEqualityComparer<PatchMethod> { public static PatchMethodComparer Instance { get; } = new PatchMethodComparer(); public bool Equals(PatchMethod x, PatchMethod y) { if (x == y) { return true; } if (x == null) { return false; } if (y == null) { return false; } if (x.GetType() != y.GetType()) { return false; } return object.Equals(x.method, y.method) && x.owner == y.owner; } public int GetHashCode(PatchMethod obj) { return (((obj.method != null) ? obj.method.GetHashCode() : 0) * 397) ^ ((obj.owner != null) ? obj.owner.GetHashCode() : 0); } } internal static class TranspilerInterop { private static readonly Dictionary<OpCode, OpCode> AllJumpCodes = new Dictionary<OpCode, OpCode> { { OpCodes.Beq_S, OpCodes.Beq }, { OpCodes.Bge_S, OpCodes.Bge }, { OpCodes.Bge_Un_S, OpCodes.Bge_Un }, { OpCodes.Bgt_S, OpCodes.Bgt }, { OpCodes.Bgt_Un_S, OpCodes.Bgt_Un }, { OpCodes.Ble_S, OpCodes.Ble }, { OpCodes.Ble_Un_S, OpCodes.Ble_Un }, { OpCodes.Blt_S, OpCodes.Blt }, { OpCodes.Blt_Un_S, OpCodes.Blt_Un }, { OpCodes.Bne_Un_S, OpCodes.Bne_Un }, { OpCodes.Brfalse_S, OpCodes.Brfalse }, { OpCodes.Brtrue_S, OpCodes.Brtrue }, { OpCodes.Br_S, OpCodes.Br }, { OpCodes.Leave_S, OpCodes.Leave } }; private static readonly Dictionary<MethodInfo, MethodInfo> Wrappers = new Dictionary<MethodInfo, MethodInfo>(); private static readonly MethodInfo ResolveToken = AccessTools.Method(typeof(MethodBase), "GetMethodFromHandle", new Type[1] { typeof(RuntimeMethodHandle) }, (Type[])null); private static readonly MethodInfo ApplyTranspilerMethod = AccessTools.Method(typeof(TranspilerInterop), "ApplyTranspiler", (Type[])null, (Type[])null); public static MethodInfo WrapInterop(MethodInfo transpiler) { //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Expected O, but got Unknown lock (Wrappers) { if (Wrappers.TryGetValue(transpiler, out var value)) { return value; } } DynamicMethodDefinition val = new DynamicMethodDefinition("TranspilerWrapper<" + Extensions.GetID((MethodBase)transpiler, (string)null, (string)null, true, false, true) + ">", typeof(IEnumerable<CodeInstruction>), new Type[3] { typeof(IEnumerable<CodeInstruction>), typeof(ILGenerator), typeof(MethodBase) }); try { ILGenerator iLGenerator = val.GetILGenerator(); iLGenerator.Emit(OpCodes.Ldtoken, transpiler); iLGenerator.Emit(OpCodes.Call, ResolveToken); iLGenerator.Emit(OpCodes.Castclass, typeof(MethodInfo)); iLGenerator.Emit(OpCodes.Ldarg_0); iLGenerator.Emit(OpCodes.Ldarg_1); iLGenerator.Emit(OpCodes.Ldarg_2); iLGenerator.Emit(OpCodes.Call, ApplyTranspilerMethod); iLGenerator.Emit(OpCodes.Ret); MethodInfo methodInfo = val.GenerateWith<DMDCecilGenerator>((object)null); lock (Wrappers) { Wrappers[transpiler] = methodInfo; } return methodInfo; } finally { ((IDisposable)val)?.Dispose(); } } private static IEnumerable<CodeInstruction> ApplyTranspiler(MethodInfo transpiler, IEnumerable<CodeInstruction> instructions, ILGenerator generator, MethodBase method) { Dictionary<object, Dictionary<string, object>> unassignedValues; IEnumerable enumerable = ConvertToGeneralInstructions(transpiler, instructions, out unassignedValues); List<object> originalInstructions = null; if (unassignedValues != null) { originalInstructions = instructions.Cast<object>().ToList(); } List<object> transpilerCallParameters = GetTranspilerCallParameters(generator, transpiler, method, enumerable); if (transpiler.Invoke(null, transpilerCallParameters.ToArray()) is IEnumerable enumerable2) { enumerable = enumerable2; } if (unassignedValues != null) { enumerable = ConvertToOurInstructions(enumerable, typeof(CodeInstruction), originalInstructions, unassignedValues); } return (enumerable as List<CodeInstruction>) ?? enumerable.Cast<CodeInstruction>().ToList(); } private static OpCode ReplaceShortJumps(OpCode opcode) { using (IEnumerator<KeyValuePair<OpCode, OpCode>> enumerator = AllJumpCodes.Where((KeyValuePair<OpCode, OpCode> pair) => opcode == pair.Key).GetEnumerator()) { if (enumerator.MoveNext()) { return enumerator.Current.Value; } } return opcode; } private static object ConvertInstruction(Type type, object instruction, out Dictionary<string, object> unassigned) { Dictionary<string, object> nonExisting = new Dictionary<string, object>(); object result = AccessTools.MakeDeepCopy(instruction, type, (Func<string, Traverse, Traverse, object>)delegate(string namePath, Traverse trvSrc, Traverse trvDest) { object value = trvSrc.GetValue(); if (trvDest.FieldExists()) { return (namePath == "opcode") ? ((object)ReplaceShortJumps((OpCode)value)) : value; } nonExisting[namePath] = value; return null; }, ""); unassigned = nonExisting; return result; } private static bool ShouldAddExceptionInfo(object op, int opIndex, List<object> originalInstructions, List<object> newInstructions, Dictionary<object, Dictionary<string, object>> unassignedValues) { int num = originalInstructions.IndexOf(op); if (num == -1) { return false; } if (!unassignedValues.TryGetValue(op, out var unassigned)) { return false; } if (!unassigned.TryGetValue("blocks", out var blocksObject)) { return false; } List<ExceptionBlock> blocks = blocksObject as List<ExceptionBlock>; int num2 = newInstructions.Count((object instr) => instr == op); if (num2 <= 1) { return true; } ExceptionBlock val = ((IEnumerable<ExceptionBlock>)blocks).FirstOrDefault((Func<ExceptionBlock, bool>)((ExceptionBlock block) => (int)block.blockType != 5)); ExceptionBlock val2 = ((IEnumerable<ExceptionBlock>)blocks).FirstOrDefault((Func<ExceptionBlock, bool>)((ExceptionBlock block) => (int)block.blockType == 5)); if (val != null && val2 == null) { object obj = originalInstructions.Skip(num + 1).FirstOrDefault(delegate(object instr) { if (!unassignedValues.TryGetValue(instr, out unassigned)) { return false; } if (!unassigned.TryGetValue("blocks", out blocksObject)) { return false; } blocks = blocksObject as List<ExceptionBlock>; return blocks.Any(); }); if (obj != null) { int num3 = num + 1; int num4 = num3 + originalInstructions.Skip(num3).ToList().IndexOf(obj) - 1; IEnumerable<object> first = originalInstructions.GetRange(num3, num4 - num3).Intersect(newInstructions); obj = newInstructions.Skip(opIndex + 1).FirstOrDefault(delegate(object instr) { if (!unassignedValues.TryGetValue(instr, out unassigned)) { return false; } if (!unassigned.TryGetValue("blocks", out blocksObject)) { return false; } blocks = blocksObject as List<ExceptionBlock>; return blocks.Any(); }); if (obj != null) { num3 = opIndex + 1; num4 = num3 + newInstructions.Skip(opIndex + 1).ToList().IndexOf(obj) - 1; List<object> range = newInstructions.GetRange(num3, num4 - num3); List<object> source = first.Except(range).ToList(); return !source.Any(); } } } if (val == null && val2 != null) { object obj2 = originalInstructions.GetRange(0, num).LastOrDefault(delegate(object instr) { if (!unassignedValues.TryGetValue(instr, out unassigned)) { return false; } if (!unassigned.TryGetValue("blocks", out blocksObject)) { return false; } blocks = blocksObject as List<ExceptionBlock>; return blocks.Any(); }); if (obj2 == null) { return true; } int num5 = originalInstructions.GetRange(0, num).LastIndexOf(obj2); int num6 = num; IEnumerable<object> first2 = originalInstructions.GetRange(num5, num6 - num5).Intersect(newInstructions); obj2 = newInstructions.GetRange(0, opIndex).LastOrDefault(delegate(object instr) { if (!unassignedValues.TryGetValue(instr, out unassigned)) { return false; } if (!unassigned.TryGetValue("blocks", out blocksObject)) { return false; } blocks = blocksObject as List<ExceptionBlock>; return blocks.Any(); }); if (obj2 == null) { return true; } num5 = newInstructions.GetRange(0, opIndex).LastIndexOf(obj2); num6 = opIndex; List<object> range2 = newInstructions.GetRange(num5, num6 - num5); IEnumerable<object> source2 = first2.Except(range2); return !source2.Any(); } return true; } private static IEnumerable ConvertInstructionsAndUnassignedValues(Type type, IEnumerable enumerable, out Dictionary<object, Dictionary<string, object>> unassignedValues) { Assembly assembly = type.GetGenericTypeDefinition().Assembly; Type type2 = assembly.GetType(typeof(List<>).FullName); Type type3 = type.GetGenericArguments()[0]; Type type4 = type2.MakeGenericType(type3); Type type5 = assembly.GetType(type4.FullName); object obj = Activator.CreateInstance(type5); MethodInfo method = obj.GetType().GetMethod("Add"); unassignedValues = new Dictionary<object, Dictionary<string, object>>(); foreach (object item in enumerable) { Dictionary<string, object> unassigned; object obj2 = ConvertInstruction(type3, item, out unassigned); unassignedValues.Add(obj2, unassigned); method.Invoke(obj, new object[1] { obj2 }); } return obj as IEnumerable; } private static IEnumerable ConvertToOurInstructions(IEnumerable instructions, Type codeInstructionType, List<object> originalInstructions, Dictionary<object, Dictionary<string, object>> unassignedValues) { List<object> newInstructions = instructions.Cast<object>().ToList(); int index = -1; foreach (object op in newInstructions) { index++; object elementTo = AccessTools.MakeDeepCopy(op, codeInstructionType, (Func<string, Traverse, Traverse, object>)null, ""); if (unassignedValues.TryGetValue(op, out var fields)) { bool addExceptionInfo = ShouldAddExceptionInfo(op, index, originalInstructions, newInstructions, unassignedValues); Traverse trv = Traverse.Create(elementTo); foreach (KeyValuePair<string, object> field2 in fields.Where((KeyValuePair<string, object> field) => addExceptionInfo || field.Key != "blocks")) { trv.Field(field2.Key).SetValue(field2.Value); } } yield return elementTo; fields = null; } } private static bool IsCodeInstructionsParameter(Type type) { return type.IsGenericType && type.GetGenericTypeDefinition().Name.StartsWith("IEnumerable", StringComparison.Ordinal); } private static IEnumerable ConvertToGeneralInstructions(MethodInfo transpiler, IEnumerable enumerable, out Dictionary<object, Dictionary<string, object>> unassignedValues) { Type type = (from p in transpiler.GetParameters() select p.ParameterType).FirstOrDefault((Type t) => IsCodeInstructionsParameter(t)); if (type == null) { unassignedValues = new Dictionary<object, Dictionary<string, object>>(); return enumerable; } if (type != typeof(IEnumerable<CodeInstruction>)) { return ConvertInstructionsAndUnassignedValues(type, enumerable, out unassignedValues); } unassignedValues = null; return (enumerable as IList<CodeInstruction>) ?? ((enumerable as IEnumerable<CodeInstruction>) ?? enumerable.Cast<CodeInstruction>()).ToList(); } private static List<object> GetTranspilerCallParameters(ILGenerator generator, MethodInfo transpiler, MethodBase method, IEnumerable instructions) { List<object> parameter = new List<object>(); CollectionExtensions.Do<Type>(from param in transpiler.GetParameters() select param.ParameterType, (Action<Type>)delegate(Type type) { if (type.IsAssignableFrom(typeof(ILGenerator))) { parameter.Add(generator); } else if (type.IsAssignableFrom(typeof(MethodBase))) { parameter.Add(method); } else if (IsCodeInstructionsParameter(type)) { parameter.Add(instructions); } }); return parameter; } }
BepInEx/core/Mono.Cecil.dll
Decompiled a week ago
The result has been truncated due to the large size, download it to view full contents!
#define DEBUG using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Cecil.Metadata; using Mono.Cecil.PE; using Mono.Collections.Generic; using Mono.Security.Cryptography; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyProduct("Mono.Cecil")] [assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")] [assembly: ComVisible(false)] [assembly: AssemblyFileVersion("0.11.6.0")] [assembly: AssemblyInformationalVersion("0.11.6.0")] [assembly: AssemblyTitle("Mono.Cecil")] [assembly: Guid("fd225bb4-fa53-44b2-a6db-85f5e48dcb54")] [assembly: InternalsVisibleTo("Mono.Cecil.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")] [assembly: InternalsVisibleTo("Mono.Cecil.Pdb, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")] [assembly: InternalsVisibleTo("Mono.Cecil.Mdb, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")] [assembly: InternalsVisibleTo("Mono.Cecil.Rocks, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyVersion("0.11.6.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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } internal static class Consts { public const string AssemblyName = "Mono.Cecil"; public const string PublicKey = "00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf"; } namespace Mono { internal static class Disposable { public static Disposable<T> Owned<T>(T value) where T : class, IDisposable { return new Disposable<T>(value, owned: true); } public static Disposable<T> NotOwned<T>(T value) where T : class, IDisposable { return new Disposable<T>(value, owned: false); } } internal struct Disposable<T> : IDisposable where T : class, IDisposable { internal readonly T value; private readonly bool owned; public Disposable(T value, bool owned) { this.value = value; this.owned = owned; } public void Dispose() { if (value != null && owned) { value.Dispose(); } } } internal static class Empty<T> { public static readonly T[] Array = new T[0]; } internal class ArgumentNullOrEmptyException : ArgumentException { public ArgumentNullOrEmptyException(string paramName) : base("Argument null or empty", paramName) { } } internal class MergeSort<T> { private readonly T[] elements; private readonly T[] buffer; private readonly IComparer<T> comparer; private MergeSort(T[] elements, IComparer<T> comparer) { this.elements = elements; buffer = new T[elements.Length]; Array.Copy(this.elements, buffer, elements.Length); this.comparer = comparer; } public static void Sort(T[] source, IComparer<T> comparer) { Sort(source, 0, source.Length, comparer); } public static void Sort(T[] source, int start, int length, IComparer<T> comparer) { new MergeSort<T>(source, comparer).Sort(start, length); } private void Sort(int start, int length) { TopDownSplitMerge(buffer, elements, start, length); } private void TopDownSplitMerge(T[] a, T[] b, int start, int end) { if (end - start >= 2) { int num = (end + start) / 2; TopDownSplitMerge(b, a, start, num); TopDownSplitMerge(b, a, num, end); TopDownMerge(a, b, start, num, end); } } private void TopDownMerge(T[] a, T[] b, int start, int middle, int end) { int num = start; int num2 = middle; for (int i = start; i < end; i++) { if (num < middle && (num2 >= end || comparer.Compare(a[num], a[num2]) <= 0)) { b[i] = a[num++]; } else { b[i] = a[num2++]; } } } } } namespace Mono.Security.Cryptography { internal static class CryptoConvert { private static int ToInt32LE(byte[] bytes, int offset) { return (bytes[offset + 3] << 24) | (bytes[offset + 2] << 16) | (bytes[offset + 1] << 8) | bytes[offset]; } private static uint ToUInt32LE(byte[] bytes, int offset) { return (uint)((bytes[offset + 3] << 24) | (bytes[offset + 2] << 16) | (bytes[offset + 1] << 8) | bytes[offset]); } private static byte[] GetBytesLE(int val) { return new byte[4] { (byte)((uint)val & 0xFFu), (byte)((uint)(val >> 8) & 0xFFu), (byte)((uint)(val >> 16) & 0xFFu), (byte)((uint)(val >> 24) & 0xFFu) }; } private static byte[] Trim(byte[] array) { for (int i = 0; i < array.Length; i++) { if (array[i] != 0) { byte[] array2 = new byte[array.Length - i]; Buffer.BlockCopy(array, i, array2, 0, array2.Length); return array2; } } return null; } private static RSA FromCapiPrivateKeyBlob(byte[] blob, int offset) { RSAParameters parameters = default(RSAParameters); try { if (blob[offset] != 7 || blob[offset + 1] != 2 || blob[offset + 2] != 0 || blob[offset + 3] != 0 || ToUInt32LE(blob, offset + 8) != 843141970) { throw new CryptographicException("Invalid blob header"); } int num = ToInt32LE(blob, offset + 12); byte[] array = new byte[4]; Buffer.BlockCopy(blob, offset + 16, array, 0, 4); Array.Reverse(array); parameters.Exponent = Trim(array); int num2 = offset + 20; int num3 = num >> 3; parameters.Modulus = new byte[num3]; Buffer.BlockCopy(blob, num2, parameters.Modulus, 0, num3); Array.Reverse(parameters.Modulus); num2 += num3; int num4 = num3 >> 1; parameters.P = new byte[num4]; Buffer.BlockCopy(blob, num2, parameters.P, 0, num4); Array.Reverse(parameters.P); num2 += num4; parameters.Q = new byte[num4]; Buffer.BlockCopy(blob, num2, parameters.Q, 0, num4); Array.Reverse(parameters.Q); num2 += num4; parameters.DP = new byte[num4]; Buffer.BlockCopy(blob, num2, parameters.DP, 0, num4); Array.Reverse(parameters.DP); num2 += num4; parameters.DQ = new byte[num4]; Buffer.BlockCopy(blob, num2, parameters.DQ, 0, num4); Array.Reverse(parameters.DQ); num2 += num4; parameters.InverseQ = new byte[num4]; Buffer.BlockCopy(blob, num2, parameters.InverseQ, 0, num4); Array.Reverse(parameters.InverseQ); num2 += num4; parameters.D = new byte[num3]; if (num2 + num3 + offset <= blob.Length) { Buffer.BlockCopy(blob, num2, parameters.D, 0, num3); Array.Reverse(parameters.D); } } catch (Exception inner) { throw new CryptographicException("Invalid blob.", inner); } RSA rSA = null; try { rSA = RSA.Create(); rSA.ImportParameters(parameters); } catch (CryptographicException) { bool flag = false; try { CspParameters cspParameters = new CspParameters(); cspParameters.Flags = CspProviderFlags.UseMachineKeyStore; rSA = new RSACryptoServiceProvider(cspParameters); rSA.ImportParameters(parameters); } catch { flag = true; } if (flag) { throw; } } return rSA; } private static RSA FromCapiPublicKeyBlob(byte[] blob, int offset) { try { if (blob[offset] != 6 || blob[offset + 1] != 2 || blob[offset + 2] != 0 || blob[offset + 3] != 0 || ToUInt32LE(blob, offset + 8) != 826364754) { throw new CryptographicException("Invalid blob header"); } int num = ToInt32LE(blob, offset + 12); RSAParameters parameters = default(RSAParameters); parameters.Exponent = new byte[3]; parameters.Exponent[0] = blob[offset + 18]; parameters.Exponent[1] = blob[offset + 17]; parameters.Exponent[2] = blob[offset + 16]; int srcOffset = offset + 20; int num2 = num >> 3; parameters.Modulus = new byte[num2]; Buffer.BlockCopy(blob, srcOffset, parameters.Modulus, 0, num2); Array.Reverse(parameters.Modulus); RSA rSA = null; try { rSA = RSA.Create(); rSA.ImportParameters(parameters); } catch (CryptographicException) { CspParameters cspParameters = new CspParameters(); cspParameters.Flags = CspProviderFlags.UseMachineKeyStore; rSA = new RSACryptoServiceProvider(cspParameters); rSA.ImportParameters(parameters); } return rSA; } catch (Exception inner) { throw new CryptographicException("Invalid blob.", inner); } } public static RSA FromCapiKeyBlob(byte[] blob) { return FromCapiKeyBlob(blob, 0); } public static RSA FromCapiKeyBlob(byte[] blob, int offset) { if (blob == null) { throw new ArgumentNullException("blob"); } if (offset >= blob.Length) { throw new ArgumentException("blob is too small."); } switch (blob[offset]) { case 0: if (blob[offset + 12] == 6) { return FromCapiPublicKeyBlob(blob, offset + 12); } break; case 6: return FromCapiPublicKeyBlob(blob, offset); case 7: return FromCapiPrivateKeyBlob(blob, offset); } throw new CryptographicException("Unknown blob format."); } public static byte[] ToCapiPublicKeyBlob(RSA rsa) { RSAParameters rSAParameters = rsa.ExportParameters(includePrivateParameters: false); int num = rSAParameters.Modulus.Length; byte[] array = new byte[20 + num]; array[0] = 6; array[1] = 2; array[5] = 36; array[8] = 82; array[9] = 83; array[10] = 65; array[11] = 49; byte[] bytesLE = GetBytesLE(num << 3); array[12] = bytesLE[0]; array[13] = bytesLE[1]; array[14] = bytesLE[2]; array[15] = bytesLE[3]; int num2 = 16; int num3 = rSAParameters.Exponent.Length; while (num3 > 0) { array[num2++] = rSAParameters.Exponent[--num3]; } num2 = 20; byte[] modulus = rSAParameters.Modulus; int num4 = modulus.Length; Array.Reverse(modulus, 0, num4); Buffer.BlockCopy(modulus, 0, array, num2, num4); num2 += num4; return array; } } } namespace Mono.Collections.Generic { public class Collection<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection { public struct Enumerator : IEnumerator<T>, IEnumerator, IDisposable { private Collection<T> collection; private T current; private int next; private readonly int version; public T Current => current; object IEnumerator.Current { get { CheckState(); if (next <= 0) { throw new InvalidOperationException(); } return current; } } internal Enumerator(Collection<T> collection) { this = default(Enumerator); this.collection = collection; version = collection.version; } public bool MoveNext() { CheckState(); if (next < 0) { return false; } if (next < collection.size) { current = collection.items[next++]; return true; } next = -1; return false; } public void Reset() { CheckState(); next = 0; } private void CheckState() { if (collection == null) { throw new ObjectDisposedException(GetType().FullName); } if (version != collection.version) { throw new InvalidOperationException(); } } public void Dispose() { collection = null; } } internal T[] items; internal int size; private int version; public int Count => size; public T this[int index] { get { if (index >= size) { throw new ArgumentOutOfRangeException(); } return items[index]; } set { CheckIndex(index); if (index == size) { throw new ArgumentOutOfRangeException(); } OnSet(value, index); items[index] = value; } } public int Capacity { get { return items.Length; } set { if (value < 0 || value < size) { throw new ArgumentOutOfRangeException(); } Resize(value); } } bool ICollection<T>.IsReadOnly => false; bool IList.IsFixedSize => false; bool IList.IsReadOnly => false; object IList.this[int index] { get { return this[index]; } set { CheckIndex(index); try { this[index] = (T)value; return; } catch (InvalidCastException) { } catch (NullReferenceException) { } throw new ArgumentException(); } } int ICollection.Count => Count; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; public Collection() { items = Empty<T>.Array; } public Collection(int capacity) { if (capacity < 0) { throw new ArgumentOutOfRangeException(); } items = ((capacity == 0) ? Empty<T>.Array : new T[capacity]); } public Collection(ICollection<T> items) { if (items == null) { throw new ArgumentNullException("items"); } this.items = new T[items.Count]; items.CopyTo(this.items, 0); size = this.items.Length; } public void Add(T item) { if (size == items.Length) { Grow(1); } OnAdd(item, size); items[size++] = item; version++; } public bool Contains(T item) { return IndexOf(item) != -1; } public int IndexOf(T item) { return Array.IndexOf(items, item, 0, size); } public void Insert(int index, T item) { CheckIndex(index); if (size == items.Length) { Grow(1); } OnInsert(item, index); Shift(index, 1); items[index] = item; version++; } public void RemoveAt(int index) { if (index < 0 || index >= size) { throw new ArgumentOutOfRangeException(); } T item = items[index]; OnRemove(item, index); Shift(index, -1); version++; } public bool Remove(T item) { int num = IndexOf(item); if (num == -1) { return false; } OnRemove(item, num); Shift(num, -1); version++; return true; } public void Clear() { OnClear(); Array.Clear(items, 0, size); size = 0; version++; } public void CopyTo(T[] array, int arrayIndex) { Array.Copy(items, 0, array, arrayIndex, size); } public T[] ToArray() { T[] array = new T[size]; Array.Copy(items, 0, array, 0, size); return array; } private void CheckIndex(int index) { if (index < 0 || index > size) { throw new ArgumentOutOfRangeException(); } } private void Shift(int start, int delta) { if (delta < 0) { start -= delta; } if (start < size) { Array.Copy(items, start, items, start + delta, size - start); } size += delta; if (delta < 0) { Array.Clear(items, size, -delta); } } protected virtual void OnAdd(T item, int index) { } protected virtual void OnInsert(T item, int index) { } protected virtual void OnSet(T item, int index) { } protected virtual void OnRemove(T item, int index) { } protected virtual void OnClear() { } internal virtual void Grow(int desired) { int num = size + desired; if (num > items.Length) { num = Math.Max(Math.Max(items.Length * 2, 4), num); Resize(num); } } protected void Resize(int new_size) { if (new_size != size) { if (new_size < size) { throw new ArgumentOutOfRangeException(); } items = items.Resize(new_size); } } int IList.Add(object value) { try { Add((T)value); return size - 1; } catch (InvalidCastException) { } catch (NullReferenceException) { } throw new ArgumentException(); } void IList.Clear() { Clear(); } bool IList.Contains(object value) { return ((IList)this).IndexOf(value) > -1; } int IList.IndexOf(object value) { try { return IndexOf((T)value); } catch (InvalidCastException) { } catch (NullReferenceException) { } return -1; } void IList.Insert(int index, object value) { CheckIndex(index); try { Insert(index, (T)value); return; } catch (InvalidCastException) { } catch (NullReferenceException) { } throw new ArgumentException(); } void IList.Remove(object value) { try { Remove((T)value); } catch (InvalidCastException) { } catch (NullReferenceException) { } } void IList.RemoveAt(int index) { RemoveAt(index); } void ICollection.CopyTo(Array array, int index) { Array.Copy(items, 0, array, index, size); } public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } } public sealed class ReadOnlyCollection<T> : Collection<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection { private static ReadOnlyCollection<T> empty; public static ReadOnlyCollection<T> Empty { get { if (empty != null) { return empty; } Interlocked.CompareExchange(ref empty, new ReadOnlyCollection<T>(), null); return empty; } } bool ICollection<T>.IsReadOnly => true; bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; private ReadOnlyCollection() { } public ReadOnlyCollection(T[] array) { if (array == null) { throw new ArgumentNullException(); } Initialize(array, array.Length); } public ReadOnlyCollection(Collection<T> collection) { if (collection == null) { throw new ArgumentNullException(); } Initialize(collection.items, collection.size); } private void Initialize(T[] items, int size) { base.items = new T[size]; Array.Copy(items, 0, base.items, 0, size); base.size = size; } internal override void Grow(int desired) { throw new InvalidOperationException(); } protected override void OnAdd(T item, int index) { throw new InvalidOperationException(); } protected override void OnClear() { throw new InvalidOperationException(); } protected override void OnInsert(T item, int index) { throw new InvalidOperationException(); } protected override void OnRemove(T item, int index) { throw new InvalidOperationException(); } protected override void OnSet(T item, int index) { throw new InvalidOperationException(); } } } namespace Mono.Cecil { internal static class Mixin { public enum Argument { name, fileName, fullName, stream, type, method, field, parameters, module, modifierType, eventType, fieldType, declaringType, returnType, propertyType, interfaceType, constraintType } public static Version ZeroVersion = new Version(0, 0, 0, 0); public const int NotResolvedMarker = -2; public const int NoDataMarker = -1; internal static object NoValue = new object(); internal static object NotResolved = new object(); public const string mscorlib = "mscorlib"; public const string system_runtime = "System.Runtime"; public const string system_private_corelib = "System.Private.CoreLib"; public const string netstandard = "netstandard"; public const int TableCount = 58; public const int CodedIndexCount = 14; public static bool IsNullOrEmpty<T>(this T[] self) { return self == null || self.Length == 0; } public static bool IsNullOrEmpty<T>(this Collection<T> self) { return self == null || self.size == 0; } public static T[] Resize<T>(this T[] self, int length) { Array.Resize(ref self, length); return self; } public static T[] Add<T>(this T[] self, T item) { if (self == null) { self = new T[1] { item }; return self; } self = self.Resize(self.Length + 1); self[^1] = item; return self; } public static Version CheckVersion(Version version) { if (version == null) { return ZeroVersion; } if (version.Build == -1) { return new Version(version.Major, version.Minor, 0, 0); } if (version.Revision == -1) { return new Version(version.Major, version.Minor, version.Build, 0); } return version; } public static bool TryGetUniqueDocument(this MethodDebugInformation info, out Document document) { document = info.SequencePoints[0].Document; for (int i = 1; i < info.SequencePoints.Count; i++) { SequencePoint sequencePoint = info.SequencePoints[i]; if (sequencePoint.Document != document) { return false; } } return true; } public static void ResolveConstant(this IConstantProvider self, ref object constant, ModuleDefinition module) { if (module == null) { constant = NoValue; return; } lock (module.SyncRoot) { if (constant != NotResolved) { return; } if (module.HasImage()) { constant = module.Read(self, (IConstantProvider provider, MetadataReader reader) => reader.ReadConstant(provider)); } else { constant = NoValue; } } } public static bool GetHasCustomAttributes(this ICustomAttributeProvider self, ModuleDefinition module) { return module.HasImage() && module.Read(self, (ICustomAttributeProvider provider, MetadataReader reader) => reader.HasCustomAttributes(provider)); } public static Collection<CustomAttribute> GetCustomAttributes(this ICustomAttributeProvider self, ref Collection<CustomAttribute> variable, ModuleDefinition module) { if (module.HasImage()) { return module.Read(ref variable, self, (ICustomAttributeProvider provider, MetadataReader reader) => reader.ReadCustomAttributes(provider)); } Interlocked.CompareExchange(ref variable, new Collection<CustomAttribute>(), null); return variable; } public static bool ContainsGenericParameter(this IGenericInstance self) { Collection<TypeReference> genericArguments = self.GenericArguments; for (int i = 0; i < genericArguments.Count; i++) { if (genericArguments[i].ContainsGenericParameter) { return true; } } return false; } public static void GenericInstanceFullName(this IGenericInstance self, StringBuilder builder) { builder.Append("<"); Collection<TypeReference> genericArguments = self.GenericArguments; for (int i = 0; i < genericArguments.Count; i++) { if (i > 0) { builder.Append(","); } builder.Append(genericArguments[i].FullName); } builder.Append(">"); } public static bool GetHasGenericParameters(this IGenericParameterProvider self, ModuleDefinition module) { return module.HasImage() && module.Read(self, (IGenericParameterProvider provider, MetadataReader reader) => reader.HasGenericParameters(provider)); } public static Collection<GenericParameter> GetGenericParameters(this IGenericParameterProvider self, ref Collection<GenericParameter> collection, ModuleDefinition module) { if (module.HasImage()) { return module.Read(ref collection, self, (IGenericParameterProvider provider, MetadataReader reader) => reader.ReadGenericParameters(provider)); } Interlocked.CompareExchange(ref collection, new GenericParameterCollection(self), null); return collection; } public static bool GetHasMarshalInfo(this IMarshalInfoProvider self, ModuleDefinition module) { return module.HasImage() && module.Read(self, (IMarshalInfoProvider provider, MetadataReader reader) => reader.HasMarshalInfo(provider)); } public static MarshalInfo GetMarshalInfo(this IMarshalInfoProvider self, ref MarshalInfo variable, ModuleDefinition module) { return module.HasImage() ? module.Read(ref variable, self, (IMarshalInfoProvider provider, MetadataReader reader) => reader.ReadMarshalInfo(provider)) : null; } public static bool GetAttributes(this uint self, uint attributes) { return (self & attributes) != 0; } public static uint SetAttributes(this uint self, uint attributes, bool value) { if (value) { return self | attributes; } return self & ~attributes; } public static bool GetMaskedAttributes(this uint self, uint mask, uint attributes) { return (self & mask) == attributes; } public static uint SetMaskedAttributes(this uint self, uint mask, uint attributes, bool value) { if (value) { self &= ~mask; return self | attributes; } return self & ~(mask & attributes); } public static bool GetAttributes(this ushort self, ushort attributes) { return (self & attributes) != 0; } public static ushort SetAttributes(this ushort self, ushort attributes, bool value) { if (value) { return (ushort)(self | attributes); } return (ushort)(self & ~attributes); } public static bool GetMaskedAttributes(this ushort self, ushort mask, uint attributes) { return (self & mask) == attributes; } public static ushort SetMaskedAttributes(this ushort self, ushort mask, uint attributes, bool value) { if (value) { self = (ushort)(self & ~mask); return (ushort)(self | attributes); } return (ushort)(self & ~(mask & attributes)); } public static bool HasImplicitThis(this IMethodSignature self) { return self.HasThis && !self.ExplicitThis; } public static void MethodSignatureFullName(this IMethodSignature self, StringBuilder builder) { builder.Append("("); if (self.HasParameters) { Collection<ParameterDefinition> parameters = self.Parameters; for (int i = 0; i < parameters.Count; i++) { ParameterDefinition parameterDefinition = parameters[i]; if (i > 0) { builder.Append(","); } if (parameterDefinition.ParameterType.IsSentinel) { builder.Append("...,"); } builder.Append(parameterDefinition.ParameterType.FullName); } } builder.Append(")"); } public static void CheckModule(ModuleDefinition module) { if (module == null) { throw new ArgumentNullException(Argument.module.ToString()); } } public static bool TryGetAssemblyNameReference(this ModuleDefinition module, AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference) { Collection<AssemblyNameReference> assemblyReferences = module.AssemblyReferences; for (int i = 0; i < assemblyReferences.Count; i++) { AssemblyNameReference assemblyNameReference = assemblyReferences[i]; if (Equals(name_reference, assemblyNameReference)) { assembly_reference = assemblyNameReference; return true; } } assembly_reference = null; return false; } private static bool Equals(byte[] a, byte[] b) { if (a == b) { return true; } if (a == null) { return false; } if (a.Length != b.Length) { return false; } for (int i = 0; i < a.Length; i++) { if (a[i] != b[i]) { return false; } } return true; } private static bool Equals<T>(T a, T b) where T : class, IEquatable<T> { if (a == b) { return true; } return a?.Equals(b) ?? false; } private static bool Equals(AssemblyNameReference a, AssemblyNameReference b) { if (a == b) { return true; } if (a.Name != b.Name) { return false; } if (!Equals(a.Version, b.Version)) { return false; } if (a.Culture != b.Culture) { return false; } if (!Equals(a.PublicKeyToken, b.PublicKeyToken)) { return false; } return true; } public static ParameterDefinition GetParameter(this Mono.Cecil.Cil.MethodBody self, int index) { MethodDefinition method = self.method; if (method.HasThis) { if (index == 0) { return self.ThisParameter; } index--; } Collection<ParameterDefinition> parameters = method.Parameters; if (index < 0 || index >= parameters.size) { return null; } return parameters[index]; } public static VariableDefinition GetVariable(this Mono.Cecil.Cil.MethodBody self, int index) { Collection<VariableDefinition> variables = self.Variables; if (index < 0 || index >= variables.size) { return null; } return variables[index]; } public static bool GetSemantics(this MethodDefinition self, MethodSemanticsAttributes semantics) { return (self.SemanticsAttributes & semantics) != 0; } public static void SetSemantics(this MethodDefinition self, MethodSemanticsAttributes semantics, bool value) { if (value) { self.SemanticsAttributes |= semantics; } else { self.SemanticsAttributes &= (MethodSemanticsAttributes)(ushort)(~(int)semantics); } } public static bool IsVarArg(this IMethodSignature self) { return self.CallingConvention == MethodCallingConvention.VarArg; } public static int GetSentinelPosition(this IMethodSignature self) { if (!self.HasParameters) { return -1; } Collection<ParameterDefinition> parameters = self.Parameters; for (int i = 0; i < parameters.Count; i++) { if (parameters[i].ParameterType.IsSentinel) { return i; } } return -1; } public static void CheckName(object name) { if (name == null) { throw new ArgumentNullException(Argument.name.ToString()); } } public static void CheckName(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullOrEmptyException(Argument.name.ToString()); } } public static void CheckFileName(string fileName) { if (string.IsNullOrEmpty(fileName)) { throw new ArgumentNullOrEmptyException(Argument.fileName.ToString()); } } public static void CheckFullName(string fullName) { if (string.IsNullOrEmpty(fullName)) { throw new ArgumentNullOrEmptyException(Argument.fullName.ToString()); } } public static void CheckStream(object stream) { if (stream == null) { throw new ArgumentNullException(Argument.stream.ToString()); } } public static void CheckWriteSeek(Stream stream) { if (!stream.CanWrite || !stream.CanSeek) { throw new ArgumentException("Stream must be writable and seekable."); } } public static void CheckReadSeek(Stream stream) { if (!stream.CanRead || !stream.CanSeek) { throw new ArgumentException("Stream must be readable and seekable."); } } public static void CheckType(object type) { if (type == null) { throw new ArgumentNullException(Argument.type.ToString()); } } public static void CheckType(object type, Argument argument) { if (type == null) { throw new ArgumentNullException(argument.ToString()); } } public static void CheckField(object field) { if (field == null) { throw new ArgumentNullException(Argument.field.ToString()); } } public static void CheckMethod(object method) { if (method == null) { throw new ArgumentNullException(Argument.method.ToString()); } } public static void CheckParameters(object parameters) { if (parameters == null) { throw new ArgumentNullException(Argument.parameters.ToString()); } } public static uint GetTimestamp() { return (uint)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; } public static bool HasImage(this ModuleDefinition self) { return self?.HasImage ?? false; } public static string GetFileName(this Stream self) { if (!(self is FileStream fileStream)) { return string.Empty; } return Path.GetFullPath(fileStream.Name); } public static TargetRuntime ParseRuntime(this string self) { if (string.IsNullOrEmpty(self)) { return TargetRuntime.Net_4_0; } return self[1] switch { '1' => (self[3] != '0') ? TargetRuntime.Net_1_1 : TargetRuntime.Net_1_0, '2' => TargetRuntime.Net_2_0, _ => TargetRuntime.Net_4_0, }; } public static string RuntimeVersionString(this TargetRuntime runtime) { return runtime switch { TargetRuntime.Net_1_0 => "v1.0.3705", TargetRuntime.Net_1_1 => "v1.1.4322", TargetRuntime.Net_2_0 => "v2.0.50727", _ => "v4.0.30319", }; } public static bool IsWindowsMetadata(this ModuleDefinition module) { return module.MetadataKind != MetadataKind.Ecma335; } public static byte[] ReadAll(this Stream self) { MemoryStream memoryStream = new MemoryStream((int)self.Length); byte[] array = new byte[1024]; int count; while ((count = self.Read(array, 0, array.Length)) != 0) { memoryStream.Write(array, 0, count); } return memoryStream.ToArray(); } public static void Read(object o) { } public static bool GetHasSecurityDeclarations(this ISecurityDeclarationProvider self, ModuleDefinition module) { return module.HasImage() && module.Read(self, (ISecurityDeclarationProvider provider, MetadataReader reader) => reader.HasSecurityDeclarations(provider)); } public static Collection<SecurityDeclaration> GetSecurityDeclarations(this ISecurityDeclarationProvider self, ref Collection<SecurityDeclaration> variable, ModuleDefinition module) { if (module.HasImage) { return module.Read(ref variable, self, (ISecurityDeclarationProvider provider, MetadataReader reader) => reader.ReadSecurityDeclarations(provider)); } Interlocked.CompareExchange(ref variable, new Collection<SecurityDeclaration>(), null); return variable; } public static TypeReference GetEnumUnderlyingType(this TypeDefinition self) { Collection<FieldDefinition> fields = self.Fields; for (int i = 0; i < fields.Count; i++) { FieldDefinition fieldDefinition = fields[i]; if (!fieldDefinition.IsStatic) { return fieldDefinition.FieldType; } } throw new ArgumentException(); } public static TypeDefinition GetNestedType(this TypeDefinition self, string fullname) { if (!self.HasNestedTypes) { return null; } Collection<TypeDefinition> nestedTypes = self.NestedTypes; for (int i = 0; i < nestedTypes.Count; i++) { TypeDefinition typeDefinition = nestedTypes[i]; if (typeDefinition.TypeFullName() == fullname) { return typeDefinition; } } return null; } public static bool IsPrimitive(this ElementType self) { ElementType elementType = self; ElementType elementType2 = elementType; if (elementType2 - 2 <= ElementType.U8 || elementType2 - 24 <= ElementType.Void) { return true; } return false; } public static string TypeFullName(this TypeReference self) { return string.IsNullOrEmpty(self.Namespace) ? self.Name : (self.Namespace + "." + self.Name); } public static bool IsTypeOf(this TypeReference self, string @namespace, string name) { return self.Name == name && self.Namespace == @namespace; } public static bool IsTypeSpecification(this TypeReference type) { switch (type.etype) { case ElementType.Ptr: case ElementType.ByRef: case ElementType.Var: case ElementType.Array: case ElementType.GenericInst: case ElementType.FnPtr: case ElementType.SzArray: case ElementType.MVar: case ElementType.CModReqD: case ElementType.CModOpt: case ElementType.Sentinel: case ElementType.Pinned: return true; default: return false; } } public static TypeDefinition CheckedResolve(this TypeReference self) { TypeDefinition typeDefinition = self.Resolve(); if (typeDefinition == null) { throw new ResolutionException(self); } return typeDefinition; } public static bool TryGetCoreLibraryReference(this ModuleDefinition module, out AssemblyNameReference reference) { Collection<AssemblyNameReference> assemblyReferences = module.AssemblyReferences; for (int i = 0; i < assemblyReferences.Count; i++) { reference = assemblyReferences[i]; if (IsCoreLibrary(reference)) { return true; } } reference = null; return false; } public static bool IsCoreLibrary(this ModuleDefinition module) { if (module.Assembly == null) { return false; } if (!IsCoreLibrary(module.Assembly.Name)) { return false; } if (module.HasImage && module.Read(module, (ModuleDefinition m, MetadataReader reader) => reader.image.GetTableLength(Table.AssemblyRef) > 0)) { return false; } return true; } public static void KnownValueType(this TypeReference type) { if (!type.IsDefinition) { type.IsValueType = true; } } private static bool IsCoreLibrary(AssemblyNameReference reference) { string name = reference.Name; int result; switch (name) { default: result = ((name == "netstandard") ? 1 : 0); break; case "mscorlib": case "System.Runtime": case "System.Private.CoreLib": result = 1; break; } return (byte)result != 0; } public static ImageDebugHeaderEntry GetCodeViewEntry(this ImageDebugHeader header) { return header.GetEntry(ImageDebugType.CodeView); } public static ImageDebugHeaderEntry GetDeterministicEntry(this ImageDebugHeader header) { return header.GetEntry(ImageDebugType.Deterministic); } public static ImageDebugHeader AddDeterministicEntry(this ImageDebugHeader header) { ImageDebugDirectory directory = default(ImageDebugDirectory); directory.Type = ImageDebugType.Deterministic; ImageDebugHeaderEntry imageDebugHeaderEntry = new ImageDebugHeaderEntry(directory, Empty<byte>.Array); if (header == null) { return new ImageDebugHeader(imageDebugHeaderEntry); } ImageDebugHeaderEntry[] array = new ImageDebugHeaderEntry[header.Entries.Length + 1]; Array.Copy(header.Entries, array, header.Entries.Length); array[^1] = imageDebugHeaderEntry; return new ImageDebugHeader(array); } public static ImageDebugHeaderEntry GetEmbeddedPortablePdbEntry(this ImageDebugHeader header) { return header.GetEntry(ImageDebugType.EmbeddedPortablePdb); } public static ImageDebugHeaderEntry GetPdbChecksumEntry(this ImageDebugHeader header) { return header.GetEntry(ImageDebugType.PdbChecksum); } private static ImageDebugHeaderEntry GetEntry(this ImageDebugHeader header, ImageDebugType type) { if (!header.HasEntries) { return null; } for (int i = 0; i < header.Entries.Length; i++) { ImageDebugHeaderEntry imageDebugHeaderEntry = header.Entries[i]; if (imageDebugHeaderEntry.Directory.Type == type) { return imageDebugHeaderEntry; } } return null; } public static string GetPdbFileName(string assemblyFileName) { return Path.ChangeExtension(assemblyFileName, ".pdb"); } public static string GetMdbFileName(string assemblyFileName) { return assemblyFileName + ".mdb"; } public static bool IsPortablePdb(string fileName) { using FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); return IsPortablePdb(stream); } public static bool IsPortablePdb(Stream stream) { if (stream.Length < 4) { return false; } long position = stream.Position; try { BinaryReader binaryReader = new BinaryReader(stream); return binaryReader.ReadUInt32() == 1112167234; } finally { stream.Position = position; } } public static bool GetHasCustomDebugInformations(this ICustomDebugInformationProvider self, ref Collection<CustomDebugInformation> collection, ModuleDefinition module) { if (module.HasImage()) { module.Read(ref collection, self, (ICustomDebugInformationProvider provider, MetadataReader reader) => reader.module.symbol_reader?.Read(provider)); } return !collection.IsNullOrEmpty(); } public static Collection<CustomDebugInformation> GetCustomDebugInformations(this ICustomDebugInformationProvider self, ref Collection<CustomDebugInformation> collection, ModuleDefinition module) { if (module.HasImage()) { module.Read(ref collection, self, (ICustomDebugInformationProvider provider, MetadataReader reader) => reader.module.symbol_reader?.Read(provider)); } Interlocked.CompareExchange(ref collection, new Collection<CustomDebugInformation>(), null); return collection; } public static uint ReadCompressedUInt32(this byte[] data, ref int position) { uint result; if ((data[position] & 0x80) == 0) { result = data[position]; position++; } else if ((data[position] & 0x40) == 0) { result = (uint)((data[position] & -129) << 8); result |= data[position + 1]; position += 2; } else { result = (uint)((data[position] & -193) << 24); result |= (uint)(data[position + 1] << 16); result |= (uint)(data[position + 2] << 8); result |= data[position + 3]; position += 4; } return result; } public static MetadataToken GetMetadataToken(this CodedIndex self, uint data) { uint rid; TokenType type; switch (self) { case CodedIndex.TypeDefOrRef: rid = data >> 2; switch (data & 3) { case 0u: break; case 1u: goto IL_0075; case 2u: goto IL_0080; default: goto end_IL_0006; } type = TokenType.TypeDef; goto IL_0644; case CodedIndex.HasConstant: rid = data >> 2; switch (data & 3) { case 0u: break; case 1u: goto IL_00bd; case 2u: goto IL_00c8; default: goto end_IL_0006; } type = TokenType.Field; goto IL_0644; case CodedIndex.HasCustomAttribute: rid = data >> 5; switch (data & 0x1F) { case 0u: break; case 1u: goto IL_0155; case 2u: goto IL_0160; case 3u: goto IL_016b; case 4u: goto IL_0176; case 5u: goto IL_0181; case 6u: goto IL_018c; case 7u: goto IL_0197; case 8u: goto IL_019e; case 9u: goto IL_01a9; case 10u: goto IL_01b4; case 11u: goto IL_01bf; case 12u: goto IL_01ca; case 13u: goto IL_01d5; case 14u: goto IL_01e0; case 15u: goto IL_01eb; case 16u: goto IL_01f6; case 17u: goto IL_0201; case 18u: goto IL_020c; case 19u: goto IL_0217; case 20u: goto IL_0222; case 21u: goto IL_022d; default: goto end_IL_0006; } type = TokenType.Method; goto IL_0644; case CodedIndex.HasFieldMarshal: { rid = data >> 1; uint num11 = data & 1u; uint num12 = num11; if (num12 != 0) { if (num12 != 1) { break; } type = TokenType.Param; } else { type = TokenType.Field; } goto IL_0644; } case CodedIndex.HasDeclSecurity: rid = data >> 2; switch (data & 3) { case 0u: break; case 1u: goto IL_029f; case 2u: goto IL_02aa; default: goto end_IL_0006; } type = TokenType.TypeDef; goto IL_0644; case CodedIndex.MemberRefParent: rid = data >> 3; switch (data & 7) { case 0u: break; case 1u: goto IL_02ef; case 2u: goto IL_02fa; case 3u: goto IL_0305; case 4u: goto IL_0310; default: goto end_IL_0006; } type = TokenType.TypeDef; goto IL_0644; case CodedIndex.HasSemantics: { rid = data >> 1; uint num9 = data & 1u; uint num10 = num9; if (num10 != 0) { if (num10 != 1) { break; } type = TokenType.Property; } else { type = TokenType.Event; } goto IL_0644; } case CodedIndex.MethodDefOrRef: { rid = data >> 1; uint num7 = data & 1u; uint num8 = num7; if (num8 != 0) { if (num8 != 1) { break; } type = TokenType.MemberRef; } else { type = TokenType.Method; } goto IL_0644; } case CodedIndex.MemberForwarded: { rid = data >> 1; uint num5 = data & 1u; uint num6 = num5; if (num6 != 0) { if (num6 != 1) { break; } type = TokenType.Method; } else { type = TokenType.Field; } goto IL_0644; } case CodedIndex.Implementation: rid = data >> 2; switch (data & 3) { case 0u: break; case 1u: goto IL_03ec; case 2u: goto IL_03f7; default: goto end_IL_0006; } type = TokenType.File; goto IL_0644; case CodedIndex.CustomAttributeType: { rid = data >> 3; uint num3 = data & 7u; uint num4 = num3; if (num4 != 2) { if (num4 != 3) { break; } type = TokenType.MemberRef; } else { type = TokenType.Method; } goto IL_0644; } case CodedIndex.ResolutionScope: rid = data >> 2; switch (data & 3) { case 0u: break; case 1u: goto IL_046a; case 2u: goto IL_0475; case 3u: goto IL_0480; default: goto end_IL_0006; } type = TokenType.Module; goto IL_0644; case CodedIndex.TypeOrMethodDef: { rid = data >> 1; uint num = data & 1u; uint num2 = num; if (num2 != 0) { if (num2 != 1) { break; } type = TokenType.Method; } else { type = TokenType.TypeDef; } goto IL_0644; } case CodedIndex.HasCustomDebugInformation: { rid = data >> 5; switch (data & 0x1F) { case 0u: break; case 1u: goto IL_0556; case 2u: goto IL_0561; case 3u: goto IL_056c; case 4u: goto IL_0577; case 5u: goto IL_0582; case 6u: goto IL_058d; case 7u: goto IL_0598; case 8u: goto IL_059f; case 9u: goto IL_05aa; case 10u: goto IL_05b5; case 11u: goto IL_05c0; case 12u: goto IL_05c8; case 13u: goto IL_05d0; case 14u: goto IL_05d8; case 15u: goto IL_05e0; case 16u: goto IL_05e8; case 17u: goto IL_05f0; case 18u: goto IL_05f8; case 19u: goto IL_0600; case 20u: goto IL_0608; case 21u: goto IL_0610; case 22u: goto IL_0618; case 23u: goto IL_0620; case 24u: goto IL_0628; case 25u: goto IL_0630; case 26u: goto IL_0638; default: goto end_IL_0006; } type = TokenType.Method; goto IL_0644; } IL_0638: type = TokenType.ImportScope; goto IL_0644; IL_0630: type = TokenType.LocalConstant; goto IL_0644; IL_0628: type = TokenType.LocalVariable; goto IL_0644; IL_0620: type = TokenType.LocalScope; goto IL_0644; IL_0618: type = TokenType.Document; goto IL_0644; IL_0610: type = TokenType.MethodSpec; goto IL_0644; IL_0608: type = TokenType.GenericParamConstraint; goto IL_0644; IL_0600: type = TokenType.GenericParam; goto IL_0644; IL_05f8: type = TokenType.ManifestResource; goto IL_0644; IL_05f0: type = TokenType.ExportedType; goto IL_0644; IL_05e8: type = TokenType.File; goto IL_0644; IL_05e0: type = TokenType.AssemblyRef; goto IL_0644; IL_05d8: type = TokenType.Assembly; goto IL_0644; IL_05d0: type = TokenType.TypeSpec; goto IL_0644; IL_05c8: type = TokenType.ModuleRef; goto IL_0644; IL_05c0: type = TokenType.Signature; goto IL_0644; IL_05b5: type = TokenType.Event; goto IL_0644; IL_05aa: type = TokenType.Property; goto IL_0644; IL_059f: type = TokenType.Permission; goto IL_0644; IL_0598: type = TokenType.Module; goto IL_0644; IL_058d: type = TokenType.MemberRef; goto IL_0644; IL_0582: type = TokenType.InterfaceImpl; goto IL_0644; IL_0577: type = TokenType.Param; goto IL_0644; IL_056c: type = TokenType.TypeDef; goto IL_0644; IL_0561: type = TokenType.TypeRef; goto IL_0644; IL_0556: type = TokenType.Field; goto IL_0644; IL_01f6: type = TokenType.File; goto IL_0644; IL_01eb: type = TokenType.AssemblyRef; goto IL_0644; IL_01d5: type = TokenType.TypeSpec; goto IL_0644; IL_01e0: type = TokenType.Assembly; goto IL_0644; IL_0480: type = TokenType.TypeRef; goto IL_0644; IL_0475: type = TokenType.AssemblyRef; goto IL_0644; IL_046a: type = TokenType.ModuleRef; goto IL_0644; IL_01ca: type = TokenType.ModuleRef; goto IL_0644; IL_01bf: type = TokenType.Signature; goto IL_0644; IL_01a9: type = TokenType.Property; goto IL_0644; IL_01b4: type = TokenType.Event; goto IL_0644; IL_03f7: type = TokenType.ExportedType; goto IL_0644; IL_03ec: type = TokenType.AssemblyRef; goto IL_0644; IL_019e: type = TokenType.Permission; goto IL_0644; IL_0197: type = TokenType.Module; goto IL_0644; IL_0181: type = TokenType.InterfaceImpl; goto IL_0644; IL_018c: type = TokenType.MemberRef; goto IL_0644; IL_0176: type = TokenType.Param; goto IL_0644; IL_0160: type = TokenType.TypeRef; goto IL_0644; IL_016b: type = TokenType.TypeDef; goto IL_0644; IL_0155: type = TokenType.Field; goto IL_0644; IL_0075: type = TokenType.TypeRef; goto IL_0644; IL_0310: type = TokenType.TypeSpec; goto IL_0644; IL_0305: type = TokenType.Method; goto IL_0644; IL_02fa: type = TokenType.ModuleRef; goto IL_0644; IL_02ef: type = TokenType.TypeRef; goto IL_0644; IL_00c8: type = TokenType.Property; goto IL_0644; IL_02aa: type = TokenType.Assembly; goto IL_0644; IL_029f: type = TokenType.Method; goto IL_0644; IL_00bd: type = TokenType.Param; goto IL_0644; IL_0644: return new MetadataToken(type, rid); IL_0080: type = TokenType.TypeSpec; goto IL_0644; IL_022d: type = TokenType.MethodSpec; goto IL_0644; IL_0222: type = TokenType.GenericParamConstraint; goto IL_0644; IL_0217: type = TokenType.GenericParam; goto IL_0644; IL_020c: type = TokenType.ManifestResource; goto IL_0644; IL_0201: type = TokenType.ExportedType; goto IL_0644; end_IL_0006: break; } return MetadataToken.Zero; } public static uint CompressMetadataToken(this CodedIndex self, MetadataToken token) { uint result = 0u; if (token.RID == 0) { return result; } switch (self) { case CodedIndex.TypeDefOrRef: result = token.RID << 2; switch (token.TokenType) { case TokenType.TypeDef: return result | 0u; case TokenType.TypeRef: return result | 1u; case TokenType.TypeSpec: return result | 2u; } break; case CodedIndex.HasConstant: result = token.RID << 2; switch (token.TokenType) { case TokenType.Field: return result | 0u; case TokenType.Param: return result | 1u; case TokenType.Property: return result | 2u; } break; case CodedIndex.HasCustomAttribute: result = token.RID << 5; switch (token.TokenType) { case TokenType.Method: return result | 0u; case TokenType.Field: return result | 1u; case TokenType.TypeRef: return result | 2u; case TokenType.TypeDef: return result | 3u; case TokenType.Param: return result | 4u; case TokenType.InterfaceImpl: return result | 5u; case TokenType.MemberRef: return result | 6u; case TokenType.Module: return result | 7u; case TokenType.Permission: return result | 8u; case TokenType.Property: return result | 9u; case TokenType.Event: return result | 0xAu; case TokenType.Signature: return result | 0xBu; case TokenType.ModuleRef: return result | 0xCu; case TokenType.TypeSpec: return result | 0xDu; case TokenType.Assembly: return result | 0xEu; case TokenType.AssemblyRef: return result | 0xFu; case TokenType.File: return result | 0x10u; case TokenType.ExportedType: return result | 0x11u; case TokenType.ManifestResource: return result | 0x12u; case TokenType.GenericParam: return result | 0x13u; case TokenType.GenericParamConstraint: return result | 0x14u; case TokenType.MethodSpec: return result | 0x15u; } break; case CodedIndex.HasFieldMarshal: result = token.RID << 1; switch (token.TokenType) { case TokenType.Field: return result | 0u; case TokenType.Param: return result | 1u; } break; case CodedIndex.HasDeclSecurity: result = token.RID << 2; switch (token.TokenType) { case TokenType.TypeDef: return result | 0u; case TokenType.Method: return result | 1u; case TokenType.Assembly: return result | 2u; } break; case CodedIndex.MemberRefParent: result = token.RID << 3; switch (token.TokenType) { case TokenType.TypeDef: return result | 0u; case TokenType.TypeRef: return result | 1u; case TokenType.ModuleRef: return result | 2u; case TokenType.Method: return result | 3u; case TokenType.TypeSpec: return result | 4u; } break; case CodedIndex.HasSemantics: result = token.RID << 1; switch (token.TokenType) { case TokenType.Event: return result | 0u; case TokenType.Property: return result | 1u; } break; case CodedIndex.MethodDefOrRef: result = token.RID << 1; switch (token.TokenType) { case TokenType.Method: return result | 0u; case TokenType.MemberRef: return result | 1u; } break; case CodedIndex.MemberForwarded: result = token.RID << 1; switch (token.TokenType) { case TokenType.Field: return result | 0u; case TokenType.Method: return result | 1u; } break; case CodedIndex.Implementation: result = token.RID << 2; switch (token.TokenType) { case TokenType.File: return result | 0u; case TokenType.AssemblyRef: return result | 1u; case TokenType.ExportedType: return result | 2u; } break; case CodedIndex.CustomAttributeType: result = token.RID << 3; switch (token.TokenType) { case TokenType.Method: return result | 2u; case TokenType.MemberRef: return result | 3u; } break; case CodedIndex.ResolutionScope: result = token.RID << 2; switch (token.TokenType) { case TokenType.Module: return result | 0u; case TokenType.ModuleRef: return result | 1u; case TokenType.AssemblyRef: return result | 2u; case TokenType.TypeRef: return result | 3u; } break; case CodedIndex.TypeOrMethodDef: result = token.RID << 1; switch (token.TokenType) { case TokenType.TypeDef: return result | 0u; case TokenType.Method: return result | 1u; } break; case CodedIndex.HasCustomDebugInformation: result = token.RID << 5; switch (token.TokenType) { case TokenType.Method: return result | 0u; case TokenType.Field: return result | 1u; case TokenType.TypeRef: return result | 2u; case TokenType.TypeDef: return result | 3u; case TokenType.Param: return result | 4u; case TokenType.InterfaceImpl: return result | 5u; case TokenType.MemberRef: return result | 6u; case TokenType.Module: return result | 7u; case TokenType.Permission: return result | 8u; case TokenType.Property: return result | 9u; case TokenType.Event: return result | 0xAu; case TokenType.Signature: return result | 0xBu; case TokenType.ModuleRef: return result | 0xCu; case TokenType.TypeSpec: return result | 0xDu; case TokenType.Assembly: return result | 0xEu; case TokenType.AssemblyRef: return result | 0xFu; case TokenType.File: return result | 0x10u; case TokenType.ExportedType: return result | 0x11u; case TokenType.ManifestResource: return result | 0x12u; case TokenType.GenericParam: return result | 0x13u; case TokenType.GenericParamConstraint: return result | 0x14u; case TokenType.MethodSpec: return result | 0x15u; case TokenType.Document: return result | 0x16u; case TokenType.LocalScope: return result | 0x17u; case TokenType.LocalVariable: return result | 0x18u; case TokenType.LocalConstant: return result | 0x19u; case TokenType.ImportScope: return result | 0x1Au; } break; } throw new ArgumentException(); } public static int GetSize(this CodedIndex self, Func<Table, int> counter) { int num; Table[] array; switch (self) { case CodedIndex.TypeDefOrRef: num = 2; array = new Table[3] { Table.TypeDef, Table.TypeRef, Table.TypeSpec }; break; case CodedIndex.HasConstant: num = 2; array = new Table[3] { Table.Field, Table.Param, Table.Property }; break; case CodedIndex.HasCustomAttribute: num = 5; array = new Table[22] { Table.Method, Table.Field, Table.TypeRef, Table.TypeDef, Table.Param, Table.InterfaceImpl, Table.MemberRef, Table.Module, Table.DeclSecurity, Table.Property, Table.Event, Table.StandAloneSig, Table.ModuleRef, Table.TypeSpec, Table.Assembly, Table.AssemblyRef, Table.File, Table.ExportedType, Table.ManifestResource, Table.GenericParam, Table.GenericParamConstraint, Table.MethodSpec }; break; case CodedIndex.HasFieldMarshal: num = 1; array = new Table[2] { Table.Field, Table.Param }; break; case CodedIndex.HasDeclSecurity: num = 2; array = new Table[3] { Table.TypeDef, Table.Method, Table.Assembly }; break; case CodedIndex.MemberRefParent: num = 3; array = new Table[5] { Table.TypeDef, Table.TypeRef, Table.ModuleRef, Table.Method, Table.TypeSpec }; break; case CodedIndex.HasSemantics: num = 1; array = new Table[2] { Table.Event, Table.Property }; break; case CodedIndex.MethodDefOrRef: num = 1; array = new Table[2] { Table.Method, Table.MemberRef }; break; case CodedIndex.MemberForwarded: num = 1; array = new Table[2] { Table.Field, Table.Method }; break; case CodedIndex.Implementation: num = 2; array = new Table[3] { Table.File, Table.AssemblyRef, Table.ExportedType }; break; case CodedIndex.CustomAttributeType: num = 3; array = new Table[2] { Table.Method, Table.MemberRef }; break; case CodedIndex.ResolutionScope: num = 2; array = new Table[4] { Table.Module, Table.ModuleRef, Table.AssemblyRef, Table.TypeRef }; break; case CodedIndex.TypeOrMethodDef: num = 1; array = new Table[2] { Table.TypeDef, Table.Method }; break; case CodedIndex.HasCustomDebugInformation: num = 5; array = new Table[27] { Table.Method, Table.Field, Table.TypeRef, Table.TypeDef, Table.Param, Table.InterfaceImpl, Table.MemberRef, Table.Module, Table.DeclSecurity, Table.Property, Table.Event, Table.StandAloneSig, Table.ModuleRef, Table.TypeSpec, Table.Assembly, Table.AssemblyRef, Table.File, Table.ExportedType, Table.ManifestResource, Table.GenericParam, Table.GenericParamConstraint, Table.MethodSpec, Table.Document, Table.LocalScope, Table.LocalVariable, Table.LocalConstant, Table.ImportScope }; break; default: throw new ArgumentException(); } int num2 = 0; for (int i = 0; i < array.Length; i++) { num2 = Math.Max(counter(array[i]), num2); } return (num2 < 1 << 16 - num) ? 2 : 4; } public static RSA CreateRSA(this WriterParameters writer_parameters) { if (writer_parameters.StrongNameKeyBlob != null) { return CryptoConvert.FromCapiKeyBlob(writer_parameters.StrongNameKeyBlob); } string key_container; byte[] key; if (writer_parameters.StrongNameKeyContainer != null) { key_container = writer_parameters.StrongNameKeyContainer; } else if (!TryGetKeyContainer(writer_parameters.StrongNameKeyPair, out key, out key_container)) { return CryptoConvert.FromCapiKeyBlob(key); } CspParameters parameters = new CspParameters { Flags = CspProviderFlags.UseMachineKeyStore, KeyContainerName = key_container, KeyNumber = 2 }; return new RSACryptoServiceProvider(parameters); } private static bool TryGetKeyContainer(ISerializable key_pair, out byte[] key, out string key_container) { SerializationInfo serializationInfo = new SerializationInfo(typeof(StrongNameKeyPair), new FormatterConverter()); key_pair.GetObjectData(serializationInfo, default(StreamingContext)); key = (byte[])serializationInfo.GetValue("_keyPairArray", typeof(byte[])); key_container = serializationInfo.GetString("_keyPairContainer"); return key_container != null; } } public struct ArrayDimension { private int? lower_bound; private int? upper_bound; public int? LowerBound { get { return lower_bound; } set { lower_bound = value; } } public int? UpperBound { get { return upper_bound; } set { upper_bound = value; } } public bool IsSized => lower_bound.HasValue || upper_bound.HasValue; public ArrayDimension(int? lowerBound, int? upperBound) { lower_bound = lowerBound; upper_bound = upperBound; } public override string ToString() { string result; if (IsSized) { int? num = lower_bound; string? text = num.ToString(); num = upper_bound; result = text + "..." + num; } else { result = string.Empty; } return result; } } public sealed class ArrayType : TypeSpecification { private Collection<ArrayDimension> dimensions; public Collection<ArrayDimension> Dimensions { get { if (dimensions != null) { return dimensions; } Collection<ArrayDimension> collection = new Collection<ArrayDimension>(); collection.Add(default(ArrayDimension)); Interlocked.CompareExchange(ref dimensions, collection, null); return dimensions; } } public int Rank => (dimensions == null) ? 1 : dimensions.Count; public bool IsVector { get { if (dimensions == null) { return true; } if (dimensions.Count > 1) { return false; } return !dimensions[0].IsSized; } } public override bool IsValueType { get { return false; } set { throw new InvalidOperationException(); } } public override string Name => base.Name + Suffix; public override string FullName => base.FullName + Suffix; private string Suffix { get { if (IsVector) { return "[]"; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("["); for (int i = 0; i < dimensions.Count; i++) { if (i > 0) { stringBuilder.Append(","); } stringBuilder.Append(dimensions[i].ToString()); } stringBuilder.Append("]"); return stringBuilder.ToString(); } } public override bool IsArray => true; public ArrayType(TypeReference type) : base(type) { Mixin.CheckType(type); etype = Mono.Cecil.Metadata.ElementType.Array; } public ArrayType(TypeReference type, int rank) : this(type) { Mixin.CheckType(type); if (rank != 1) { dimensions = new Collection<ArrayDimension>(rank); for (int i = 0; i < rank; i++) { dimensions.Add(default(ArrayDimension)); } etype = Mono.Cecil.Metadata.ElementType.Array; } } } public sealed class AssemblyDefinition : ICustomAttributeProvider, IMetadataTokenProvider, ISecurityDeclarationProvider, IDisposable { private AssemblyNameDefinition name; internal ModuleDefinition main_module; private Collection<ModuleDefinition> modules; private Collection<CustomAttribute> custom_attributes; private Collection<SecurityDeclaration> security_declarations; public AssemblyNameDefinition Name { get { return name; } set { name = value; } } public string FullName => (name != null) ? name.FullName : string.Empty; public MetadataToken MetadataToken { get { return new MetadataToken(TokenType.Assembly, 1); } set { } } public Collection<ModuleDefinition> Modules { get { if (modules != null) { return modules; } if (main_module.HasImage) { return main_module.Read(ref modules, this, (AssemblyDefinition _, MetadataReader reader) => reader.ReadModules()); } Interlocked.CompareExchange(ref modules, new Collection<ModuleDefinition>(1) { main_module }, null); return modules; } } public ModuleDefinition MainModule => main_module; public MethodDefinition EntryPoint { get { return main_module.EntryPoint; } set { main_module.EntryPoint = value; } } public bool HasCustomAttributes { get { if (custom_attributes != null) { return custom_attributes.Count > 0; } return this.GetHasCustomAttributes(main_module); } } public Collection<CustomAttribute> CustomAttributes => custom_attributes ?? this.GetCustomAttributes(ref custom_attributes, main_module); public bool HasSecurityDeclarations { get { if (security_declarations != null) { return security_declarations.Count > 0; } return this.GetHasSecurityDeclarations(main_module); } } public Collection<SecurityDeclaration> SecurityDeclarations => security_declarations ?? this.GetSecurityDeclarations(ref security_declarations, main_module); internal AssemblyDefinition() { } public void Dispose() { if (modules == null) { main_module.Dispose(); return; } Collection<ModuleDefinition> collection = Modules; for (int i = 0; i < collection.Count; i++) { collection[i].Dispose(); } } public static AssemblyDefinition CreateAssembly(AssemblyNameDefinition assemblyName, string moduleName, ModuleKind kind) { return CreateAssembly(assemblyName, moduleName, new ModuleParameters { Kind = kind }); } public static AssemblyDefinition CreateAssembly(AssemblyNameDefinition assemblyName, string moduleName, ModuleParameters parameters) { if (assemblyName == null) { throw new ArgumentNullException("assemblyName"); } if (moduleName == null) { throw new ArgumentNullException("moduleName"); } Mixin.CheckParameters(parameters); if (parameters.Kind == ModuleKind.NetModule) { throw new ArgumentException("kind"); } AssemblyDefinition assembly = ModuleDefinition.CreateModule(moduleName, parameters).Assembly; assembly.Name = assemblyName; return assembly; } public static AssemblyDefinition ReadAssembly(string fileName) { return ReadAssembly(ModuleDefinition.ReadModule(fileName)); } public static AssemblyDefinition ReadAssembly(string fileName, ReaderParameters parameters) { return ReadAssembly(ModuleDefinition.ReadModule(fileName, parameters)); } public static AssemblyDefinition ReadAssembly(Stream stream) { return ReadAssembly(ModuleDefinition.ReadModule(stream)); } public static AssemblyDefinition ReadAssembly(Stream stream, ReaderParameters parameters) { return ReadAssembly(ModuleDefinition.ReadModule(stream, parameters)); } private static AssemblyDefinition ReadAssembly(ModuleDefinition module) { AssemblyDefinition assembly = module.Assembly; if (assembly == null) { throw new ArgumentException(); } return assembly; } public void Write(string fileName) { Write(fileName, new WriterParameters()); } public void Write(string fileName, WriterParameters parameters) { main_module.Write(fileName, parameters); } public void Write() { main_module.Write(); } public void Write(WriterParameters parameters) { main_module.Write(parameters); } public void Write(Stream stream) { Write(stream, new WriterParameters()); } public void Write(Stream stream, WriterParameters parameters) { main_module.Write(stream, parameters); } public override string ToString() { return FullName; } } [Flags] public enum AssemblyAttributes : uint { PublicKey = 1u, SideBySideCompatible = 0u, Retargetable = 0x100u, WindowsRuntime = 0x200u, DisableJITCompileOptimizer = 0x4000u, EnableJITCompileTracking = 0x8000u } public enum AssemblyHashAlgorithm : uint { None = 0u, MD5 = 32771u, SHA1 = 32772u, SHA256 = 32780u, SHA384 = 32781u, SHA512 = 32782u, Reserved = 32771u } public sealed class AssemblyLinkedResource : Resource { private AssemblyNameReference reference; public AssemblyNameReference Assembly { get { return reference; } set { reference = value; } } public override ResourceType ResourceType => ResourceType.AssemblyLinked; public AssemblyLinkedResource(string name, ManifestResourceAttributes flags) : base(name, flags) { } public AssemblyLinkedResource(string name, ManifestResourceAttributes flags, AssemblyNameReference reference) : base(name, flags) { this.reference = reference; } } public sealed class AssemblyNameDefinition : AssemblyNameReference { public override byte[] Hash => Empty<byte>.Array; internal AssemblyNameDefinition() { token = new MetadataToken(TokenType.Assembly, 1); } public AssemblyNameDefinition(string name, Version version) : base(name, version) { token = new MetadataToken(TokenType.Assembly, 1); } } public class AssemblyNameReference : IMetadataScope, IMetadataTokenProvider { private string name; private string culture; private Version version; private uint attributes; private byte[] public_key; private byte[] public_key_token; private AssemblyHashAlgorithm hash_algorithm; private byte[] hash; internal MetadataToken token; private string full_name; public string Name { get { return name; } set { name = value; full_name = null; } } public string Culture { get { return culture; } set { culture = value; full_name = null; } } public Version Version { get { return version; } set { version = Mixin.CheckVersion(value); full_name = null; } } public AssemblyAttributes Attributes { get { return (AssemblyAttributes)attributes; } set { attributes = (uint)value; } } public bool HasPublicKey { get { return attributes.GetAttributes(1u); } set { attributes = attributes.SetAttributes(1u, value); } } public bool IsSideBySideCompatible { get { return attributes.GetAttributes(0u); } set { attributes = attributes.SetAttributes(0u, value); } } public bool IsRetargetable { get { return attributes.GetAttributes(256u); } set { attributes = attributes.SetAttributes(256u, value); } } public bool IsWindowsRuntime { get { return attributes.GetAttributes(512u); } set { attributes = attributes.SetAttributes(512u, value); } } public byte[] PublicKey { get { return public_key ?? Empty<byte>.Array; } set { public_key = value; HasPublicKey = !public_key.IsNullOrEmpty(); public_key_token = null; full_name = null; } } public byte[] PublicKeyToken { get { if (public_key_token == null && !public_key.IsNullOrEmpty()) { byte[] array = HashPublicKey(); byte[] array2 = new byte[8]; Array.Copy(array, array.Length - 8, array2, 0, 8); Array.Reverse(array2, 0, 8); Interlocked.CompareExchange(ref public_key_token, array2, null); } return public_key_token ?? Empty<byte>.Array; } set { public_key_token = value; full_name = null; } } public virtual MetadataScopeType MetadataScopeType => MetadataScopeType.AssemblyNameReference; public string FullName { get { if (full_name != null) { return full_name; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(name); stringBuilder.Append(", "); stringBuilder.Append("Version="); stringBuilder.Append(version.ToString(4)); stringBuilder.Append(", "); stringBuilder.Append("Culture="); stringBuilder.Append(string.IsNullOrEmpty(culture) ? "neutral" : culture); stringBuilder.Append(", "); stringBuilder.Append("PublicKeyToken="); byte[] publicKeyToken = PublicKeyToken; if (!publicKeyToken.IsNullOrEmpty() && publicKeyToken.Length != 0) { for (int i = 0; i < publicKeyToken.Length; i++) { stringBuilder.Append(publicKeyToken[i].ToString("x2")); } } else { stringBuilder.Append("null"); } if (IsRetargetable) { stringBuilder.Append(", "); stringBuilder.Append("Retargetable=Yes"); } Interlocked.CompareExchange(ref full_name, stringBuilder.ToString(), null); return full_name; } } public AssemblyHashAlgorithm HashAlgorithm { get { return hash_algorithm; } set { hash_algorithm = value; } } public virtual byte[] Hash { get { return hash; } set { hash = value; } } public MetadataToken MetadataToken { get { return token; } set { token = value; } } private byte[] HashPublicKey() { AssemblyHashAlgorithm assemblyHashAlgorithm = hash_algorithm; AssemblyHashAlgorithm assemblyHashAlgorithm2 = assemblyHashAlgorithm; HashAlgorithm hashAlgorithm = ((assemblyHashAlgorithm2 != AssemblyHashAlgorithm.MD5) ? ((HashAlgorithm)SHA1.Create()) : ((HashAlgorithm)MD5.Create())); using (hashAlgorithm) { return hashAlgorithm.ComputeHash(public_key); } } public static AssemblyNameReference Parse(string fullName) { if (fullName == null) { throw new ArgumentNullException("fullName"); } if (fullName.Length == 0) { throw new ArgumentException("Name can not be empty"); } AssemblyNameReference assemblyNameReference = new AssemblyNameReference(); string[] array = fullName.Split(','); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (i == 0) { assemblyNameReference.Name = text; continue; } string[] array2 = text.Split('='); if (array2.Length != 2) { throw new ArgumentException("Malformed name"); } switch (array2[0].ToLowerInvariant()) { case "version": assemblyNameReference.Version = new Version(array2[1]); break; case "culture": assemblyNameReference.Culture = ((array2[1] == "neutral") ? "" : array2[1]); break; case "publickeytoken": { string text2 = array2[1]; if (!(text2 == "null")) { assemblyNameReference.PublicKeyToken = new byte[text2.Length / 2]; for (int j = 0; j < assemblyNameReference.PublicKeyToken.Length; j++) { assemblyNameReference.PublicKeyToken[j] = byte.Parse(text2.Substring(j * 2, 2), NumberStyles.HexNumber); } } break; } } } return assemblyNameReference; } internal AssemblyNameReference() { version = Mixin.ZeroVersion; token = new MetadataToken(TokenType.AssemblyRef); } public AssemblyNameReference(string name, Version version) { Mixin.CheckName(name); this.name = name; this.version = Mixin.CheckVersion(version); hash_algorithm = AssemblyHashAlgorithm.None; token = new MetadataToken(TokenType.AssemblyRef); } public override string ToString() { return FullName; } } internal abstract class ModuleReader { protected readonly ModuleDefinition module; protected ModuleReader(Image image, ReadingMode mode) { module = new ModuleDefinition(image); module.ReadingMode = mode; } protected abstract void ReadModule(); public abstract void ReadSymbols(ModuleDefinition module); protected void ReadModuleManifest(MetadataReader reader) { reader.Populate(module); ReadAssembly(reader); } private void ReadAssembly(MetadataReader reader) { AssemblyNameDefinition assemblyNameDefinition = reader.ReadAssemblyNameDefinition(); if (assemblyNameDefinition == null) { module.kind = ModuleKind.NetModule; return; } AssemblyDefinition assemblyDefinition = new AssemblyDefinition(); assemblyDefinition.Name = assemblyNameDefinition; module.assembly = assemblyDefinition; assemblyDefinition.main_module = module; } public static ModuleDefinition CreateModule(Image image, ReaderParameters parameters) { ModuleReader moduleReader = CreateModuleReader(image, parameters.ReadingMode); ModuleDefinition moduleDefinition = moduleReader.module; if (parameters.assembly_resolver != null) { moduleDefinition.assembly_resolver = Disposable.NotOwned(parameters.assembly_resolver); } if (parameters.metadata_resolver != null) { moduleDefinition.metadata_resolver = parameters.metadata_resolver; } if (parameters.metadata_importer_provider != null) { moduleDefinition.metadata_importer = parameters.metadata_importer_provider.GetMetadataImporter(moduleDefinition); } if (parameters.reflection_importer_provider != null) { moduleDefinition.reflection_importer = parameters.reflection_importer_provider.GetReflectionImporter(moduleDefinition); } GetMetadataKind(moduleDefinition, parameters); moduleReader.ReadModule(); ReadSymbols(moduleDefinition, parameters); moduleReader.ReadSymbols(moduleDefinition); if (parameters.ReadingMode == ReadingMode.Immediate) { moduleDefinition.MetadataSystem.Clear(); } return moduleDefinition; } private static void ReadSymbols(ModuleDefinition module, ReaderParameters parameters) { ISymbolReaderProvider symbolReaderProvider = parameters.SymbolReaderProvider; if (symbolReaderProvider == null && parameters.ReadSymbols) { symbolReaderProvider = new DefaultSymbolReaderProvider(); } if (symbolReaderProvider != null) { module.SymbolReaderProvider = symbolReaderProvider; ISymbolReader symbolReader = ((parameters.SymbolStream != null) ? symbolReaderProvider.GetSymbolReader(module, parameters.SymbolStream) : symbolReaderProvider.GetSymbolReader(module, module.FileName)); if (symbolReader != null) { try { module.ReadSymbols(symbolReader, parameters.ThrowIfSymbolsAreNotMatching); } catch (Exception) { symbolReader.Dispose(); throw; } } } if (module.Image.HasDebugTables()) { module.ReadSymbols(new PortablePdbReader(module.Image, module)); } } private static void GetMetadataKind(ModuleDefinition module, ReaderParameters parameters) { if (!parameters.ApplyWindowsRuntimeProjections) { module.MetadataKind = MetadataKind.Ecma335; return; } string runtimeVersion = module.RuntimeVersion; if (!runtimeVersion.Contains("WindowsRuntime")) { module.MetadataKind = MetadataKind.Ecma335; } else if (runtimeVersion.Contains("CLR")) { module.MetadataKind = MetadataKind.ManagedWindowsMetadata; } else { module.MetadataKind = MetadataKind.WindowsMetadata; } } private static ModuleReader CreateModuleReader(Image image, ReadingMode mode) { return mode switch { ReadingMode.Immediate => new ImmediateModuleReader(image), ReadingMode.Deferred => new DeferredModuleReader(image), _ => throw new ArgumentException(), }; } } internal sealed class ImmediateModuleReader : ModuleReader { private bool resolve_attributes; public ImmediateModuleReader(Image image) : base(image, ReadingMode.Immediate) { } protected override void ReadModule() { module.Read(module, delegate(ModuleDefinition module, MetadataReader reader) { ReadModuleManifest(reader); ReadModule(module, resolve_attributes: true); }); } public void ReadModule(ModuleDefinition module, bool resolve_attributes) { this.resolve_attributes = resolve_attributes; if (module.HasAssemblyReferences) { Mixin.Read(module.AssemblyReferences); } if (module.HasResources) { Mixin.Read(module.Resources); } if (module.HasModuleReferences) { Mixin.Read(module.ModuleReferences); } if (module.HasTypes) { ReadTypes(module.Types); } if (module.HasExportedTypes) { Mixin.Read(module.ExportedTypes); } ReadCustomAttributes(module); AssemblyDefinition assembly = module.Assembly; if (module.kind != ModuleKind.NetModule && assembly != null) { ReadCustomAttributes(assembly); ReadSecurityDeclarations(assembly); } } private void ReadTypes(Collection<TypeDefinition> types) { for (int i = 0; i < types.Count; i++) { ReadType(types[i]); } } private void ReadType(TypeDefinition type) { ReadGenericParameters(type); if (type.HasInterfaces) { ReadInterfaces(type); } if (type.HasNestedTypes) { ReadTypes(type.NestedTypes); } if (type.HasLayoutInfo) { Mixin.Read(type.ClassSize); } if (type.HasFields) { ReadFields(type); } if (type.HasMethods) { ReadMethods(type); } if (type.HasProperties) { ReadProperties(type); } if (type.HasEvents) { ReadEvents(type); } ReadSecurityDeclarations(type); ReadCustomAttributes(type); } private void ReadInterfaces(TypeDefinition type) { Collection<InterfaceImplementation> interfaces = type.Interfaces; for (int i = 0; i < interfaces.Count; i++) { ReadCustomAttributes(interfaces[i]); } } private void ReadGenericParameters(IGenericParameterProvider provider) { if (!provider.HasGenericParameters) { return; } Collection<GenericParameter> genericParameters = provider.GenericParameters; for (int i = 0; i < genericParameters.Count; i++) { GenericParameter genericParameter = genericParameters[i]; if (genericParameter.HasConstraints) { ReadGenericParameterConstraints(genericParameter); } ReadCustomAttributes(genericParameter); } } private void ReadGenericParameterConstraints(GenericParameter parameter) { Collection<GenericParameterConstraint> constraints = parameter.Constraints; for (int i = 0; i < constraints.Count; i++) { ReadCustomAttributes(constraints[i]); } } private void ReadSecurityDeclarations(ISecurityDeclarationProvider provider) { if (!provider.HasSecurityDeclarations) { return; } Collection<SecurityDeclaration> securityDeclarations = provider.SecurityDeclarations; if (resolve_attributes) { for (int i = 0; i < securityDeclarations.Count; i++) { SecurityDeclaration securityDeclaration = securityDeclarations[i]; Mixin.Read(securityDeclaration.SecurityAttributes); } } } private void ReadCustomAttributes(ICustomAttributeProvider provider) { if (!provider.HasCustomAttributes) { return; } Collection<CustomAttribute> customAttributes = provider.CustomAttributes; if (resolve_attributes) { for (int i = 0; i < customAttributes.Count; i++) { CustomAttribute customAttribute = customAttributes[i]; Mixin.Read(customAttribute.ConstructorArguments); } } } private void ReadFields(TypeDefinition type) { Collection<FieldDefinition> fields = type.Fields; for (int i = 0; i < fields.Count; i++) { FieldDefinition fieldDefinition = fields[i]; if (fieldDefinition.HasConstant) { Mixin.Read(fieldDefinition.Constant); } if (fieldDefinition.HasLayoutInfo) { Mixin.Read(fieldDefinition.Offset); } if (fieldDefinition.RVA > 0) { Mixin.Read(fieldDefinition.InitialValue); } if (fieldDefinition.HasMarshalInfo) { Mixin.Read(fieldDefinition.MarshalInfo); } ReadCustomAttributes(fieldDefinition); } } private void ReadMethods(TypeDefinition type) { Collection<MethodDefinition> methods = type.Methods; for (int i = 0; i < methods.Count; i++) { MethodDefinition methodDefinition = methods[i]; ReadGenericParameters(methodDefinition); if (methodDefinition.HasParameters) { ReadParameters(methodDefinition); } if (methodDefinition.HasOverrides) { Mixin.Read(methodDefinition.Overrides); } if (methodDefinition.IsPInvokeImpl) { Mixin.Read(methodDefinition.PInvokeInfo); } ReadSecurityDeclarations(methodDefinition); ReadCustomAttributes(methodDefinition); MethodReturnType methodReturnType = methodDefinition.MethodReturnType; if (methodReturnType.HasConstant) { Mixin.Read(methodReturnType.Constant); } if (methodReturnType.HasMarshalInfo) { Mixin.Read(methodReturnType.MarshalInfo); } ReadCustomAttributes(methodReturnType); } } private void ReadParameters(MethodDefinition method) { Collection<ParameterDefinition> parameters = method.Parameters; for (int i = 0; i < parameters.Count; i++) { ParameterDefinition parameterDefinition = parameters[i]; if (parameterDefinition.HasConstant) { Mixin.Read(parameterDefinition.Constant); } if (parameterDefinition.HasMarshalInfo) { Mixin.Read(parameterDefinition.MarshalInfo); } ReadCustomAttributes(parameterDefinition); } } private void ReadProperties(TypeDefinition type) { Collection<PropertyDefinition> properties = type.Properties; for (int i = 0; i < properties.Count; i++) { PropertyDefinition propertyDefinition = properties[i]; Mixin.Read(propertyDefinition.GetMethod); if (propertyDefinition.HasConstant) { Mixin.Read(propertyDefinition.Constant); } ReadCustomAttributes(propertyDefinition); } } private void ReadEvents(TypeDefinition type) { Collection<EventDefinition> events = type.Events; for (int i = 0; i < events.Count; i++) { EventDefinition eventDefinition = events[i]; Mixin.Read(eventDefinition.AddMethod); ReadCustomAttributes(eventDefinition); } } public override void ReadSymbols(ModuleDefinition module) { if (module.symbol_reader != null) { ReadTypesSymbols(module.Types, module.symbol_reader); } } private void ReadTypesSymbols(Collection<TypeDefinition> types, ISymbolReader symbol_reader) { for (int i = 0; i < types.Count; i++) { TypeDefinition typeDefinition = types[i]; typeDefinition.custom_infos = symbol_reader.Read(typeDefinition); if (typeDefinition.HasNestedTypes) { ReadTypesSymbols(typeDefinition.NestedTypes, symbol_reader); } if (typeDefinition.HasMethods) { ReadMethodsSymbols(typeDefinition, symbol_reader); } } } private void ReadMethodsSymbols(TypeDefinition type, ISymbolReader symbol_reader) { Collection<MethodDefinition> methods = type.Methods; for (int i = 0; i < methods.Count; i++) { MethodDefinition methodDefinition = methods[i]; if (methodDefinition.HasBody && methodDefinition.token.RID != 0 && methodDefinition.debug_info == null) { methodDefinition.debug_info = symbol_reader.Read(methodDefinition); } } } } internal sealed class DeferredModuleReader : ModuleReader { public DeferredModuleReader(Image image) : base(image, ReadingMode.Deferred) { } protected override void ReadModule() { module.Read(module, delegate(ModuleDefinition _, MetadataReader reader) { ReadModuleManifest(reader); }); } public override void ReadSymbols(ModuleDefinition module) { } } internal sealed class MetadataReader : ByteBuffer { internal readonly Image image; internal readonly ModuleDefinition module; internal readonly MetadataSystem metadata; internal CodeReader code; internal IGenericContext context; private readonly MetadataReader metadata_reader; public MetadataReader(ModuleDefinition module) : base(module.Image.TableHeap.data) { image = module.Image; this.module = module; metadata = module.MetadataSystem; code = new CodeReader(this); } public MetadataReader(Image image, ModuleDefinition module, MetadataReader metadata_reader) : base(image.TableHeap.data) { this.image = image; this.module = module; metadata = module.MetadataSystem; this.metadata_reader = metadata_reader; } private int GetCodedIndexSize(CodedIndex index) { return image.GetCodedIndexSize(index); } private uint ReadByIndexSize(int size) { if (size == 4) { return ReadUInt32(); } return ReadUInt16(); } private byte[] ReadBlob() { BlobHeap blobHeap = image.BlobHeap; if (blobHeap == null) { position += 2; return Empty<byte>.Array; } return blobHeap.Read(ReadBlobIndex()); } private byte[] ReadBlob(uint signature) { BlobHeap blobHeap = image.BlobHeap; if (blobHeap == null) { return Empty<byte>.Array; } return blobHeap.Read(signature); } private uint ReadBlobIndex() { return ReadByIndexSize(image.BlobHeap?.IndexSize ?? 2); } private void GetBlobView(uint signature, out byte[] blob, out int index, out int count) { BlobHeap blobHeap = image.BlobHeap; if (blobHeap == null) { blob = null; index = (count = 0); } else { blobHeap.GetView(signature, out blob, out index, out count); } } private string ReadString() { return image.StringHeap.Read(ReadByIndexSize(image.StringHeap.IndexSize)); } private uint ReadStringIndex() { return ReadByIndexSize(image.StringHeap.IndexSize); } private Guid ReadGuid() { return image.GuidHeap.Read(ReadByIndexSize(image.GuidHeap.IndexSize)); } private uint ReadTableIndex(Table table) { return ReadByIndexSize(image.GetTableIndexSize(table)); } private MetadataToken ReadMetadataToken(CodedIndex index) { return index.GetMetadataToken(ReadByIndexSize(GetCodedIndexSize(index))); } private int MoveTo(Table table) { TableInformation tableInformation = image.TableHeap[table]; if (tableInformation.Length != 0) { position = (int)tableInformation.Offset; } return (int)tableInformation.Length; } private bool MoveTo(Table table, uint row) { TableInformation tableInformation = image.TableHeap[table]; uint num = tableInformation.Length; if (num == 0 || row > num) { return false; } position = (int)(tableInformation.Offset + tableInformation.RowSize * (row - 1)); return true; } public AssemblyNameDefinition ReadAssemblyNameDefinition() { if (MoveTo(Table.Assembly) == 0) { return null; } AssemblyNameDefinition assemblyNameDefinition = new AssemblyNameDefinition(); assemblyNameDefinition.HashAlgorithm = (AssemblyHashAlgorithm)ReadUInt32(); PopulateVersionAndFlags(assemblyNameDefinition); assemblyNameDefinition.PublicKey = ReadBlob(); PopulateNameAndCulture(assemblyNameDefinition); return assemblyNameDefinition; } public ModuleDefinition Populate(ModuleDefinition module) { if (MoveTo(Table.Module) == 0) { return module; } Advance(2); module.Name = ReadString(); module.Mvid = ReadGuid(); return module; } private void InitializeAssemblyReferences() { if (metadata.AssemblyReferences != null) { return; } int num = MoveTo(Table.AssemblyRef); AssemblyNameReference[] array = (metadata.AssemblyReferences = new AssemblyNameReference[num]); for (uint num2 = 0u; num2 < num; num2++) { AssemblyNameReference assemblyNameReference = new AssemblyNameReference(); assemblyNameReference.token = new MetadataToken(TokenType.AssemblyRef, num2 + 1); PopulateVersionAndFlags(assemblyNameReference); byte[] array2 = ReadBlob(); if (assemblyNameReference.HasPublicKey) { assemblyNameReference.PublicKey = array2; } else { assemblyNameReference.PublicKeyToken = array2; } PopulateNameAndCulture(assemblyNameReference); assemblyNameReference.Hash = ReadBlob(); array[num2] = assemblyNameReference; } } public Collection<AssemblyNameReference> ReadAssemblyReferences() { InitializeAssemblyReferences(); Collection<AssemblyNameReference> collection = new Collection<AssemblyNameReference>(metadata.AssemblyReferences); if (module.IsWindowsMetadata()) { module.Projections.AddVirtualReferences(collection); } return collection; } public MethodDefinition ReadEntryPoint() { if (module.Image.EntryPointToken == 0) { return null; } return GetMethodDefinition(new MetadataToken(module.Image.EntryPointToken).RID); } public Collection<ModuleDefinition> ReadModules() { Collection<ModuleDefinition> collection = new Collection<ModuleDefinition>(1); collection.Add(module); int num = MoveTo(Table.File); for (uint num2 = 1u; num2 <= num; num2++) { FileAttributes fileAttributes = (FileAttributes)ReadUInt32(); string name = ReadString(); ReadBlobIndex(); if (fileAttributes == FileAttributes.ContainsMetaData) { ReaderParameters parameters = new ReaderParameters { ReadingMode = module.ReadingMode, SymbolReaderProvider = module.SymbolReaderProvider, AssemblyResolver = module.AssemblyResolver }; ModuleDefinition moduleDefinition = ModuleDefinition.ReadModule(GetModuleFileName(name), parameters); moduleDefinition.assembly = module.assembly; collection.Add(moduleDefinition); } } return collection; } private string GetModuleFileName(string name) { if (module.FileName == null) { throw new NotSupportedException(); } string directoryName = Path.GetDirectoryName(module.FileName); return Path.Combine(directoryName, name); } private void InitializeModuleReferences() { if (metadata.ModuleReferences == null) { int num = MoveTo(Table.ModuleRef); ModuleReference[] array = (metadata.ModuleReferences = new ModuleReference[num]); for (uint num2 = 0u; num2 < num; num2++) { ModuleReference moduleReference = new ModuleReference(ReadString()); moduleReference.token = new MetadataToken(TokenType.ModuleRef, num2 + 1); array[num2] = moduleReference; } } } public Collection<ModuleReference> ReadModuleReferences() { InitializeModuleReferences(); return new Collection<ModuleReference>(metadata.ModuleReferences); } public bool HasFileResource() { int num = MoveTo(Table.File); if (num == 0) { return false; } for (uint num2 = 1u; num2 <= num; num2++) { if (ReadFileRecord(num2).Col1 == FileAttributes.ContainsNoMetaData) { return true; } } return false; } public Collection<Resource> ReadResources() { int num = MoveTo(Table.ManifestResource); Collection<Resource> collection = new Collection<Resource>(num); for (int i = 1; i <= num; i++) { uint offset = ReadUInt32(); ManifestResourceAttributes manifestResourceAttributes = (ManifestResourceAttributes)ReadUInt32(); string name = ReadString(); MetadataToken scope = ReadMetadataToken(CodedIndex.Implementation); Resource item; if (scope.RID == 0) { item = new EmbeddedResource(name, manifestResourceAttributes, offset, this); } else if (scope.TokenType == TokenType.AssemblyRef) { item = new AssemblyLinkedResource(name, manifestResourceAttributes) { Assembly = (AssemblyNameReference)GetTypeReferenceScope(scope) }; } else { if (scope.TokenType != TokenType.File) { continue; } Row<FileAttributes, string, uint> row = ReadFileRecord(scope.RID); item = new LinkedResource(name, manifestResourceAttributes) { File = row.Col2, hash = ReadBlob(row.Col3) }; } collection.Add(item); } return collection; } private Row<FileAttributes, string, uint> ReadFileRecord(uint rid) { int num = position; if (!MoveTo(Table.File, rid)) { throw new ArgumentException(); } Row<FileAttributes, string, uint> result = new Row<FileAttributes, string, uint>((FileAttributes)ReadUInt32(), ReadString(), ReadBlobIndex()); position = num; return result; } public byte[] GetManagedResource(uint offset) { return image.GetReaderAt(image.Resources.VirtualAddress, offset, delegate(uint o, BinaryStreamReader reader) { reader.Advance((int)o); return reader.ReadBytes(reader.ReadInt32()); }) ?? Empty<byte>.Array; } private void PopulateVersionAndFlags(AssemblyNameReference name) { name.Version = new Version(ReadUInt16(), ReadUInt16(), ReadUInt16(), ReadUInt16()); name.Attributes = (AssemblyAttributes)ReadUInt32(); } private void PopulateNameAndCulture(AssemblyNameReference name) { name.Name = ReadString(); name.Culture = ReadString(); } public TypeDefinitionCollection ReadTypes() { InitializeTypeDefinitions(); TypeDefinition[] types = metadata.Types; int capacity = types.Length - metadata.NestedTypes.Count; TypeDefinitionCollection typeDefinitionCollection = new TypeDefinitionCollection(module, capacity); foreach (TypeDefinition typeDefinition in types) { if (!IsNested(typeDefinition.Attributes)) { typeDefinitionCollection.Add(typeDefinition); } } if (image.HasTable(Table.MethodPtr) || image.HasTable(Table.FieldPtr)) { CompleteTypes(); } return typeDefinitionCollection; } private void CompleteTypes() { TypeDefinition[] types = metadata.Types; foreach (TypeDefinition typeDefinition in types) { Mixin.Read(typeDefinition.Fields); Mixin.Read(typeDefinition.Methods); } } private void InitializeTypeDefinitions() { if (metadata.Types != null) { return; } InitializeNestedTypes(); InitializeFields(); InitializeMethods(); int num = MoveTo(Table.TypeDef); TypeDefinition[] array = (metadata.Types = new TypeDefinition[num]); for (uint num2 = 0u; num2 < num; num2++) { if (array[num2] == null) { array[num2] = ReadType(num2 + 1); } } if (module.IsWindowsMetadata()) { for (uint num3 = 0u; num3 < num; num3++) { WindowsRuntimeProjections.Project(array[num3]); } } } private static bool IsNested(TypeAttributes attributes) { TypeAttributes typeAttributes = attributes & TypeAttributes.VisibilityMask; TypeAttributes typeAttributes2 = typeAttributes; if (typeAttributes2 - 2 <= TypeAttributes.NestedAssembly) { return true; } return false; } public bool HasNestedTypes(TypeDefinition type) { InitializeNestedTypes(); if (!metadata.TryGetNestedTypeMapping(type, out var mapping)) { return false; } return mapping.Count > 0; } public Collection<TypeDefinition> ReadNestedTypes(TypeDefinition type) { InitializeNestedTypes(); if (!metadata.TryGetNestedTypeMapping(type, out var mapping)) { return new MemberDefinitionCollection<TypeDefinition>(type); } MemberDefinitionCollection<TypeDefinition> memberDefinitionCollection = new MemberDefinitionCollection<TypeDefinition>(type, mapping.Count); for (int i = 0; i < mapping.Count; i++) { TypeDefinition typeDefinition = GetTypeDefinition(mapping[i]); if (typeDefinition != null) { memberDef
BepInEx/core/Mono.Cecil.Mdb.dll
Decompiled a week agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.SymbolStore; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using Microsoft.CodeAnalysis; using Mono.Cecil.Cil; using Mono.Collections.Generic; using Mono.CompilerServices.SymbolWriter; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyProduct("Mono.Cecil")] [assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")] [assembly: ComVisible(false)] [assembly: AssemblyFileVersion("0.11.6.0")] [assembly: AssemblyInformationalVersion("0.11.6.0")] [assembly: AssemblyTitle("Mono.Cecil.Mdb")] [assembly: CLSCompliant(false)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyVersion("0.11.6.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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Mono.CompilerServices.SymbolWriter { public class MonoSymbolFileException : Exception { public MonoSymbolFileException() { } public MonoSymbolFileException(string message, params object[] args) : base(string.Format(message, args)) { } public MonoSymbolFileException(string message, Exception innerException) : base(message, innerException) { } } internal sealed class MyBinaryWriter : BinaryWriter { public MyBinaryWriter(Stream stream) : base(stream) { } public void WriteLeb128(int value) { Write7BitEncodedInt(value); } } internal class MyBinaryReader : BinaryReader { public MyBinaryReader(Stream stream) : base(stream) { } public int ReadLeb128() { return Read7BitEncodedInt(); } public string ReadString(int offset) { long position = BaseStream.Position; BaseStream.Position = offset; string result = ReadString(); BaseStream.Position = position; return result; } } public interface ISourceFile { SourceFileEntry Entry { get; } } public interface ICompileUnit { CompileUnitEntry Entry { get; } } public interface IMethodDef { string Name { get; } int Token { get; } } public class MonoSymbolFile : IDisposable { private List<MethodEntry> methods = new List<MethodEntry>(); private List<SourceFileEntry> sources = new List<SourceFileEntry>(); private List<CompileUnitEntry> comp_units = new List<CompileUnitEntry>(); private Dictionary<int, AnonymousScopeEntry> anonymous_scopes; private OffsetTable ot; private int last_type_index; private int last_method_index; private int last_namespace_index; public readonly int MajorVersion = 50; public readonly int MinorVersion = 0; public int NumLineNumbers; private MyBinaryReader reader; private Dictionary<int, SourceFileEntry> source_file_hash; private Dictionary<int, CompileUnitEntry> compile_unit_hash; private List<MethodEntry> method_list; private Dictionary<int, MethodEntry> method_token_hash; private Dictionary<string, int> source_name_hash; private Guid guid; internal int LineNumberCount = 0; internal int LocalCount = 0; internal int StringSize = 0; internal int LineNumberSize = 0; internal int ExtendedLineNumberSize = 0; public int CompileUnitCount => ot.CompileUnitCount; public int SourceCount => ot.SourceCount; public int MethodCount => ot.MethodCount; public int TypeCount => ot.TypeCount; public int AnonymousScopeCount => ot.AnonymousScopeCount; public int NamespaceCount => last_namespace_index; public Guid Guid => guid; public OffsetTable OffsetTable => ot; public SourceFileEntry[] Sources { get { if (reader == null) { throw new InvalidOperationException(); } SourceFileEntry[] array = new SourceFileEntry[SourceCount]; for (int i = 0; i < SourceCount; i++) { array[i] = GetSourceFile(i + 1); } return array; } } public CompileUnitEntry[] CompileUnits { get { if (reader == null) { throw new InvalidOperationException(); } CompileUnitEntry[] array = new CompileUnitEntry[CompileUnitCount]; for (int i = 0; i < CompileUnitCount; i++) { array[i] = GetCompileUnit(i + 1); } return array; } } public MethodEntry[] Methods { get { if (reader == null) { throw new InvalidOperationException(); } lock (this) { read_methods(); MethodEntry[] array = new MethodEntry[MethodCount]; method_list.CopyTo(array, 0); return array; } } } internal MyBinaryReader BinaryReader { get { if (reader == null) { throw new InvalidOperationException(); } return reader; } } public MonoSymbolFile() { ot = new OffsetTable(); } public int AddSource(SourceFileEntry source) { sources.Add(source); return sources.Count; } public int AddCompileUnit(CompileUnitEntry entry) { comp_units.Add(entry); return comp_units.Count; } public void AddMethod(MethodEntry entry) { methods.Add(entry); } public MethodEntry DefineMethod(CompileUnitEntry comp_unit, int token, ScopeVariable[] scope_vars, LocalVariableEntry[] locals, LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, string real_name, MethodEntry.Flags flags, int namespace_id) { if (reader != null) { throw new InvalidOperationException(); } MethodEntry methodEntry = new MethodEntry(this, comp_unit, token, scope_vars, locals, lines, code_blocks, real_name, flags, namespace_id); AddMethod(methodEntry); return methodEntry; } internal void DefineAnonymousScope(int id) { if (reader != null) { throw new InvalidOperationException(); } if (anonymous_scopes == null) { anonymous_scopes = new Dictionary<int, AnonymousScopeEntry>(); } anonymous_scopes.Add(id, new AnonymousScopeEntry(id)); } internal void DefineCapturedVariable(int scope_id, string name, string captured_name, CapturedVariable.CapturedKind kind) { if (reader != null) { throw new InvalidOperationException(); } AnonymousScopeEntry anonymousScopeEntry = anonymous_scopes[scope_id]; anonymousScopeEntry.AddCapturedVariable(name, captured_name, kind); } internal void DefineCapturedScope(int scope_id, int id, string captured_name) { if (reader != null) { throw new InvalidOperationException(); } AnonymousScopeEntry anonymousScopeEntry = anonymous_scopes[scope_id]; anonymousScopeEntry.AddCapturedScope(id, captured_name); } internal int GetNextTypeIndex() { return ++last_type_index; } internal int GetNextMethodIndex() { return ++last_method_index; } internal int GetNextNamespaceIndex() { return ++last_namespace_index; } private void Write(MyBinaryWriter bw, Guid guid) { bw.Write(5037318119232611860L); bw.Write(MajorVersion); bw.Write(MinorVersion); bw.Write(guid.ToByteArray()); long position = bw.BaseStream.Position; ot.Write(bw, MajorVersion, MinorVersion); methods.Sort(); for (int i = 0; i < methods.Count; i++) { methods[i].Index = i + 1; } ot.DataSectionOffset = (int)bw.BaseStream.Position; foreach (SourceFileEntry source in sources) { source.WriteData(bw); } foreach (CompileUnitEntry comp_unit in comp_units) { comp_unit.WriteData(bw); } foreach (MethodEntry method in methods) { method.WriteData(this, bw); } ot.DataSectionSize = (int)bw.BaseStream.Position - ot.DataSectionOffset; ot.MethodTableOffset = (int)bw.BaseStream.Position; for (int j = 0; j < methods.Count; j++) { MethodEntry methodEntry = methods[j]; methodEntry.Write(bw); } ot.MethodTableSize = (int)bw.BaseStream.Position - ot.MethodTableOffset; ot.SourceTableOffset = (int)bw.BaseStream.Position; for (int k = 0; k < sources.Count; k++) { SourceFileEntry sourceFileEntry = sources[k]; sourceFileEntry.Write(bw); } ot.SourceTableSize = (int)bw.BaseStream.Position - ot.SourceTableOffset; ot.CompileUnitTableOffset = (int)bw.BaseStream.Position; for (int l = 0; l < comp_units.Count; l++) { CompileUnitEntry compileUnitEntry = comp_units[l]; compileUnitEntry.Write(bw); } ot.CompileUnitTableSize = (int)bw.BaseStream.Position - ot.CompileUnitTableOffset; ot.AnonymousScopeCount = ((anonymous_scopes != null) ? anonymous_scopes.Count : 0); ot.AnonymousScopeTableOffset = (int)bw.BaseStream.Position; if (anonymous_scopes != null) { foreach (AnonymousScopeEntry value in anonymous_scopes.Values) { value.Write(bw); } } ot.AnonymousScopeTableSize = (int)bw.BaseStream.Position - ot.AnonymousScopeTableOffset; ot.TypeCount = last_type_index; ot.MethodCount = methods.Count; ot.SourceCount = sources.Count; ot.CompileUnitCount = comp_units.Count; ot.TotalFileSize = (int)bw.BaseStream.Position; bw.Seek((int)position, SeekOrigin.Begin); ot.Write(bw, MajorVersion, MinorVersion); bw.Seek(0, SeekOrigin.End); } public void CreateSymbolFile(Guid guid, FileStream fs) { if (reader != null) { throw new InvalidOperationException(); } Write(new MyBinaryWriter(fs), guid); } private MonoSymbolFile(Stream stream) { reader = new MyBinaryReader(stream); try { long num = reader.ReadInt64(); int num2 = reader.ReadInt32(); int num3 = reader.ReadInt32(); if (num != 5037318119232611860L) { throw new MonoSymbolFileException("Symbol file is not a valid"); } if (num2 != 50) { throw new MonoSymbolFileException("Symbol file has version {0} but expected {1}", num2, 50); } if (num3 != 0) { throw new MonoSymbolFileException("Symbol file has version {0}.{1} but expected {2}.{3}", num2, num3, 50, 0); } MajorVersion = num2; MinorVersion = num3; guid = new Guid(reader.ReadBytes(16)); ot = new OffsetTable(reader, num2, num3); } catch (Exception innerException) { throw new MonoSymbolFileException("Cannot read symbol file", innerException); } source_file_hash = new Dictionary<int, SourceFileEntry>(); compile_unit_hash = new Dictionary<int, CompileUnitEntry>(); } public static MonoSymbolFile ReadSymbolFile(Assembly assembly) { string location = assembly.Location; string mdbFilename = location + ".mdb"; Module[] modules = assembly.GetModules(); Guid moduleVersionId = modules[0].ModuleVersionId; return ReadSymbolFile(mdbFilename, moduleVersionId); } public static MonoSymbolFile ReadSymbolFile(string mdbFilename) { return ReadSymbolFile(new FileStream(mdbFilename, FileMode.Open, FileAccess.Read)); } public static MonoSymbolFile ReadSymbolFile(string mdbFilename, Guid assemblyGuid) { MonoSymbolFile monoSymbolFile = ReadSymbolFile(mdbFilename); if (assemblyGuid != monoSymbolFile.guid) { throw new MonoSymbolFileException("Symbol file `{0}' does not match assembly", mdbFilename); } return monoSymbolFile; } public static MonoSymbolFile ReadSymbolFile(Stream stream) { return new MonoSymbolFile(stream); } public SourceFileEntry GetSourceFile(int index) { if (index < 1 || index > ot.SourceCount) { throw new ArgumentException(); } if (reader == null) { throw new InvalidOperationException(); } lock (this) { if (source_file_hash.TryGetValue(index, out var value)) { return value; } long position = reader.BaseStream.Position; reader.BaseStream.Position = ot.SourceTableOffset + SourceFileEntry.Size * (index - 1); value = new SourceFileEntry(this, reader); source_file_hash.Add(index, value); reader.BaseStream.Position = position; return value; } } public CompileUnitEntry GetCompileUnit(int index) { if (index < 1 || index > ot.CompileUnitCount) { throw new ArgumentException(); } if (reader == null) { throw new InvalidOperationException(); } lock (this) { if (compile_unit_hash.TryGetValue(index, out var value)) { return value; } long position = reader.BaseStream.Position; reader.BaseStream.Position = ot.CompileUnitTableOffset + CompileUnitEntry.Size * (index - 1); value = new CompileUnitEntry(this, reader); compile_unit_hash.Add(index, value); reader.BaseStream.Position = position; return value; } } private void read_methods() { lock (this) { if (method_token_hash == null) { method_token_hash = new Dictionary<int, MethodEntry>(); method_list = new List<MethodEntry>(); long position = reader.BaseStream.Position; reader.BaseStream.Position = ot.MethodTableOffset; for (int i = 0; i < MethodCount; i++) { MethodEntry methodEntry = new MethodEntry(this, reader, i + 1); method_token_hash.Add(methodEntry.Token, methodEntry); method_list.Add(methodEntry); } reader.BaseStream.Position = position; } } } public MethodEntry GetMethodByToken(int token) { if (reader == null) { throw new InvalidOperationException(); } lock (this) { read_methods(); method_token_hash.TryGetValue(token, out var value); return value; } } public MethodEntry GetMethod(int index) { if (index < 1 || index > ot.MethodCount) { throw new ArgumentException(); } if (reader == null) { throw new InvalidOperationException(); } lock (this) { read_methods(); return method_list[index - 1]; } } public int FindSource(string file_name) { if (reader == null) { throw new InvalidOperationException(); } lock (this) { if (source_name_hash == null) { source_name_hash = new Dictionary<string, int>(); for (int i = 0; i < ot.SourceCount; i++) { SourceFileEntry sourceFile = GetSourceFile(i + 1); source_name_hash.Add(sourceFile.FileName, i); } } if (!source_name_hash.TryGetValue(file_name, out var value)) { return -1; } return value; } } public AnonymousScopeEntry GetAnonymousScope(int id) { if (reader == null) { throw new InvalidOperationException(); } lock (this) { if (anonymous_scopes != null) { anonymous_scopes.TryGetValue(id, out var value); return value; } anonymous_scopes = new Dictionary<int, AnonymousScopeEntry>(); reader.BaseStream.Position = ot.AnonymousScopeTableOffset; for (int i = 0; i < ot.AnonymousScopeCount; i++) { AnonymousScopeEntry value = new AnonymousScopeEntry(reader); anonymous_scopes.Add(value.ID, value); } return anonymous_scopes[id]; } } public void Dispose() { Dispose(disposing: true); } protected virtual void Dispose(bool disposing) { if (disposing && reader != null) { reader.Close(); reader = null; } } } public class OffsetTable { [Flags] public enum Flags { IsAspxSource = 1, WindowsFileNames = 2 } public const int MajorVersion = 50; public const int MinorVersion = 0; public const long Magic = 5037318119232611860L; public int TotalFileSize; public int DataSectionOffset; public int DataSectionSize; public int CompileUnitCount; public int CompileUnitTableOffset; public int CompileUnitTableSize; public int SourceCount; public int SourceTableOffset; public int SourceTableSize; public int MethodCount; public int MethodTableOffset; public int MethodTableSize; public int TypeCount; public int AnonymousScopeCount; public int AnonymousScopeTableOffset; public int AnonymousScopeTableSize; public Flags FileFlags; public int LineNumberTable_LineBase = -1; public int LineNumberTable_LineRange = 8; public int LineNumberTable_OpcodeBase = 9; internal OffsetTable() { int platform = (int)Environment.OSVersion.Platform; if (platform != 4 && platform != 128) { FileFlags |= Flags.WindowsFileNames; } } internal OffsetTable(BinaryReader reader, int major_version, int minor_version) { TotalFileSize = reader.ReadInt32(); DataSectionOffset = reader.ReadInt32(); DataSectionSize = reader.ReadInt32(); CompileUnitCount = reader.ReadInt32(); CompileUnitTableOffset = reader.ReadInt32(); CompileUnitTableSize = reader.ReadInt32(); SourceCount = reader.ReadInt32(); SourceTableOffset = reader.ReadInt32(); SourceTableSize = reader.ReadInt32(); MethodCount = reader.ReadInt32(); MethodTableOffset = reader.ReadInt32(); MethodTableSize = reader.ReadInt32(); TypeCount = reader.ReadInt32(); AnonymousScopeCount = reader.ReadInt32(); AnonymousScopeTableOffset = reader.ReadInt32(); AnonymousScopeTableSize = reader.ReadInt32(); LineNumberTable_LineBase = reader.ReadInt32(); LineNumberTable_LineRange = reader.ReadInt32(); LineNumberTable_OpcodeBase = reader.ReadInt32(); FileFlags = (Flags)reader.ReadInt32(); } internal void Write(BinaryWriter bw, int major_version, int minor_version) { bw.Write(TotalFileSize); bw.Write(DataSectionOffset); bw.Write(DataSectionSize); bw.Write(CompileUnitCount); bw.Write(CompileUnitTableOffset); bw.Write(CompileUnitTableSize); bw.Write(SourceCount); bw.Write(SourceTableOffset); bw.Write(SourceTableSize); bw.Write(MethodCount); bw.Write(MethodTableOffset); bw.Write(MethodTableSize); bw.Write(TypeCount); bw.Write(AnonymousScopeCount); bw.Write(AnonymousScopeTableOffset); bw.Write(AnonymousScopeTableSize); bw.Write(LineNumberTable_LineBase); bw.Write(LineNumberTable_LineRange); bw.Write(LineNumberTable_OpcodeBase); bw.Write((int)FileFlags); } public override string ToString() { return $"OffsetTable [{TotalFileSize} - {DataSectionOffset}:{DataSectionSize} - {SourceCount}:{SourceTableOffset}:{SourceTableSize} - {MethodCount}:{MethodTableOffset}:{MethodTableSize} - {TypeCount}]"; } } public class LineNumberEntry { public sealed class LocationComparer : IComparer<LineNumberEntry> { public static readonly LocationComparer Default = new LocationComparer(); public int Compare(LineNumberEntry l1, LineNumberEntry l2) { return (l1.Row == l2.Row) ? l1.Column.CompareTo(l2.Column) : l1.Row.CompareTo(l2.Row); } } public readonly int Row; public int Column; public int EndRow; public int EndColumn; public readonly int File; public readonly int Offset; public readonly bool IsHidden; public static readonly LineNumberEntry Null = new LineNumberEntry(0, 0, 0, 0); public LineNumberEntry(int file, int row, int column, int offset) : this(file, row, column, offset, is_hidden: false) { } public LineNumberEntry(int file, int row, int offset) : this(file, row, -1, offset, is_hidden: false) { } public LineNumberEntry(int file, int row, int column, int offset, bool is_hidden) : this(file, row, column, -1, -1, offset, is_hidden) { } public LineNumberEntry(int file, int row, int column, int end_row, int end_column, int offset, bool is_hidden) { File = file; Row = row; Column = column; EndRow = end_row; EndColumn = end_column; Offset = offset; IsHidden = is_hidden; } public override string ToString() { return $"[Line {File}:{Row},{Column}-{EndRow},{EndColumn}:{Offset}]"; } } public class CodeBlockEntry { public enum Type { Lexical = 1, CompilerGenerated, IteratorBody, IteratorDispatcher } public int Index; public int Parent; public Type BlockType; public int StartOffset; public int EndOffset; public CodeBlockEntry(int index, int parent, Type type, int start_offset) { Index = index; Parent = parent; BlockType = type; StartOffset = start_offset; } internal CodeBlockEntry(int index, MyBinaryReader reader) { Index = index; int num = reader.ReadLeb128(); BlockType = (Type)(num & 0x3F); Parent = reader.ReadLeb128(); StartOffset = reader.ReadLeb128(); EndOffset = reader.ReadLeb128(); if (((uint)num & 0x40u) != 0) { int num2 = reader.ReadInt16(); reader.BaseStream.Position += num2; } } public void Close(int end_offset) { EndOffset = end_offset; } internal void Write(MyBinaryWriter bw) { bw.WriteLeb128((int)BlockType); bw.WriteLeb128(Parent); bw.WriteLeb128(StartOffset); bw.WriteLeb128(EndOffset); } public override string ToString() { return $"[CodeBlock {Index}:{Parent}:{BlockType}:{StartOffset}:{EndOffset}]"; } } public struct LocalVariableEntry { public readonly int Index; public readonly string Name; public readonly int BlockIndex; public LocalVariableEntry(int index, string name, int block) { Index = index; Name = name; BlockIndex = block; } internal LocalVariableEntry(MonoSymbolFile file, MyBinaryReader reader) { Index = reader.ReadLeb128(); Name = reader.ReadString(); BlockIndex = reader.ReadLeb128(); } internal void Write(MonoSymbolFile file, MyBinaryWriter bw) { bw.WriteLeb128(Index); bw.Write(Name); bw.WriteLeb128(BlockIndex); } public override string ToString() { return $"[LocalVariable {Name}:{Index}:{BlockIndex - 1}]"; } } public struct CapturedVariable { public enum CapturedKind : byte { Local, Parameter, This } public readonly string Name; public readonly string CapturedName; public readonly CapturedKind Kind; public CapturedVariable(string name, string captured_name, CapturedKind kind) { Name = name; CapturedName = captured_name; Kind = kind; } internal CapturedVariable(MyBinaryReader reader) { Name = reader.ReadString(); CapturedName = reader.ReadString(); Kind = (CapturedKind)reader.ReadByte(); } internal void Write(MyBinaryWriter bw) { bw.Write(Name); bw.Write(CapturedName); bw.Write((byte)Kind); } public override string ToString() { return $"[CapturedVariable {Name}:{CapturedName}:{Kind}]"; } } public struct CapturedScope { public readonly int Scope; public readonly string CapturedName; public CapturedScope(int scope, string captured_name) { Scope = scope; CapturedName = captured_name; } internal CapturedScope(MyBinaryReader reader) { Scope = reader.ReadLeb128(); CapturedName = reader.ReadString(); } internal void Write(MyBinaryWriter bw) { bw.WriteLeb128(Scope); bw.Write(CapturedName); } public override string ToString() { return $"[CapturedScope {Scope}:{CapturedName}]"; } } public struct ScopeVariable { public readonly int Scope; public readonly int Index; public ScopeVariable(int scope, int index) { Scope = scope; Index = index; } internal ScopeVariable(MyBinaryReader reader) { Scope = reader.ReadLeb128(); Index = reader.ReadLeb128(); } internal void Write(MyBinaryWriter bw) { bw.WriteLeb128(Scope); bw.WriteLeb128(Index); } public override string ToString() { return $"[ScopeVariable {Scope}:{Index}]"; } } public class AnonymousScopeEntry { public readonly int ID; private List<CapturedVariable> captured_vars = new List<CapturedVariable>(); private List<CapturedScope> captured_scopes = new List<CapturedScope>(); public CapturedVariable[] CapturedVariables { get { CapturedVariable[] array = new CapturedVariable[captured_vars.Count]; captured_vars.CopyTo(array, 0); return array; } } public CapturedScope[] CapturedScopes { get { CapturedScope[] array = new CapturedScope[captured_scopes.Count]; captured_scopes.CopyTo(array, 0); return array; } } public AnonymousScopeEntry(int id) { ID = id; } internal AnonymousScopeEntry(MyBinaryReader reader) { ID = reader.ReadLeb128(); int num = reader.ReadLeb128(); for (int i = 0; i < num; i++) { captured_vars.Add(new CapturedVariable(reader)); } int num2 = reader.ReadLeb128(); for (int j = 0; j < num2; j++) { captured_scopes.Add(new CapturedScope(reader)); } } internal void AddCapturedVariable(string name, string captured_name, CapturedVariable.CapturedKind kind) { captured_vars.Add(new CapturedVariable(name, captured_name, kind)); } internal void AddCapturedScope(int scope, string captured_name) { captured_scopes.Add(new CapturedScope(scope, captured_name)); } internal void Write(MyBinaryWriter bw) { bw.WriteLeb128(ID); bw.WriteLeb128(captured_vars.Count); foreach (CapturedVariable captured_var in captured_vars) { captured_var.Write(bw); } bw.WriteLeb128(captured_scopes.Count); foreach (CapturedScope captured_scope in captured_scopes) { captured_scope.Write(bw); } } public override string ToString() { return $"[AnonymousScope {ID}]"; } } public class CompileUnitEntry : ICompileUnit { public readonly int Index; private int DataOffset; private MonoSymbolFile file; private SourceFileEntry source; private List<SourceFileEntry> include_files; private List<NamespaceEntry> namespaces; private bool creating; public static int Size => 8; CompileUnitEntry ICompileUnit.Entry => this; public SourceFileEntry SourceFile { get { if (creating) { return source; } ReadData(); return source; } } public NamespaceEntry[] Namespaces { get { ReadData(); NamespaceEntry[] array = new NamespaceEntry[namespaces.Count]; namespaces.CopyTo(array, 0); return array; } } public SourceFileEntry[] IncludeFiles { get { ReadData(); if (include_files == null) { return new SourceFileEntry[0]; } SourceFileEntry[] array = new SourceFileEntry[include_files.Count]; include_files.CopyTo(array, 0); return array; } } public CompileUnitEntry(MonoSymbolFile file, SourceFileEntry source) { this.file = file; this.source = source; Index = file.AddCompileUnit(this); creating = true; namespaces = new List<NamespaceEntry>(); } public void AddFile(SourceFileEntry file) { if (!creating) { throw new InvalidOperationException(); } if (include_files == null) { include_files = new List<SourceFileEntry>(); } include_files.Add(file); } public int DefineNamespace(string name, string[] using_clauses, int parent) { if (!creating) { throw new InvalidOperationException(); } int nextNamespaceIndex = file.GetNextNamespaceIndex(); NamespaceEntry item = new NamespaceEntry(name, nextNamespaceIndex, using_clauses, parent); namespaces.Add(item); return nextNamespaceIndex; } internal void WriteData(MyBinaryWriter bw) { DataOffset = (int)bw.BaseStream.Position; bw.WriteLeb128(source.Index); int value = ((include_files != null) ? include_files.Count : 0); bw.WriteLeb128(value); if (include_files != null) { foreach (SourceFileEntry include_file in include_files) { bw.WriteLeb128(include_file.Index); } } bw.WriteLeb128(namespaces.Count); foreach (NamespaceEntry @namespace in namespaces) { @namespace.Write(file, bw); } } internal void Write(BinaryWriter bw) { bw.Write(Index); bw.Write(DataOffset); } internal CompileUnitEntry(MonoSymbolFile file, MyBinaryReader reader) { this.file = file; Index = reader.ReadInt32(); DataOffset = reader.ReadInt32(); } public void ReadAll() { ReadData(); } private void ReadData() { if (creating) { throw new InvalidOperationException(); } lock (file) { if (namespaces != null) { return; } MyBinaryReader binaryReader = file.BinaryReader; int num = (int)binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = DataOffset; int index = binaryReader.ReadLeb128(); source = file.GetSourceFile(index); int num2 = binaryReader.ReadLeb128(); if (num2 > 0) { include_files = new List<SourceFileEntry>(); for (int i = 0; i < num2; i++) { include_files.Add(file.GetSourceFile(binaryReader.ReadLeb128())); } } int num3 = binaryReader.ReadLeb128(); namespaces = new List<NamespaceEntry>(); for (int j = 0; j < num3; j++) { namespaces.Add(new NamespaceEntry(file, binaryReader)); } binaryReader.BaseStream.Position = num; } } } public class SourceFileEntry { public readonly int Index; private int DataOffset; private MonoSymbolFile file; private string file_name; private byte[] guid; private byte[] hash; private bool creating; private bool auto_generated; private readonly string sourceFile; public static int Size => 8; public byte[] Checksum => hash; public string FileName { get { return file_name; } set { file_name = value; } } public bool AutoGenerated => auto_generated; public SourceFileEntry(MonoSymbolFile file, string file_name) { this.file = file; this.file_name = file_name; Index = file.AddSource(this); creating = true; } public SourceFileEntry(MonoSymbolFile file, string sourceFile, byte[] guid, byte[] checksum) : this(file, sourceFile, sourceFile, guid, checksum) { } public SourceFileEntry(MonoSymbolFile file, string fileName, string sourceFile, byte[] guid, byte[] checksum) : this(file, fileName) { this.guid = guid; hash = checksum; this.sourceFile = sourceFile; } internal void WriteData(MyBinaryWriter bw) { DataOffset = (int)bw.BaseStream.Position; bw.Write(file_name); if (guid == null) { guid = new byte[16]; } if (hash == null) { try { using FileStream inputStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read); MD5 mD = MD5.Create(); hash = mD.ComputeHash(inputStream); } catch { hash = new byte[16]; } } bw.Write(guid); bw.Write(hash); bw.Write((byte)(auto_generated ? 1u : 0u)); } internal void Write(BinaryWriter bw) { bw.Write(Index); bw.Write(DataOffset); } internal SourceFileEntry(MonoSymbolFile file, MyBinaryReader reader) { this.file = file; Index = reader.ReadInt32(); DataOffset = reader.ReadInt32(); int num = (int)reader.BaseStream.Position; reader.BaseStream.Position = DataOffset; sourceFile = (file_name = reader.ReadString()); guid = reader.ReadBytes(16); hash = reader.ReadBytes(16); auto_generated = reader.ReadByte() == 1; reader.BaseStream.Position = num; } public void SetAutoGenerated() { if (!creating) { throw new InvalidOperationException(); } auto_generated = true; file.OffsetTable.FileFlags |= OffsetTable.Flags.IsAspxSource; } public bool CheckChecksum() { try { using FileStream inputStream = new FileStream(sourceFile, FileMode.Open); MD5 mD = MD5.Create(); byte[] array = mD.ComputeHash(inputStream); for (int i = 0; i < 16; i++) { if (array[i] != hash[i]) { return false; } } return true; } catch { return false; } } public override string ToString() { return $"SourceFileEntry ({Index}:{DataOffset})"; } } public class LineNumberTable { protected LineNumberEntry[] _line_numbers; public readonly int LineBase; public readonly int LineRange; public readonly byte OpcodeBase; public readonly int MaxAddressIncrement; public const int Default_LineBase = -1; public const int Default_LineRange = 8; public const byte Default_OpcodeBase = 9; public const byte DW_LNS_copy = 1; public const byte DW_LNS_advance_pc = 2; public const byte DW_LNS_advance_line = 3; public const byte DW_LNS_set_file = 4; public const byte DW_LNS_const_add_pc = 8; public const byte DW_LNE_end_sequence = 1; public const byte DW_LNE_MONO_negate_is_hidden = 64; internal const byte DW_LNE_MONO__extensions_start = 64; internal const byte DW_LNE_MONO__extensions_end = 127; public LineNumberEntry[] LineNumbers => _line_numbers; protected LineNumberTable(MonoSymbolFile file) { LineBase = file.OffsetTable.LineNumberTable_LineBase; LineRange = file.OffsetTable.LineNumberTable_LineRange; OpcodeBase = (byte)file.OffsetTable.LineNumberTable_OpcodeBase; MaxAddressIncrement = (255 - OpcodeBase) / LineRange; } internal LineNumberTable(MonoSymbolFile file, LineNumberEntry[] lines) : this(file) { _line_numbers = lines; } internal void Write(MonoSymbolFile file, MyBinaryWriter bw, bool hasColumnsInfo, bool hasEndInfo) { int num = (int)bw.BaseStream.Position; bool flag = false; int num2 = 1; int num3 = 0; int num4 = 1; for (int i = 0; i < LineNumbers.Length; i++) { int num5 = LineNumbers[i].Row - num2; int num6 = LineNumbers[i].Offset - num3; if (LineNumbers[i].File != num4) { bw.Write((byte)4); bw.WriteLeb128(LineNumbers[i].File); num4 = LineNumbers[i].File; } if (LineNumbers[i].IsHidden != flag) { bw.Write((byte)0); bw.Write((byte)1); bw.Write((byte)64); flag = LineNumbers[i].IsHidden; } if (num6 >= MaxAddressIncrement) { if (num6 < 2 * MaxAddressIncrement) { bw.Write((byte)8); num6 -= MaxAddressIncrement; } else { bw.Write((byte)2); bw.WriteLeb128(num6); num6 = 0; } } if (num5 < LineBase || num5 >= LineBase + LineRange) { bw.Write((byte)3); bw.WriteLeb128(num5); if (num6 != 0) { bw.Write((byte)2); bw.WriteLeb128(num6); } bw.Write((byte)1); } else { byte value = (byte)(num5 - LineBase + LineRange * num6 + OpcodeBase); bw.Write(value); } num2 = LineNumbers[i].Row; num3 = LineNumbers[i].Offset; } bw.Write((byte)0); bw.Write((byte)1); bw.Write((byte)1); if (hasColumnsInfo) { for (int j = 0; j < LineNumbers.Length; j++) { LineNumberEntry lineNumberEntry = LineNumbers[j]; if (lineNumberEntry.Row >= 0) { bw.WriteLeb128(lineNumberEntry.Column); } } } if (hasEndInfo) { for (int k = 0; k < LineNumbers.Length; k++) { LineNumberEntry lineNumberEntry2 = LineNumbers[k]; if (lineNumberEntry2.EndRow == -1 || lineNumberEntry2.EndColumn == -1 || lineNumberEntry2.Row > lineNumberEntry2.EndRow) { bw.WriteLeb128(16777215); continue; } bw.WriteLeb128(lineNumberEntry2.EndRow - lineNumberEntry2.Row); bw.WriteLeb128(lineNumberEntry2.EndColumn); } } file.ExtendedLineNumberSize += (int)bw.BaseStream.Position - num; } internal static LineNumberTable Read(MonoSymbolFile file, MyBinaryReader br, bool readColumnsInfo, bool readEndInfo) { LineNumberTable lineNumberTable = new LineNumberTable(file); lineNumberTable.DoRead(file, br, readColumnsInfo, readEndInfo); return lineNumberTable; } private void DoRead(MonoSymbolFile file, MyBinaryReader br, bool includesColumns, bool includesEnds) { List<LineNumberEntry> list = new List<LineNumberEntry>(); bool flag = false; bool flag2 = false; int num = 1; int num2 = 0; int file2 = 1; while (true) { byte b = br.ReadByte(); if (b == 0) { byte b2 = br.ReadByte(); long position = br.BaseStream.Position + b2; b = br.ReadByte(); if (b == 1) { if (flag2) { list.Add(new LineNumberEntry(file2, num, -1, num2, flag)); } break; } if (b == 64) { flag = !flag; flag2 = true; } else if (b < 64 || b > 127) { throw new MonoSymbolFileException("Unknown extended opcode {0:x}", b); } br.BaseStream.Position = position; } else if (b < OpcodeBase) { switch (b) { case 1: list.Add(new LineNumberEntry(file2, num, -1, num2, flag)); flag2 = false; break; case 2: num2 += br.ReadLeb128(); flag2 = true; break; case 3: num += br.ReadLeb128(); flag2 = true; break; case 4: file2 = br.ReadLeb128(); flag2 = true; break; case 8: num2 += MaxAddressIncrement; flag2 = true; break; default: throw new MonoSymbolFileException("Unknown standard opcode {0:x} in LNT", b); } } else { b -= OpcodeBase; num2 += b / LineRange; num += LineBase + b % LineRange; list.Add(new LineNumberEntry(file2, num, -1, num2, flag)); flag2 = false; } } _line_numbers = list.ToArray(); if (includesColumns) { for (int i = 0; i < _line_numbers.Length; i++) { LineNumberEntry lineNumberEntry = _line_numbers[i]; if (lineNumberEntry.Row >= 0) { lineNumberEntry.Column = br.ReadLeb128(); } } } if (!includesEnds) { return; } for (int j = 0; j < _line_numbers.Length; j++) { LineNumberEntry lineNumberEntry2 = _line_numbers[j]; int num3 = br.ReadLeb128(); if (num3 == 16777215) { lineNumberEntry2.EndRow = -1; lineNumberEntry2.EndColumn = -1; } else { lineNumberEntry2.EndRow = lineNumberEntry2.Row + num3; lineNumberEntry2.EndColumn = br.ReadLeb128(); } } } public bool GetMethodBounds(out LineNumberEntry start, out LineNumberEntry end) { if (_line_numbers.Length > 1) { start = _line_numbers[0]; end = _line_numbers[_line_numbers.Length - 1]; return true; } start = LineNumberEntry.Null; end = LineNumberEntry.Null; return false; } } public class MethodEntry : IComparable { [Flags] public enum Flags { LocalNamesAmbiguous = 1, ColumnsInfoIncluded = 2, EndInfoIncluded = 4 } public readonly int CompileUnitIndex; public readonly int Token; public readonly int NamespaceID; private int DataOffset; private int LocalVariableTableOffset; private int LineNumberTableOffset; private int CodeBlockTableOffset; private int ScopeVariableTableOffset; private int RealNameOffset; private Flags flags; private int index; public readonly CompileUnitEntry CompileUnit; private LocalVariableEntry[] locals; private CodeBlockEntry[] code_blocks; private ScopeVariable[] scope_vars; private LineNumberTable lnt; private string real_name; public readonly MonoSymbolFile SymbolFile; public const int Size = 12; public Flags MethodFlags => flags; public int Index { get { return index; } set { index = value; } } internal MethodEntry(MonoSymbolFile file, MyBinaryReader reader, int index) { SymbolFile = file; this.index = index; Token = reader.ReadInt32(); DataOffset = reader.ReadInt32(); LineNumberTableOffset = reader.ReadInt32(); long position = reader.BaseStream.Position; reader.BaseStream.Position = DataOffset; CompileUnitIndex = reader.ReadLeb128(); LocalVariableTableOffset = reader.ReadLeb128(); NamespaceID = reader.ReadLeb128(); CodeBlockTableOffset = reader.ReadLeb128(); ScopeVariableTableOffset = reader.ReadLeb128(); RealNameOffset = reader.ReadLeb128(); flags = (Flags)reader.ReadLeb128(); reader.BaseStream.Position = position; CompileUnit = file.GetCompileUnit(CompileUnitIndex); } internal MethodEntry(MonoSymbolFile file, CompileUnitEntry comp_unit, int token, ScopeVariable[] scope_vars, LocalVariableEntry[] locals, LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, string real_name, Flags flags, int namespace_id) { SymbolFile = file; this.real_name = real_name; this.locals = locals; this.code_blocks = code_blocks; this.scope_vars = scope_vars; this.flags = flags; index = -1; Token = token; CompileUnitIndex = comp_unit.Index; CompileUnit = comp_unit; NamespaceID = namespace_id; CheckLineNumberTable(lines); lnt = new LineNumberTable(file, lines); file.NumLineNumbers += lines.Length; int num = ((locals != null) ? locals.Length : 0); if (num <= 32) { for (int i = 0; i < num; i++) { string name = locals[i].Name; for (int j = i + 1; j < num; j++) { if (locals[j].Name == name) { flags |= Flags.LocalNamesAmbiguous; return; } } } return; } Dictionary<string, LocalVariableEntry> dictionary = new Dictionary<string, LocalVariableEntry>(); for (int k = 0; k < locals.Length; k++) { LocalVariableEntry value = locals[k]; if (dictionary.ContainsKey(value.Name)) { flags |= Flags.LocalNamesAmbiguous; break; } dictionary.Add(value.Name, value); } } private static void CheckLineNumberTable(LineNumberEntry[] line_numbers) { int num = -1; int num2 = -1; if (line_numbers == null) { return; } foreach (LineNumberEntry lineNumberEntry in line_numbers) { if (lineNumberEntry.Equals(LineNumberEntry.Null)) { throw new MonoSymbolFileException(); } if (lineNumberEntry.Offset < num) { throw new MonoSymbolFileException(); } if (lineNumberEntry.Offset > num) { num2 = lineNumberEntry.Row; num = lineNumberEntry.Offset; } else if (lineNumberEntry.Row > num2) { num2 = lineNumberEntry.Row; } } } internal void Write(MyBinaryWriter bw) { if (index <= 0 || DataOffset == 0) { throw new InvalidOperationException(); } bw.Write(Token); bw.Write(DataOffset); bw.Write(LineNumberTableOffset); } internal void WriteData(MonoSymbolFile file, MyBinaryWriter bw) { if (index <= 0) { throw new InvalidOperationException(); } LocalVariableTableOffset = (int)bw.BaseStream.Position; int num = ((locals != null) ? locals.Length : 0); bw.WriteLeb128(num); for (int i = 0; i < num; i++) { locals[i].Write(file, bw); } file.LocalCount += num; CodeBlockTableOffset = (int)bw.BaseStream.Position; int num2 = ((code_blocks != null) ? code_blocks.Length : 0); bw.WriteLeb128(num2); for (int j = 0; j < num2; j++) { code_blocks[j].Write(bw); } ScopeVariableTableOffset = (int)bw.BaseStream.Position; int num3 = ((scope_vars != null) ? scope_vars.Length : 0); bw.WriteLeb128(num3); for (int k = 0; k < num3; k++) { scope_vars[k].Write(bw); } if (real_name != null) { RealNameOffset = (int)bw.BaseStream.Position; bw.Write(real_name); } LineNumberEntry[] lineNumbers = lnt.LineNumbers; foreach (LineNumberEntry lineNumberEntry in lineNumbers) { if (lineNumberEntry.EndRow != -1 || lineNumberEntry.EndColumn != -1) { flags |= Flags.EndInfoIncluded; } } LineNumberTableOffset = (int)bw.BaseStream.Position; lnt.Write(file, bw, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0); DataOffset = (int)bw.BaseStream.Position; bw.WriteLeb128(CompileUnitIndex); bw.WriteLeb128(LocalVariableTableOffset); bw.WriteLeb128(NamespaceID); bw.WriteLeb128(CodeBlockTableOffset); bw.WriteLeb128(ScopeVariableTableOffset); bw.WriteLeb128(RealNameOffset); bw.WriteLeb128((int)flags); } public void ReadAll() { GetLineNumberTable(); GetLocals(); GetCodeBlocks(); GetScopeVariables(); GetRealName(); } public LineNumberTable GetLineNumberTable() { lock (SymbolFile) { if (lnt != null) { return lnt; } if (LineNumberTableOffset == 0) { return null; } MyBinaryReader binaryReader = SymbolFile.BinaryReader; long position = binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = LineNumberTableOffset; lnt = LineNumberTable.Read(SymbolFile, binaryReader, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0); binaryReader.BaseStream.Position = position; return lnt; } } public LocalVariableEntry[] GetLocals() { lock (SymbolFile) { if (locals != null) { return locals; } if (LocalVariableTableOffset == 0) { return null; } MyBinaryReader binaryReader = SymbolFile.BinaryReader; long position = binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = LocalVariableTableOffset; int num = binaryReader.ReadLeb128(); locals = new LocalVariableEntry[num]; for (int i = 0; i < num; i++) { locals[i] = new LocalVariableEntry(SymbolFile, binaryReader); } binaryReader.BaseStream.Position = position; return locals; } } public CodeBlockEntry[] GetCodeBlocks() { lock (SymbolFile) { if (code_blocks != null) { return code_blocks; } if (CodeBlockTableOffset == 0) { return null; } MyBinaryReader binaryReader = SymbolFile.BinaryReader; long position = binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = CodeBlockTableOffset; int num = binaryReader.ReadLeb128(); code_blocks = new CodeBlockEntry[num]; for (int i = 0; i < num; i++) { code_blocks[i] = new CodeBlockEntry(i, binaryReader); } binaryReader.BaseStream.Position = position; return code_blocks; } } public ScopeVariable[] GetScopeVariables() { lock (SymbolFile) { if (scope_vars != null) { return scope_vars; } if (ScopeVariableTableOffset == 0) { return null; } MyBinaryReader binaryReader = SymbolFile.BinaryReader; long position = binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = ScopeVariableTableOffset; int num = binaryReader.ReadLeb128(); scope_vars = new ScopeVariable[num]; for (int i = 0; i < num; i++) { scope_vars[i] = new ScopeVariable(binaryReader); } binaryReader.BaseStream.Position = position; return scope_vars; } } public string GetRealName() { lock (SymbolFile) { if (real_name != null) { return real_name; } if (RealNameOffset == 0) { return null; } real_name = SymbolFile.BinaryReader.ReadString(RealNameOffset); return real_name; } } public int CompareTo(object obj) { MethodEntry methodEntry = (MethodEntry)obj; if (methodEntry.Token < Token) { return 1; } if (methodEntry.Token > Token) { return -1; } return 0; } public override string ToString() { return $"[Method {index}:{Token:x}:{CompileUnitIndex}:{CompileUnit}]"; } } public struct NamespaceEntry { public readonly string Name; public readonly int Index; public readonly int Parent; public readonly string[] UsingClauses; public NamespaceEntry(string name, int index, string[] using_clauses, int parent) { Name = name; Index = index; Parent = parent; UsingClauses = ((using_clauses != null) ? using_clauses : new string[0]); } internal NamespaceEntry(MonoSymbolFile file, MyBinaryReader reader) { Name = reader.ReadString(); Index = reader.ReadLeb128(); Parent = reader.ReadLeb128(); int num = reader.ReadLeb128(); UsingClauses = new string[num]; for (int i = 0; i < num; i++) { UsingClauses[i] = reader.ReadString(); } } internal void Write(MonoSymbolFile file, MyBinaryWriter bw) { bw.Write(Name); bw.WriteLeb128(Index); bw.WriteLeb128(Parent); bw.WriteLeb128(UsingClauses.Length); string[] usingClauses = UsingClauses; foreach (string value in usingClauses) { bw.Write(value); } } public override string ToString() { return $"[Namespace {Name}:{Index}:{Parent}]"; } } public class MonoSymbolWriter { private List<SourceMethodBuilder> methods; private List<SourceFileEntry> sources; private List<CompileUnitEntry> comp_units; protected readonly MonoSymbolFile file; private string filename; private SourceMethodBuilder current_method; private Stack<SourceMethodBuilder> current_method_stack = new Stack<SourceMethodBuilder>(); public MonoSymbolFile SymbolFile => file; public MonoSymbolWriter(string filename) { methods = new List<SourceMethodBuilder>(); sources = new List<SourceFileEntry>(); comp_units = new List<CompileUnitEntry>(); file = new MonoSymbolFile(); this.filename = filename + ".mdb"; } public void CloseNamespace() { } public void DefineLocalVariable(int index, string name) { if (current_method != null) { current_method.AddLocal(index, name); } } public void DefineCapturedLocal(int scope_id, string name, string captured_name) { file.DefineCapturedVariable(scope_id, name, captured_name, CapturedVariable.CapturedKind.Local); } public void DefineCapturedParameter(int scope_id, string name, string captured_name) { file.DefineCapturedVariable(scope_id, name, captured_name, CapturedVariable.CapturedKind.Parameter); } public void DefineCapturedThis(int scope_id, string captured_name) { file.DefineCapturedVariable(scope_id, "this", captured_name, CapturedVariable.CapturedKind.This); } public void DefineCapturedScope(int scope_id, int id, string captured_name) { file.DefineCapturedScope(scope_id, id, captured_name); } public void DefineScopeVariable(int scope, int index) { if (current_method != null) { current_method.AddScopeVariable(scope, index); } } public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, bool is_hidden) { if (current_method != null) { current_method.MarkSequencePoint(offset, file, line, column, is_hidden); } } public SourceMethodBuilder OpenMethod(ICompileUnit file, int ns_id, IMethodDef method) { SourceMethodBuilder result = new SourceMethodBuilder(file, ns_id, method); current_method_stack.Push(current_method); current_method = result; methods.Add(current_method); return result; } public void CloseMethod() { current_method = current_method_stack.Pop(); } public SourceFileEntry DefineDocument(string url) { SourceFileEntry sourceFileEntry = new SourceFileEntry(file, url); sources.Add(sourceFileEntry); return sourceFileEntry; } public SourceFileEntry DefineDocument(string url, byte[] guid, byte[] checksum) { SourceFileEntry sourceFileEntry = new SourceFileEntry(file, url, guid, checksum); sources.Add(sourceFileEntry); return sourceFileEntry; } public CompileUnitEntry DefineCompilationUnit(SourceFileEntry source) { CompileUnitEntry compileUnitEntry = new CompileUnitEntry(file, source); comp_units.Add(compileUnitEntry); return compileUnitEntry; } public int DefineNamespace(string name, CompileUnitEntry unit, string[] using_clauses, int parent) { if (unit == null || using_clauses == null) { throw new NullReferenceException(); } return unit.DefineNamespace(name, using_clauses, parent); } public int OpenScope(int start_offset) { if (current_method == null) { return 0; } current_method.StartBlock(CodeBlockEntry.Type.Lexical, start_offset); return 0; } public void CloseScope(int end_offset) { if (current_method != null) { current_method.EndBlock(end_offset); } } public void OpenCompilerGeneratedBlock(int start_offset) { if (current_method != null) { current_method.StartBlock(CodeBlockEntry.Type.CompilerGenerated, start_offset); } } public void CloseCompilerGeneratedBlock(int end_offset) { if (current_method != null) { current_method.EndBlock(end_offset); } } public void StartIteratorBody(int start_offset) { current_method.StartBlock(CodeBlockEntry.Type.IteratorBody, start_offset); } public void EndIteratorBody(int end_offset) { current_method.EndBlock(end_offset); } public void StartIteratorDispatcher(int start_offset) { current_method.StartBlock(CodeBlockEntry.Type.IteratorDispatcher, start_offset); } public void EndIteratorDispatcher(int end_offset) { current_method.EndBlock(end_offset); } public void DefineAnonymousScope(int id) { file.DefineAnonymousScope(id); } public void WriteSymbolFile(Guid guid) { foreach (SourceMethodBuilder method in methods) { method.DefineMethod(file); } try { File.Delete(filename); } catch { } using FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write); file.CreateSymbolFile(guid, fs); } } public class SourceMethodBuilder { private List<LocalVariableEntry> _locals; private List<CodeBlockEntry> _blocks; private List<ScopeVariable> _scope_vars; private Stack<CodeBlockEntry> _block_stack; private readonly List<LineNumberEntry> method_lines; private readonly ICompileUnit _comp_unit; private readonly int ns_id; private readonly IMethodDef method; public CodeBlockEntry[] Blocks { get { if (_blocks == null) { return new CodeBlockEntry[0]; } CodeBlockEntry[] array = new CodeBlockEntry[_blocks.Count]; _blocks.CopyTo(array, 0); return array; } } public CodeBlockEntry CurrentBlock { get { if (_block_stack != null && _block_stack.Count > 0) { return _block_stack.Peek(); } return null; } } public LocalVariableEntry[] Locals { get { if (_locals == null) { return new LocalVariableEntry[0]; } return _locals.ToArray(); } } public ICompileUnit SourceFile => _comp_unit; public ScopeVariable[] ScopeVariables { get { if (_scope_vars == null) { return new ScopeVariable[0]; } return _scope_vars.ToArray(); } } public SourceMethodBuilder(ICompileUnit comp_unit) { _comp_unit = comp_unit; method_lines = new List<LineNumberEntry>(); } public SourceMethodBuilder(ICompileUnit comp_unit, int ns_id, IMethodDef method) : this(comp_unit) { this.ns_id = ns_id; this.method = method; } public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, bool is_hidden) { MarkSequencePoint(offset, file, line, column, -1, -1, is_hidden); } public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, int end_line, int end_column, bool is_hidden) { int file2 = file?.Index ?? 0; LineNumberEntry lineNumberEntry = new LineNumberEntry(file2, line, column, end_line, end_column, offset, is_hidden); if (method_lines.Count > 0) { LineNumberEntry lineNumberEntry2 = method_lines[method_lines.Count - 1]; if (lineNumberEntry2.Offset == offset) { if (LineNumberEntry.LocationComparer.Default.Compare(lineNumberEntry, lineNumberEntry2) > 0) { method_lines[method_lines.Count - 1] = lineNumberEntry; } return; } } method_lines.Add(lineNumberEntry); } public void StartBlock(CodeBlockEntry.Type type, int start_offset) { StartBlock(type, start_offset, (_blocks == null) ? 1 : (_blocks.Count + 1)); } public void StartBlock(CodeBlockEntry.Type type, int start_offset, int scopeIndex) { if (_block_stack == null) { _block_stack = new Stack<CodeBlockEntry>(); } if (_blocks == null) { _blocks = new List<CodeBlockEntry>(); } int parent = ((CurrentBlock != null) ? CurrentBlock.Index : (-1)); CodeBlockEntry item = new CodeBlockEntry(scopeIndex, parent, type, start_offset); _block_stack.Push(item); _blocks.Add(item); } public void EndBlock(int end_offset) { CodeBlockEntry codeBlockEntry = _block_stack.Pop(); codeBlockEntry.Close(end_offset); } public void AddLocal(int index, string name) { if (_locals == null) { _locals = new List<LocalVariableEntry>(); } int block = ((CurrentBlock != null) ? CurrentBlock.Index : 0); _locals.Add(new LocalVariableEntry(index, name, block)); } public void AddScopeVariable(int scope, int index) { if (_scope_vars == null) { _scope_vars = new List<ScopeVariable>(); } _scope_vars.Add(new ScopeVariable(scope, index)); } public void DefineMethod(MonoSymbolFile file) { DefineMethod(file, method.Token); } public void DefineMethod(MonoSymbolFile file, int token) { CodeBlockEntry[] array = Blocks; if (array.Length != 0) { List<CodeBlockEntry> list = new List<CodeBlockEntry>(array.Length); int num = 0; for (int i = 0; i < array.Length; i++) { num = Math.Max(num, array[i].Index); } for (int j = 0; j < num; j++) { int num2 = j + 1; if (j < array.Length && array[j].Index == num2) { list.Add(array[j]); continue; } bool flag = false; for (int k = 0; k < array.Length; k++) { if (array[k].Index == num2) { list.Add(array[k]); flag = true; break; } } if (!flag) { list.Add(new CodeBlockEntry(num2, -1, CodeBlockEntry.Type.CompilerGenerated, 0)); } } array = list.ToArray(); } MethodEntry entry = new MethodEntry(file, _comp_unit.Entry, token, ScopeVariables, Locals, method_lines.ToArray(), array, null, MethodEntry.Flags.ColumnsInfoIncluded, ns_id); file.AddMethod(entry); } } public class SymbolWriterImpl : ISymbolWriter { private MonoSymbolWriter msw; private int nextLocalIndex; private int currentToken; private string methodName; private Stack namespaceStack = new Stack(); private bool methodOpened; private Hashtable documents = new Hashtable(); private Guid guid; public SymbolWriterImpl(Guid guid) { this.guid = guid; } public void Close() { msw.WriteSymbolFile(guid); } public void CloseMethod() { if (methodOpened) { methodOpened = false; nextLocalIndex = 0; msw.CloseMethod(); } } public void CloseNamespace() { namespaceStack.Pop(); msw.CloseNamespace(); } public void CloseScope(int endOffset) { msw.CloseScope(endOffset); } public ISymbolDocumentWriter DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType) { SymbolDocumentWriterImpl symbolDocumentWriterImpl = (SymbolDocumentWriterImpl)documents[url]; if (symbolDocumentWriterImpl == null) { SourceFileEntry source = msw.DefineDocument(url); CompileUnitEntry comp_unit = msw.DefineCompilationUnit(source); symbolDocumentWriterImpl = new SymbolDocumentWriterImpl(comp_unit); documents[url] = symbolDocumentWriterImpl; } return symbolDocumentWriterImpl; } public void DefineField(SymbolToken parent, string name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3) { } public void DefineGlobalVariable(string name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3) { } public void DefineLocalVariable(string name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3, int startOffset, int endOffset) { msw.DefineLocalVariable(nextLocalIndex++, name); } public void DefineParameter(string name, ParameterAttributes attributes, int sequence, SymAddressKind addrKind, int addr1, int addr2, int addr3) { } public void DefineSequencePoints(ISymbolDocumentWriter document, int[] offsets, int[] lines, int[] columns, int[] endLines, int[] endColumns) { SourceFileEntry file = ((SymbolDocumentWriterImpl)document)?.Entry.SourceFile; for (int i = 0; i < offsets.Length; i++) { if (i <= 0 || offsets[i] != offsets[i - 1] || lines[i] != lines[i - 1] || columns[i] != columns[i - 1]) { msw.MarkSequencePoint(offsets[i], file, lines[i], columns[i], is_hidden: false); } } } public void Initialize(IntPtr emitter, string filename, bool fFullBuild) { msw = new MonoSymbolWriter(filename); } public void OpenMethod(SymbolToken method) { currentToken = method.GetToken(); } public void OpenNamespace(string name) { NamespaceInfo namespaceInfo = new NamespaceInfo(); namespaceInfo.NamespaceID = -1; namespaceInfo.Name = name; namespaceStack.Push(namespaceInfo); } public int OpenScope(int startOffset) { return msw.OpenScope(startOffset); } public void SetMethodSourceRange(ISymbolDocumentWriter startDoc, int startLine, int startColumn, ISymbolDocumentWriter endDoc, int endLine, int endColumn) { int currentNamespace = GetCurrentNamespace(startDoc); SourceMethodImpl method = new SourceMethodImpl(methodName, currentToken, currentNamespace); msw.OpenMethod(((ICompileUnit)startDoc).Entry, currentNamespace, method); methodOpened = true; } public void SetScopeRange(int scopeID, int startOffset, int endOffset) { } public void SetSymAttribute(SymbolToken parent, string name, byte[] data) { if (name == "__name") { methodName = Encoding.UTF8.GetString(data); } } public void SetUnderlyingWriter(IntPtr underlyingWriter) { } public void SetUserEntryPoint(SymbolToken entryMethod) { } public void UsingNamespace(string fullName) { if (namespaceStack.Count == 0) { OpenNamespace(""); } NamespaceInfo namespaceInfo = (NamespaceInfo)namespaceStack.Peek(); if (namespaceInfo.NamespaceID != -1) { NamespaceInfo namespaceInfo2 = namespaceInfo; CloseNamespace(); OpenNamespace(namespaceInfo2.Name); namespaceInfo = (NamespaceInfo)namespaceStack.Peek(); namespaceInfo.UsingClauses = namespaceInfo2.UsingClauses; } namespaceInfo.UsingClauses.Add(fullName); } private int GetCurrentNamespace(ISymbolDocumentWriter doc) { if (namespaceStack.Count == 0) { OpenNamespace(""); } NamespaceInfo namespaceInfo = (NamespaceInfo)namespaceStack.Peek(); if (namespaceInfo.NamespaceID == -1) { string[] using_clauses = (string[])namespaceInfo.UsingClauses.ToArray(typeof(string)); int parent = 0; if (namespaceStack.Count > 1) { namespaceStack.Pop(); parent = ((NamespaceInfo)namespaceStack.Peek()).NamespaceID; namespaceStack.Push(namespaceInfo); } namespaceInfo.NamespaceID = msw.DefineNamespace(namespaceInfo.Name, ((ICompileUnit)doc).Entry, using_clauses, parent); } return namespaceInfo.NamespaceID; } } internal class SymbolDocumentWriterImpl : ISymbolDocumentWriter, ISourceFile, ICompileUnit { private CompileUnitEntry comp_unit; SourceFileEntry ISourceFile.Entry => comp_unit.SourceFile; public CompileUnitEntry Entry => comp_unit; public SymbolDocumentWriterImpl(CompileUnitEntry comp_unit) { this.comp_unit = comp_unit; } public void SetCheckSum(Guid algorithmId, byte[] checkSum) { } public void SetSource(byte[] source) { } } internal class SourceMethodImpl : IMethodDef { private string name; private int token; private int namespaceID; public string Name => name; public int NamespaceID => namespaceID; public int Token => token; public SourceMethodImpl(string name, int token, int namespaceID) { this.name = name; this.token = token; this.namespaceID = namespaceID; } } internal class NamespaceInfo { public string Name; public int NamespaceID; public ArrayList UsingClauses = new ArrayList(); } } namespace Mono.Cecil.Mdb { public sealed class MdbReaderProvider : ISymbolReaderProvider { public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName) { Mixin.CheckModule(module); Mixin.CheckFileName(fileName); return (ISymbolReader)(object)new MdbReader(module, MonoSymbolFile.ReadSymbolFile(Mixin.GetMdbFileName(fileName))); } public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream) { Mixin.CheckModule(module); Mixin.CheckStream((object)symbolStream); return (ISymbolReader)(object)new MdbReader(module, MonoSymbolFile.ReadSymbolFile(symbolStream)); } } public sealed class MdbReader : ISymbolReader, IDisposable { private readonly ModuleDefinition module; private readonly MonoSymbolFile symbol_file; private readonly Dictionary<string, Document> documents; public MdbReader(ModuleDefinition module, MonoSymbolFile symFile) { this.module = module; symbol_file = symFile; documents = new Dictionary<string, Document>(); } public ISymbolWriterProvider GetWriterProvider() { return (ISymbolWriterProvider)(object)new MdbWriterProvider(); } public bool ProcessDebugHeader(ImageDebugHeader header) { return symbol_file.Guid == module.Mvid; } public MethodDebugInformation Read(MethodDefinition method) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: 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_0031: Expected O, but got Unknown MetadataToken metadataToken = ((MemberReference)method).MetadataToken; MethodEntry methodByToken = symbol_file.GetMethodByToken(((MetadataToken)(ref metadataToken)).ToInt32()); if (methodByToken == null) { return null; } MethodDebugInformation val = new MethodDebugInformation(method); val.code_size = ReadCodeSize(method); ScopeDebugInformation[] scopes = ReadScopes(methodByToken, val); ReadLineNumbers(methodByToken, val); ReadLocalVariables(methodByToken, scopes); return val; } private static int ReadCodeSize(MethodDefinition method) { return ((MemberReference)method).Module.Read<MethodDefinition, int>(method, (Func<MethodDefinition, MetadataReader, int>)((MethodDefinition m, MetadataReader reader) => reader.ReadCodeSize(m))); } private static void ReadLocalVariables(MethodEntry entry, ScopeDebugInformation[] scopes) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown LocalVariableEntry[] locals = entry.GetLocals(); LocalVariableEntry[] array = locals; for (int i = 0; i < array.Length; i++) { LocalVariableEntry localVariableEntry = array[i]; VariableDebugInformation val = new VariableDebugInformation(localVariableEntry.Index, localVariableEntry.Name); int blockIndex = localVariableEntry.BlockIndex; if (blockIndex >= 0 && blockIndex < scopes.Length) { ScopeDebugInformation val2 = scopes[blockIndex]; if (val2 != null) { val2.Variables.Add(val); } } } } private void ReadLineNumbers(MethodEntry entry, MethodDebugInformation info) { LineNumberTable lineNumberTable = entry.GetLineNumberTable(); info.sequence_points = new Collection<SequencePoint>(lineNumberTable.LineNumbers.Length); for (int i = 0; i < lineNumberTable.LineNumbers.Length; i++) { LineNumberEntry lineNumberEntry = lineNumberTable.LineNumbers[i]; if (i <= 0 || lineNumberTable.LineNumbers[i - 1].Offset != lineNumberEntry.Offset) { info.sequence_points.Add(LineToSequencePoint(lineNumberEntry)); } } } private Document GetDocument(SourceFileEntry file) { //IL_001f: 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_0032: Expected O, but got Unknown string fileName = file.FileName; if (documents.TryGetValue(fileName, out var value)) { return value; } value = new Document(fileName) { Hash = file.Checksum }; documents.Add(fileName, value); return value; } private static ScopeDebugInformation[] ReadScopes(MethodEntry entry, MethodDebugInformation info) { //IL_0016: 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_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002f: 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_003c: Expected O, but got Unknown //IL_003d: Expected O, but got Unknown //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Expected O, but got Unknown //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) CodeBlockEntry[] codeBlocks = entry.GetCodeBlocks(); ScopeDebugInformation[] array = (ScopeDebugInformation[])(object)new ScopeDebugInformation[codeBlocks.Length + 1]; ScopeDebugInformation val = new ScopeDebugInformation { Start = new InstructionOffset(0), End = new InstructionOffset(info.code_size) }; ScopeDebugInformation scope = val; array[0] = val; info.scope = scope; CodeBlockEntry[] array2 = codeBlocks; foreach (CodeBlockEntry codeBlockEntry in array2) { if (codeBlockEntry.BlockType == CodeBlockEntry.Type.Lexical || codeBlockEntry.BlockType == CodeBlockEntry.Type.CompilerGenerated) { ScopeDebugInformation val2 = new ScopeDebugInformation(); val2.Start = new InstructionOffset(codeBlockEntry.StartOffset); val2.End = new InstructionOffset(codeBlockEntry.EndOffset); array[codeBlockEntry.Index + 1] = val2; if (!AddScope(info.scope.Scopes, val2)) { info.scope.Scopes.Add(val2); } } } return array; } private static bool AddScope(Collection<ScopeDebugInformation> scopes, ScopeDebugInformation scope) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0008: 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_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) Enumerator<ScopeDebugInformation> enumerator = scopes.GetEnumerator(); try { while (enumerator.MoveNext()) { ScopeDebugInformation current = enumerator.Current; if (current.HasScopes && AddScope(current.Scopes, scope)) { return true; } InstructionOffset val = scope.Start; int offset = ((InstructionOffset)(ref val)).Offset; val = current.Start; if (offset >= ((InstructionOffset)(ref val)).Offset) { val = scope.End; int offset2 = ((InstructionOffset)(ref val)).Offset; val = current.End; if (offset2 <= ((InstructionOffset)(ref val)).Offset) { current.Scopes.Add(scope); return true; } } } } finally { ((IDisposable)enumerator).Dispose(); } return false; } private SequencePoint LineToSequencePoint(LineNumberEntry line) { //IL_0020: 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_0032: Unknown result type (might be due to invalid IL or missing references) //IL_003f: 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 SourceFileEntry sourceFile = symbol_file.GetSourceFile(line.File); return new SequencePoint(line.Offset, GetDocument(sourceFile)) { StartLine = line.Row, EndLine = line.EndRow, StartColumn = line.Column, EndColumn = line.EndColumn }; } public Collection<CustomDebugInformation> Read(ICustomDebugInformationProvider provider) { return new Collection<CustomDebugInformation>(); } public void Dispose() { symbol_file.Dispose(); } } internal static class MethodEntryExtensions { public static bool HasColumnInfo(this MethodEntry entry) { return (entry.MethodFlags & MethodEntry.Flags.ColumnsInfoIncluded) != 0; } public static bool HasEndInfo(this MethodEntry entry) { return (entry.MethodFlags & MethodEntry.Flags.EndInfoIncluded) != 0; } } public sealed class MdbWriterProvider : ISymbolWriterProvider { public ISymbolWriter GetSymbolWriter(ModuleDefinition module, string fileName) { Mixin.CheckModule(module); Mixin.CheckFileName(fileName); return (ISymbolWriter)(object)new MdbWriter(module, fileName); } public ISymbolWriter GetSymbolWriter(ModuleDefinition module, Stream symbolStream) { throw new NotImplementedException(); } } public sealed class MdbWriter : ISymbolWriter, IDisposable { private class SourceFile : ISourceFile { private readonly CompileUnitEntry compilation_unit; private readonly SourceFileEntry entry; public SourceFileEntry Entry => entry; public CompileUnitEntry CompilationUnit => compilation_unit; public SourceFile(CompileUnitEntry comp_unit, SourceFileEntry entry) { compilation_unit = comp_unit; this.entry = entry; } } private class SourceMethod : IMethodDef { private readonly MethodDefinition method; public string Name => ((MemberReference)method).Name; public int Token { get { //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) MetadataToken metadataToken = ((MemberReference)method).MetadataToken; return ((MetadataToken)(ref metadataToken)).ToInt32(); } } public SourceMethod(MethodDefinition method) { this.method = method; } } private readonly ModuleDefinition module; private readonly MonoSymbolWriter writer; private readonly Dictionary<string, SourceFile> source_files; public MdbWriter(ModuleDefinition module, string assembly) { this.module = module; writer = new MonoSymbolWriter(assembly); source_files = new Dictionary<string, SourceFile>(); } public ISymbolReaderProvider GetReaderProvider() { return (ISymbolReaderProvider)(object)new MdbReaderProvider(); } private SourceFile GetSourceFile(Document document) { string url = document.Url; if (source_files.TryGetValue(url, out var value)) { return value; } SourceFileEntry sourceFileEntry = writer.DefineDocument(url, null, (document.Hash != null && document.Hash.Length == 16) ? document.Hash : null); CompileUnitEntry comp_unit = writer.DefineCompilationUnit(sourceFileEntry); value = new SourceFile(comp_unit, sourceFileEntry); source_files.Add(url, value); return value; } private void Populate(Collection<SequencePoint> sequencePoints, int[] offsets, int[] startRows, int[] endRows, int[] startCols, int[] endCols, out SourceFile file) { SourceFile sourceFile = null; for (int i = 0; i < sequencePoints.Count; i++) { SequencePoint val = sequencePoints[i]; offsets[i] = val.Offset; if (sourceFile == null) { sourceFile = GetSourceFile(val.Document); } startRows[i] = val.StartLine; endRows[i] = val.EndLine; startCols[i] = val.StartColumn; endCols[i] = val.EndColumn; } file = sourceFile; } public void Write(MethodDebugInformation info) { SourceMethod method = new SourceMethod(info.method); Collection<SequencePoint> sequencePoints = info.SequencePoints; int count = sequencePoints.Count; if (count != 0) { int[] array = new int[count]; int[] array2 = new int[count]; int[] array3 = new int[count]; int[] array4 = new int[count]; int[] array5 = new int[count]; Populate(sequencePoints, array, array2, array3, array4, array5, out var file); SourceMethodBuilder sourceMethodBuilder = writer.OpenMethod(file.CompilationUnit, 0, method); for (int i = 0; i < count; i++) { sourceMethodBuilder.MarkSequencePoint(array[i], file.CompilationUnit.SourceFile, array2[i], array4[i], array3[i], array5[i], is_hidden: false); } if (info.scope != null) { WriteRootScope(info.scope, info); } writer.CloseMethod(); } } private void WriteRootScope(ScopeDebugInformation scope, MethodDebugInformation info) { WriteScopeVariables(scope); if (scope.HasScopes) { WriteScopes(scope.Scopes, info); } } private void WriteScope(ScopeDebugInformation scope, MethodDebugInformation info) { //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_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) MonoSymbolWriter monoSymbolWriter = writer; InstructionOffset val = scope.Start; monoSymbolWriter.OpenScope(((InstructionOffset)(ref val)).Offset); WriteScopeVariables(scope); if (scope.HasScopes) { WriteScopes(scope.Scopes, info); } MonoSymbolWriter monoSymbolWriter2 = writer; val = scope.End; int end_offset; if (!((InstructionOffset)(ref val)).IsEndOfMethod) { val = scope.End; end_offset = ((InstructionOffset)(ref val)).Offset; } else { end_offset = info.code_size; } monoSymbolWriter2.CloseScope(end_offset); } private void WriteScopes(Collection<ScopeDebugInformation> scopes, MethodDebugInformation info) { for (int i = 0; i < scopes.Count; i++) { WriteScope(scopes[i], info); } } private void WriteScopeVariables(ScopeDebugInformation scope) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) if (!scope.HasVariables) { return; } Enumerator<VariableDebugInformation> enumerator = scope.variables.GetEnumerator(); try { while (enumerator.MoveNext()) { VariableDebugInformation current = enumerator.Current; if (!string.IsNullOrEmpty(current.Name)) { writer.DefineLocalVariable(current.Index, current.Name); } } } finally { ((IDisposable)enumerator).Dispose(); } } public ImageDebugHeader GetDebugHeader() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown return new ImageDebugHeader(); } public void Write() { } public void Write(ICustomDebugInformationProvider provider) { } public void Dispose() { writer.WriteSymbolFile(module.Mvid); } } }
BepInEx/core/Mono.Cecil.Pdb.dll
Decompiled a week ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using Microsoft.Cci.Pdb; using Microsoft.CodeAnalysis; using Mono.Cecil.Cil; using Mono.Cecil.PE; using Mono.Collections.Generic; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyProduct("Mono.Cecil")] [assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")] [assembly: ComVisible(false)] [assembly: AssemblyFileVersion("0.11.6.0")] [assembly: AssemblyInformationalVersion("0.11.6.0")] [assembly: AssemblyTitle("Mono.Cecil.Pdb")] [assembly: CLSCompliant(false)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.11.6.0")] [module: UnverifiableCode] [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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Mono.Cecil.Pdb { [ComImport] [Guid("B01FAFEB-C450-3A4D-BEEC-B4CEEC01E006")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISymUnmanagedDocumentWriter { void SetSource(uint sourceSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] byte[] source); void SetCheckSum(Guid algorithmId, uint checkSumSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] checkSum); } [ComImport] [Guid("0B97726E-9E6D-4f05-9A26-424022093CAA")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISymUnmanagedWriter2 { void DefineDocument([In][MarshalAs(UnmanagedType.LPWStr)] string url, [In] ref Guid langauge, [In] ref Guid languageVendor, [In] ref Guid documentType, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedDocumentWriter pRetVal); void SetUserEntryPoint([In] int methodToken); void OpenMethod([In] int methodToken); void CloseMethod(); void OpenScope([In] int startOffset, out int pRetVal); void CloseScope([In] int endOffset); void SetScopeRange_Placeholder(); void DefineLocalVariable_Placeholder(); void DefineParameter_Placeholder(); void DefineField_Placeholder(); void DefineGlobalVariable_Placeholder(); void Close(); void SetSymAttribute(uint parent, string name, uint data, IntPtr signature); void OpenNamespace([In][MarshalAs(UnmanagedType.LPWStr)] string name); void CloseNamespace(); void UsingNamespace([In][MarshalAs(UnmanagedType.LPWStr)] string fullName); void SetMethodSourceRange_Placeholder(); void Initialize([In][MarshalAs(UnmanagedType.IUnknown)] object emitter, [In][MarshalAs(UnmanagedType.LPWStr)] string filename, [In] IStream pIStream, [In] bool fFullBuild); void GetDebugInfo(out ImageDebugDirectory pIDD, [In] int cData, out int pcData, [In][Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data); void DefineSequencePoints([In][MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocumentWriter document, [In] int spCount, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] offsets, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] lines, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] columns, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endLines, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endColumns); void RemapToken_Placeholder(); void Initialize2_Placeholder(); void DefineConstant_Placeholder(); void Abort_Placeholder(); void DefineLocalVariable2([In][MarshalAs(UnmanagedType.LPWStr)] string name, [In] int attributes, [In] int sigToken, [In] int addrKind, [In] int addr1, [In] int addr2, [In] int addr3, [In] int startOffset, [In] int endOffset); void DefineGlobalVariable2_Placeholder(); void DefineConstant2([In][MarshalAs(UnmanagedType.LPWStr)] string name, [In][MarshalAs(UnmanagedType.Struct)] object variant, [In] int sigToken); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("BA3FEE4C-ECB9-4e41-83B7-183FA41CD859")] internal interface IMetaDataEmit { void SetModuleProps(string szName); void Save(string szFile, uint dwSaveFlags); void SaveToStream(IntPtr pIStream, uint dwSaveFlags); uint GetSaveSize(uint fSave); uint DefineTypeDef(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements); uint DefineNestedType(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements, uint tdEncloser); void SetHandler([In][MarshalAs(UnmanagedType.IUnknown)] object pUnk); uint DefineMethod(uint td, IntPtr zName, uint dwMethodFlags, IntPtr pvSigBlob, uint cbSigBlob, uint ulCodeRVA, uint dwImplFlags); void DefineMethodImpl(uint td, uint tkBody, uint tkDecl); uint DefineTypeRefByName(uint tkResolutionScope, IntPtr szName); uint DefineImportType(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint tdImport, IntPtr pAssemEmit); uint DefineMemberRef(uint tkImport, string szName, IntPtr pvSigBlob, uint cbSigBlob); uint DefineImportMember(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint mbMember, IntPtr pAssemEmit, uint tkParent); uint DefineEvent(uint td, string szEvent, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods); void SetClassLayout(uint td, uint dwPackSize, IntPtr rFieldOffsets, uint ulClassSize); void DeleteClassLayout(uint td); void SetFieldMarshal(uint tk, IntPtr pvNativeType, uint cbNativeType); void DeleteFieldMarshal(uint tk); uint DefinePermissionSet(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission); void SetRVA(uint md, uint ulRVA); uint GetTokenFromSig(IntPtr pvSig, uint cbSig); uint DefineModuleRef(string szName); void SetParent(uint mr, uint tk); uint GetTokenFromTypeSpec(IntPtr pvSig, uint cbSig); void SaveToMemory(IntPtr pbData, uint cbData); uint DefineUserString(string szString, uint cchString); void DeleteToken(uint tkObj); void SetMethodProps(uint md, uint dwMethodFlags, uint ulCodeRVA, uint dwImplFlags); void SetTypeDefProps(uint td, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements); void SetEventProps(uint ev, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods); uint SetPermissionSetProps(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission); void DefinePinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL); void SetPinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL); void DeletePinvokeMap(uint tk); uint DefineCustomAttribute(uint tkObj, uint tkType, IntPtr pCustomAttribute, uint cbCustomAttribute); void SetCustomAttributeValue(uint pcv, IntPtr pCustomAttribute, uint cbCustomAttribute); uint DefineField(uint td, string szName, uint dwFieldFlags, IntPtr pvSigBlob, uint cbSigBlob, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue); uint DefineProperty(uint td, string szProperty, uint dwPropFlags, IntPtr pvSig, uint cbSig, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods); uint DefineParam(uint md, uint ulParamSeq, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue); void SetFieldProps(uint fd, uint dwFieldFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue); void SetPropertyProps(uint pr, uint dwPropFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods); void SetParamProps(uint pd, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue); uint DefineSecurityAttributeSet(uint tkObj, IntPtr rSecAttrs, uint cSecAttrs); void ApplyEditAndContinue([MarshalAs(UnmanagedType.IUnknown)] object pImport); uint TranslateSigWithScope(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport import, IntPtr pbSigBlob, uint cbSigBlob, IntPtr pAssemEmit, IMetaDataEmit emit, IntPtr pvTranslatedSig, uint cbTranslatedSigMax); void SetMethodImplFlags(uint md, uint dwImplFlags); void SetFieldRVA(uint fd, uint ulRVA); void Merge(IMetaDataImport pImport, IntPtr pHostMapToken, [MarshalAs(UnmanagedType.IUnknown)] object pHandler); void MergeEnd(); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("7DAC8207-D3AE-4c75-9B67-92801A497D44")] internal interface IMetaDataImport { [PreserveSig] void CloseEnum(uint hEnum); uint CountEnum(uint hEnum); void ResetEnum(uint hEnum, uint ulPos); uint EnumTypeDefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeDefs, uint cMax); uint EnumInterfaceImpls(ref uint phEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rImpls, uint cMax); uint EnumTypeRefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeRefs, uint cMax); uint FindTypeDefByName(string szTypeDef, uint tkEnclosingClass); Guid GetScopeProps(StringBuilder szName, uint cchName, out uint pchName); uint GetModuleFromScope(); [PreserveSig] unsafe uint GetTypeDefProps(uint td, char* szTypeDef, uint cchTypeDef, uint* pchTypeDef, uint* pdwTypeDefFlags, uint* ptkExtends); uint GetInterfaceImplProps(uint iiImpl, out uint pClass); uint GetTypeRefProps(uint tr, out uint ptkResolutionScope, StringBuilder szName, uint cchName); uint ResolveTypeRef(uint tr, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppIScope); uint EnumMembers(ref uint phEnum, uint cl, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rMembers, uint cMax); uint EnumMembersWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMembers, uint cMax); uint EnumMethods(ref uint phEnum, uint cl, IntPtr rMethods, uint cMax); uint EnumMethodsWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethods, uint cMax); uint EnumFields(ref uint phEnum, uint cl, IntPtr rFields, uint cMax); uint EnumFieldsWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rFields, uint cMax); uint EnumParams(ref uint phEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rParams, uint cMax); uint EnumMemberRefs(ref uint phEnum, uint tkParent, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rMemberRefs, uint cMax); uint EnumMethodImpls(ref uint phEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethodBody, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethodDecl, uint cMax); uint EnumPermissionSets(ref uint phEnum, uint tk, uint dwActions, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rPermission, uint cMax); uint FindMember(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob); uint FindMethod(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob); uint FindField(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob); uint FindMemberRef(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob); [PreserveSig] unsafe uint GetMethodProps(uint mb, uint* pClass, char* szMethod, uint cchMethod, uint* pchMethod, uint* pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, uint* pulCodeRVA, uint* pdwImplFlags); uint GetMemberRefProps(uint mr, ref uint ptk, StringBuilder szMember, uint cchMember, out uint pchMember, out IntPtr ppvSigBlob); uint EnumProperties(ref uint phEnum, uint td, IntPtr rProperties, uint cMax); uint EnumEvents(ref uint phEnum, uint td, IntPtr rEvents, uint cMax); uint GetEventProps(uint ev, out uint pClass, StringBuilder szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 11)] uint[] rmdOtherMethod, uint cMax); uint EnumMethodSemantics(ref uint phEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rEventProp, uint cMax); uint GetMethodSemantics(uint mb, uint tkEventProp); uint GetClassLayout(uint td, out uint pdwPackSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] IntPtr rFieldOffset, uint cMax, out uint pcFieldOffset); uint GetFieldMarshal(uint tk, out IntPtr ppvNativeType); uint GetRVA(uint tk, out uint pulCodeRVA); uint GetPermissionSetProps(uint pm, out uint pdwAction, out IntPtr ppvPermission); uint GetSigFromToken(uint mdSig, out IntPtr ppvSig); uint GetModuleRefProps(uint mur, StringBuilder szName, uint cchName); uint EnumModuleRefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rModuleRefs, uint cmax); uint GetTypeSpecFromToken(uint typespec, out IntPtr ppvSig); uint GetNameFromToken(uint tk); uint EnumUnresolvedMethods(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rMethods, uint cMax); uint GetUserString(uint stk, StringBuilder szString, uint cchString); uint GetPinvokeMap(uint tk, out uint pdwMappingFlags, StringBuilder szImportName, uint cchImportName, out uint pchImportName); uint EnumSignatures(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rSignatures, uint cmax); uint EnumTypeSpecs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeSpecs, uint cmax); uint EnumUserStrings(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rStrings, uint cmax); [PreserveSig] int GetParamForMethodIndex(uint md, uint ulParamSeq, out uint pParam); uint EnumCustomAttributes(ref uint phEnum, uint tk, uint tkType, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rCustomAttributes, uint cMax); uint GetCustomAttributeProps(uint cv, out uint ptkObj, out uint ptkType, out IntPtr ppBlob); uint FindTypeRef(uint tkResolutionScope, string szName); uint GetMemberProps(uint mb, out uint pClass, StringBuilder szMember, uint cchMember, out uint pchMember, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out IntPtr ppValue); uint GetFieldProps(uint mb, out uint pClass, StringBuilder szField, uint cchField, out uint pchField, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out IntPtr ppValue); uint GetPropertyProps(uint prop, out uint pClass, StringBuilder szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out IntPtr ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out IntPtr ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 14)] uint[] rmdOtherMethod, uint cMax); uint GetParamProps(uint tk, out uint pmd, out uint pulSequence, StringBuilder szName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out IntPtr ppValue); uint GetCustomAttributeByName(uint tkObj, string szName, out IntPtr ppData); [PreserveSig] [return: MarshalAs(UnmanagedType.Bool)] bool IsValidToken(uint tk); [PreserveSig] unsafe uint GetNestedClassProps(uint tdNestedClass, uint* ptdEnclosingClass); uint GetNativeCallConvFromSig(IntPtr pvSig, uint cbSig); int IsGlobal(uint pd); } internal class ModuleMetadata : IMetaDataEmit, IMetaDataImport { private readonly ModuleDefinition module; private Dictionary<uint, TypeDefinition> types; private Dictionary<uint, MethodDefinition> methods; private const uint S_OK = 0u; private const uint E_FAIL = 2147500037u; public ModuleMetadata(ModuleDefinition module) { this.module = module; } private bool TryGetType(uint token, out TypeDefinition type) { if (types == null) { InitializeMetadata(module); } return types.TryGetValue(token, out type); } private bool TryGetMethod(uint token, out MethodDefinition method) { if (methods == null) { InitializeMetadata(module); } return methods.TryGetValue(token, out method); } private void InitializeMetadata(ModuleDefinition module) { //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) types = new Dictionary<uint, TypeDefinition>(); methods = new Dictionary<uint, MethodDefinition>(); foreach (TypeDefinition type in module.GetTypes()) { Dictionary<uint, TypeDefinition> dictionary = types; MetadataToken metadataToken = ((MemberReference)type).MetadataToken; dictionary.Add(((MetadataToken)(ref metadataToken)).ToUInt32(), type); InitializeMethods(type); } } private void InitializeMethods(TypeDefinition type) { //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_001f: 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) Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator(); try { while (enumerator.MoveNext()) { MethodDefinition current = enumerator.Current; Dictionary<uint, MethodDefinition> dictionary = methods; MetadataToken metadataToken = ((MemberReference)current).MetadataToken; dictionary.Add(((MetadataToken)(ref metadataToken)).ToUInt32(), current); } } finally { ((IDisposable)enumerator).Dispose(); } } public void SetModuleProps(string szName) { throw new NotImplementedException(); } public void Save(string szFile, uint dwSaveFlags) { throw new NotImplementedException(); } public void SaveToStream(IntPtr pIStream, uint dwSaveFlags) { throw new NotImplementedException(); } public uint GetSaveSize(uint fSave) { throw new NotImplementedException(); } public uint DefineTypeDef(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements) { throw new NotImplementedException(); } public uint DefineNestedType(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements, uint tdEncloser) { throw new NotImplementedException(); } public void SetHandler(object pUnk) { throw new NotImplementedException(); } public uint DefineMethod(uint td, IntPtr zName, uint dwMethodFlags, IntPtr pvSigBlob, uint cbSigBlob, uint ulCodeRVA, uint dwImplFlags) { throw new NotImplementedException(); } public void DefineMethodImpl(uint td, uint tkBody, uint tkDecl) { throw new NotImplementedException(); } public uint DefineTypeRefByName(uint tkResolutionScope, IntPtr szName) { throw new NotImplementedException(); } public uint DefineImportType(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint tdImport, IntPtr pAssemEmit) { throw new NotImplementedException(); } public uint DefineMemberRef(uint tkImport, string szName, IntPtr pvSigBlob, uint cbSigBlob) { throw new NotImplementedException(); } public uint DefineImportMember(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint mbMember, IntPtr pAssemEmit, uint tkParent) { throw new NotImplementedException(); } public uint DefineEvent(uint td, string szEvent, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods) { throw new NotImplementedException(); } public void SetClassLayout(uint td, uint dwPackSize, IntPtr rFieldOffsets, uint ulClassSize) { throw new NotImplementedException(); } public void DeleteClassLayout(uint td) { throw new NotImplementedException(); } public void SetFieldMarshal(uint tk, IntPtr pvNativeType, uint cbNativeType) { throw new NotImplementedException(); } public void DeleteFieldMarshal(uint tk) { throw new NotImplementedException(); } public uint DefinePermissionSet(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission) { throw new NotImplementedException(); } public void SetRVA(uint md, uint ulRVA) { throw new NotImplementedException(); } public uint GetTokenFromSig(IntPtr pvSig, uint cbSig) { throw new NotImplementedException(); } public uint DefineModuleRef(string szName) { throw new NotImplementedException(); } public void SetParent(uint mr, uint tk) { throw new NotImplementedException(); } public uint GetTokenFromTypeSpec(IntPtr pvSig, uint cbSig) { throw new NotImplementedException(); } public void SaveToMemory(IntPtr pbData, uint cbData) { throw new NotImplementedException(); } public uint DefineUserString(string szString, uint cchString) { throw new NotImplementedException(); } public void DeleteToken(uint tkObj) { throw new NotImplementedException(); } public void SetMethodProps(uint md, uint dwMethodFlags, uint ulCodeRVA, uint dwImplFlags) { throw new NotImplementedException(); } public void SetTypeDefProps(uint td, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements) { throw new NotImplementedException(); } public void SetEventProps(uint ev, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods) { throw new NotImplementedException(); } public uint SetPermissionSetProps(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission) { throw new NotImplementedException(); } public void DefinePinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL) { throw new NotImplementedException(); } public void SetPinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL) { throw new NotImplementedException(); } public void DeletePinvokeMap(uint tk) { throw new NotImplementedException(); } public uint DefineCustomAttribute(uint tkObj, uint tkType, IntPtr pCustomAttribute, uint cbCustomAttribute) { throw new NotImplementedException(); } public void SetCustomAttributeValue(uint pcv, IntPtr pCustomAttribute, uint cbCustomAttribute) { throw new NotImplementedException(); } public uint DefineField(uint td, string szName, uint dwFieldFlags, IntPtr pvSigBlob, uint cbSigBlob, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue) { throw new NotImplementedException(); } public uint DefineProperty(uint td, string szProperty, uint dwPropFlags, IntPtr pvSig, uint cbSig, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods) { throw new NotImplementedException(); } public uint DefineParam(uint md, uint ulParamSeq, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue) { throw new NotImplementedException(); } public void SetFieldProps(uint fd, uint dwFieldFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue) { throw new NotImplementedException(); } public void SetPropertyProps(uint pr, uint dwPropFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods) { throw new NotImplementedException(); } public void SetParamProps(uint pd, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue) { throw new NotImplementedException(); } public uint DefineSecurityAttributeSet(uint tkObj, IntPtr rSecAttrs, uint cSecAttrs) { throw new NotImplementedException(); } public void ApplyEditAndContinue(object pImport) { throw new NotImplementedException(); } public uint TranslateSigWithScope(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport import, IntPtr pbSigBlob, uint cbSigBlob, IntPtr pAssemEmit, IMetaDataEmit emit, IntPtr pvTranslatedSig, uint cbTranslatedSigMax) { throw new NotImplementedException(); } public void SetMethodImplFlags(uint md, uint dwImplFlags) { throw new NotImplementedException(); } public void SetFieldRVA(uint fd, uint ulRVA) { throw new NotImplementedException(); } public void Merge(IMetaDataImport pImport, IntPtr pHostMapToken, object pHandler) { throw new NotImplementedException(); } public void MergeEnd() { throw new NotImplementedException(); } public void CloseEnum(uint hEnum) { throw new NotImplementedException(); } public uint CountEnum(uint hEnum) { throw new NotImplementedException(); } public void ResetEnum(uint hEnum, uint ulPos) { throw new NotImplementedException(); } public uint EnumTypeDefs(ref uint phEnum, uint[] rTypeDefs, uint cMax) { throw new NotImplementedException(); } public uint EnumInterfaceImpls(ref uint phEnum, uint td, uint[] rImpls, uint cMax) { throw new NotImplementedException(); } public uint EnumTypeRefs(ref uint phEnum, uint[] rTypeRefs, uint cMax) { throw new NotImplementedException(); } public uint FindTypeDefByName(string szTypeDef, uint tkEnclosingClass) { throw new NotImplementedException(); } public Guid GetScopeProps(StringBuilder szName, uint cchName, out uint pchName) { throw new NotImplementedException(); } public uint GetModuleFromScope() { throw new NotImplementedException(); } public unsafe uint GetTypeDefProps(uint td, char* szTypeDef, uint cchTypeDef, uint* pchTypeDef, uint* pdwTypeDefFlags, uint* ptkExtends) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected I4, but got Unknown //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) if (!TryGetType(td, out var type)) { return 2147500037u; } string name = (((TypeReference)type).IsNested ? ((MemberReference)type).Name : ((MemberReference)type).FullName); WriteNameBuffer(name, szTypeDef, cchTypeDef, pchTypeDef); if (pdwTypeDefFlags != null) { *pdwTypeDefFlags = (uint)(int)type.Attributes; } if (ptkExtends != null) { int num; if (type.BaseType == null) { num = 0; } else { MetadataToken metadataToken = ((MemberReference)type.BaseType).MetadataToken; num = (int)((MetadataToken)(ref metadataToken)).ToUInt32(); } *ptkExtends = (uint)num; } return 0u; } public uint GetInterfaceImplProps(uint iiImpl, out uint pClass) { throw new NotImplementedException(); } public uint GetTypeRefProps(uint tr, out uint ptkResolutionScope, StringBuilder szName, uint cchName) { throw new NotImplementedException(); } public uint ResolveTypeRef(uint tr, ref Guid riid, out object ppIScope) { throw new NotImplementedException(); } public uint EnumMembers(ref uint phEnum, uint cl, uint[] rMembers, uint cMax) { throw new NotImplementedException(); } public uint EnumMembersWithName(ref uint phEnum, uint cl, string szName, uint[] rMembers, uint cMax) { throw new NotImplementedException(); } public uint EnumMethods(ref uint phEnum, uint cl, IntPtr rMethods, uint cMax) { throw new NotImplementedException(); } public uint EnumMethodsWithName(ref uint phEnum, uint cl, string szName, uint[] rMethods, uint cMax) { throw new NotImplementedException(); } public uint EnumFields(ref uint phEnum, uint cl, IntPtr rFields, uint cMax) { throw new NotImplementedException(); } public uint EnumFieldsWithName(ref uint phEnum, uint cl, string szName, uint[] rFields, uint cMax) { throw new NotImplementedException(); } public uint EnumParams(ref uint phEnum, uint mb, uint[] rParams, uint cMax) { throw new NotImplementedException(); } public uint EnumMemberRefs(ref uint phEnum, uint tkParent, uint[] rMemberRefs, uint cMax) { throw new NotImplementedException(); } public uint EnumMethodImpls(ref uint phEnum, uint td, uint[] rMethodBody, uint[] rMethodDecl, uint cMax) { throw new NotImplementedException(); } public uint EnumPermissionSets(ref uint phEnum, uint tk, uint dwActions, uint[] rPermission, uint cMax) { throw new NotImplementedException(); } public uint FindMember(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob) { throw new NotImplementedException(); } public uint FindMethod(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob) { throw new NotImplementedException(); } public uint FindField(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob) { throw new NotImplementedException(); } public uint FindMemberRef(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob) { throw new NotImplementedException(); } public unsafe uint GetMethodProps(uint mb, uint* pClass, char* szMethod, uint cchMethod, uint* pchMethod, uint* pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, uint* pulCodeRVA, uint* pdwImplFlags) { //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) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected I4, but got Unknown //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Expected I4, but got Unknown if (!TryGetMethod(mb, out var method)) { return 2147500037u; } if (pClass != null) { MetadataToken metadataToken = ((MemberReference)method.DeclaringType).MetadataToken; *pClass = ((MetadataToken)(ref metadataToken)).ToUInt32(); } WriteNameBuffer(((MemberReference)method).Name, szMethod, cchMethod, pchMethod); if (pdwAttr != null) { *pdwAttr = (uint)(int)method.Attributes; } if (pulCodeRVA != null) { *pulCodeRVA = (uint)method.RVA; } if (pdwImplFlags != null) { *pdwImplFlags = (uint)(int)method.ImplAttributes; } return 0u; } private unsafe static void WriteNameBuffer(string name, char* buffer, uint bufferLength, uint* actualLength) { long num = Math.Min(name.Length, bufferLength - 1); if (actualLength != null) { *actualLength = (uint)num; } if (buffer != null && bufferLength != 0) { for (int i = 0; i < num; i++) { buffer[i] = name[i]; } buffer[num + 1] = '\0'; } } public uint GetMemberRefProps(uint mr, ref uint ptk, StringBuilder szMember, uint cchMember, out uint pchMember, out IntPtr ppvSigBlob) { throw new NotImplementedException(); } public uint EnumProperties(ref uint phEnum, uint td, IntPtr rProperties, uint cMax) { throw new NotImplementedException(); } public uint EnumEvents(ref uint phEnum, uint td, IntPtr rEvents, uint cMax) { throw new NotImplementedException(); } public uint GetEventProps(uint ev, out uint pClass, StringBuilder szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, uint[] rmdOtherMethod, uint cMax) { throw new NotImplementedException(); } public uint EnumMethodSemantics(ref uint phEnum, uint mb, uint[] rEventProp, uint cMax) { throw new NotImplementedException(); } public uint GetMethodSemantics(uint mb, uint tkEventProp) { throw new NotImplementedException(); } public uint GetClassLayout(uint td, out uint pdwPackSize, IntPtr rFieldOffset, uint cMax, out uint pcFieldOffset) { throw new NotImplementedException(); } public uint GetFieldMarshal(uint tk, out IntPtr ppvNativeType) { throw new NotImplementedException(); } public uint GetRVA(uint tk, out uint pulCodeRVA) { throw new NotImplementedException(); } public uint GetPermissionSetProps(uint pm, out uint pdwAction, out IntPtr ppvPermission) { throw new NotImplementedException(); } public uint GetSigFromToken(uint mdSig, out IntPtr ppvSig) { throw new NotImplementedException(); } public uint GetModuleRefProps(uint mur, StringBuilder szName, uint cchName) { throw new NotImplementedException(); } public uint EnumModuleRefs(ref uint phEnum, uint[] rModuleRefs, uint cmax) { throw new NotImplementedException(); } public uint GetTypeSpecFromToken(uint typespec, out IntPtr ppvSig) { throw new NotImplementedException(); } public uint GetNameFromToken(uint tk) { throw new NotImplementedException(); } public uint EnumUnresolvedMethods(ref uint phEnum, uint[] rMethods, uint cMax) { throw new NotImplementedException(); } public uint GetUserString(uint stk, StringBuilder szString, uint cchString) { throw new NotImplementedException(); } public uint GetPinvokeMap(uint tk, out uint pdwMappingFlags, StringBuilder szImportName, uint cchImportName, out uint pchImportName) { throw new NotImplementedException(); } public uint EnumSignatures(ref uint phEnum, uint[] rSignatures, uint cmax) { throw new NotImplementedException(); } public uint EnumTypeSpecs(ref uint phEnum, uint[] rTypeSpecs, uint cmax) { throw new NotImplementedException(); } public uint EnumUserStrings(ref uint phEnum, uint[] rStrings, uint cmax) { throw new NotImplementedException(); } public int GetParamForMethodIndex(uint md, uint ulParamSeq, out uint pParam) { throw new NotImplementedException(); } public uint EnumCustomAttributes(ref uint phEnum, uint tk, uint tkType, uint[] rCustomAttributes, uint cMax) { throw new NotImplementedException(); } public uint GetCustomAttributeProps(uint cv, out uint ptkObj, out uint ptkType, out IntPtr ppBlob) { throw new NotImplementedException(); } public uint FindTypeRef(uint tkResolutionScope, string szName) { throw new NotImplementedException(); } public uint GetMemberProps(uint mb, out uint pClass, StringBuilder szMember, uint cchMember, out uint pchMember, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out IntPtr ppValue) { throw new NotImplementedException(); } public uint GetFieldProps(uint mb, out uint pClass, StringBuilder szField, uint cchField, out uint pchField, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out IntPtr ppValue) { throw new NotImplementedException(); } public uint GetPropertyProps(uint prop, out uint pClass, StringBuilder szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out IntPtr ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out IntPtr ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, uint[] rmdOtherMethod, uint cMax) { throw new NotImplementedException(); } public uint GetParamProps(uint tk, out uint pmd, out uint pulSequence, StringBuilder szName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out IntPtr ppValue) { throw new NotImplementedException(); } public uint GetCustomAttributeByName(uint tkObj, string szName, out IntPtr ppData) { throw new NotImplementedException(); } public bool IsValidToken(uint tk) { throw new NotImplementedException(); } public unsafe uint GetNestedClassProps(uint tdNestedClass, uint* ptdEnclosingClass) { //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) if (!TryGetType(tdNestedClass, out var type)) { return 2147500037u; } if (ptdEnclosingClass != null) { int num; if (!((TypeReference)type).IsNested) { num = 0; } else { MetadataToken metadataToken = ((MemberReference)type.DeclaringType).MetadataToken; num = (int)((MetadataToken)(ref metadataToken)).ToUInt32(); } *ptdEnclosingClass = (uint)num; } return 0u; } public uint GetNativeCallConvFromSig(IntPtr pvSig, uint cbSig) { throw new NotImplementedException(); } public int IsGlobal(uint pd) { throw new NotImplementedException(); } } public class NativePdbReader : ISymbolReader, IDisposable { private readonly Disposable<Stream> pdb_file; private readonly Dictionary<string, Document> documents = new Dictionary<string, Document>(); private readonly Dictionary<uint, PdbFunction> functions = new Dictionary<uint, PdbFunction>(); private readonly Dictionary<PdbScope, ImportDebugInformation> imports = new Dictionary<PdbScope, ImportDebugInformation>(); internal NativePdbReader(Disposable<Stream> file) { //IL_002a: 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) pdb_file = file; } public ISymbolWriterProvider GetWriterProvider() { return (ISymbolWriterProvider)(object)new NativePdbWriterProvider(); } public bool ProcessDebugHeader(ImageDebugHeader header) { //IL_0016: 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) if (!header.HasEntries) { return false; } Disposable<Stream> val = pdb_file; try { PdbInfo pdbInfo = PdbFile.LoadFunctions(pdb_file.value); ImageDebugHeaderEntry[] entries = header.Entries; foreach (ImageDebugHeaderEntry entry in entries) { if (IsMatchingEntry(pdbInfo, entry)) { PdbFunction[] array = pdbInfo.Functions; foreach (PdbFunction pdbFunction in array) { functions.Add(pdbFunction.token, pdbFunction); } return true; } } } finally { ((IDisposable)val).Dispose(); } return false; } private static bool IsMatchingEntry(PdbInfo info, ImageDebugHeaderEntry entry) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 if ((int)entry.Directory.Type != 2) { return false; } byte[] data = entry.Data; if (data.Length < 24) { return false; } int num = ReadInt32(data, 0); if (num != 1396986706) { return false; } byte[] array = new byte[16]; Buffer.BlockCopy(data, 4, array, 0, 16); return info.Guid == new Guid(array); } private static int ReadInt32(byte[] bytes, int start) { return bytes[start] | (bytes[start + 1] << 8) | (bytes[start + 2] << 16) | (bytes[start + 3] << 24); } public MethodDebugInformation Read(MethodDefinition method) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: 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_0032: Expected O, but got Unknown //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Expected O, but got Unknown //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01e5: Expected O, but got Unknown //IL_020e: 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_0274: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Expected O, but got Unknown //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Expected O, but got Unknown MetadataToken metadataToken = ((MemberReference)method).MetadataToken; if (!functions.TryGetValue(((MetadataToken)(ref metadataToken)).ToUInt32(), out var value)) { return null; } MethodDebugInformation val = new MethodDebugInformation(method); ReadSequencePoints(value, val); val.scope = (ScopeDebugInformation)((!Mixin.IsNullOrEmpty<PdbScope>(value.scopes)) ? ((object)ReadScopeAndLocals(value.scopes[0], val)) : ((object)new ScopeDebugInformation { Start = new InstructionOffset(0), End = new InstructionOffset((int)value.length) })); uint tokenOfMethodWhoseUsingInfoAppliesToThisMethod = value.tokenOfMethodWhoseUsingInfoAppliesToThisMethod; MetadataToken metadataToken2 = ((MemberReference)method).MetadataToken; if (tokenOfMethodWhoseUsingInfoAppliesToThisMethod != ((MetadataToken)(ref metadataToken2)).ToUInt32() && value.tokenOfMethodWhoseUsingInfoAppliesToThisMethod != 0) { val.scope.import = GetImport(value.tokenOfMethodWhoseUsingInfoAppliesToThisMethod, ((MemberReference)method).Module); } if (value.scopes.Length > 1) { for (int i = 1; i < value.scopes.Length; i++) { ScopeDebugInformation val2 = ReadScopeAndLocals(value.scopes[i], val); if (!AddScope(val.scope.Scopes, val2)) { val.scope.Scopes.Add(val2); } } } if (value.iteratorScopes != null) { StateMachineScopeDebugInformation val3 = new StateMachineScopeDebugInformation(); foreach (ILocalScope iteratorScope in value.iteratorScopes) { val3.Scopes.Add(new StateMachineScope((int)iteratorScope.Offset, (int)(iteratorScope.Offset + iteratorScope.Length + 1))); } ((DebugInformation)val).CustomDebugInformations.Add((CustomDebugInformation)(object)val3); } if (value.synchronizationInformation != null) { AsyncMethodBodyDebugInformation val4 = new AsyncMethodBodyDebugInformation((int)value.synchronizationInformation.GeneratedCatchHandlerOffset); PdbSynchronizationPoint[] synchronizationPoints = value.synchronizationInformation.synchronizationPoints; foreach (PdbSynchronizationPoint pdbSynchronizationPoint in synchronizationPoints) { val4.Yields.Add(new InstructionOffset((int)pdbSynchronizationPoint.SynchronizeOffset)); val4.Resumes.Add(new InstructionOffset((int)pdbSynchronizationPoint.ContinuationOffset)); val4.ResumeMethods.Add(method); } ((DebugInformation)val).CustomDebugInformations.Add((CustomDebugInformation)(object)val4); val.StateMachineKickOffMethod = (MethodDefinition)((MemberReference)method).Module.LookupToken((int)value.synchronizationInformation.kickoffMethodToken); } return val; } private Collection<ScopeDebugInformation> ReadScopeAndLocals(PdbScope[] scopes, MethodDebugInformation info) { Collection<ScopeDebugInformation> val = new Collection<ScopeDebugInformation>(scopes.Length); foreach (PdbScope pdbScope in scopes) { if (pdbScope != null) { val.Add(ReadScopeAndLocals(pdbScope, info)); } } return val; } private ScopeDebugInformation ReadScopeAndLocals(PdbScope scope, MethodDebugInformation info) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0027: 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_009a: Expected O, but got Unknown //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Expected O, but got Unknown ScopeDebugInformation val = new ScopeDebugInformation(); val.Start = new InstructionOffset((int)scope.offset); val.End = new InstructionOffset((int)(scope.offset + scope.length)); if (!Mixin.IsNullOrEmpty<PdbSlot>(scope.slots)) { val.variables = new Collection<VariableDebugInformation>(scope.slots.Length); PdbSlot[] slots = scope.slots; foreach (PdbSlot pdbSlot in slots) { if ((pdbSlot.flags & 1) == 0) { int slot = (int)pdbSlot.slot; VariableDebugInformation val2 = new VariableDebugInformation(slot, pdbSlot.name); if ((pdbSlot.flags & 4u) != 0) { val2.IsDebuggerHidden = true; } val.variables.Add(val2); } } } if (!Mixin.IsNullOrEmpty<PdbConstant>(scope.constants)) { val.constants = new Collection<ConstantDebugInformation>(scope.constants.Length); PdbConstant[] constants = scope.constants; foreach (PdbConstant pdbConstant in constants) { TypeReference val3 = ((MemberReference)info.Method).Module.Read<PdbConstant, TypeReference>(pdbConstant, (Func<PdbConstant, MetadataReader, TypeReference>)((PdbConstant c, MetadataReader r) => r.ReadConstantSignature(new MetadataToken(c.token)))); object obj = pdbConstant.value; if (val3 != null && !val3.IsValueType && obj is int && (int)obj == 0) { obj = null; } val.constants.Add(new ConstantDebugInformation(pdbConstant.name, val3, obj)); } } if (!Mixin.IsNullOrEmpty<string>(scope.usedNamespaces)) { if (imports.TryGetValue(scope, out var value)) { val.import = value; } else { value = GetImport(scope, ((MemberReference)info.Method).Module); imports.Add(scope, value); val.import = value; } } val.scopes = ReadScopeAndLocals(scope.scopes, info); return val; } private static bool AddScope(Collection<ScopeDebugInformation> scopes, ScopeDebugInformation scope) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0008: 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_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) Enumerator<ScopeDebugInformation> enumerator = scopes.GetEnumerator(); try { while (enumerator.MoveNext()) { ScopeDebugInformation current = enumerator.Current; if (current.HasScopes && AddScope(current.Scopes, scope)) { return true; } InstructionOffset val = scope.Start; int offset = ((InstructionOffset)(ref val)).Offset; val = current.Start; if (offset >= ((InstructionOffset)(ref val)).Offset) { val = scope.End; int offset2 = ((InstructionOffset)(ref val)).Offset; val = current.End; if (offset2 <= ((InstructionOffset)(ref val)).Offset) { current.Scopes.Add(scope); return true; } } } } finally { ((IDisposable)enumerator).Dispose(); } return false; } private ImportDebugInformation GetImport(uint token, ModuleDefinition module) { if (!functions.TryGetValue(token, out var value)) { return null; } if (value.scopes.Length != 1) { return null; } PdbScope pdbScope = value.scopes[0]; if (imports.TryGetValue(pdbScope, out var value2)) { return value2; } value2 = GetImport(pdbScope, module); imports.Add(pdbScope, value2); return value2; } private static ImportDebugInformation GetImport(PdbScope scope, ModuleDefinition module) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown //IL_0192: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Expected O, but got Unknown //IL_00f4: 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_0103: Expected O, but got Unknown //IL_0176: 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_0183: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Expected O, but got Unknown //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Expected O, but got Unknown //IL_01bb: 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_01d0: Expected O, but got Unknown //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Expected O, but got Unknown //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown if (Mixin.IsNullOrEmpty<string>(scope.usedNamespaces)) { return null; } ImportDebugInformation val = new ImportDebugInformation(); string[] usedNamespaces = scope.usedNamespaces; foreach (string text in usedNamespaces) { if (string.IsNullOrEmpty(text)) { continue; } ImportTarget val2 = null; string text2 = text.Substring(1); switch (text[0]) { case 'U': val2 = new ImportTarget((ImportTargetKind)1) { @namespace = text2 }; break; case 'T': { TypeReference val4 = TypeParser.ParseType(module, text2, false); if (val4 != null) { val2 = new ImportTarget((ImportTargetKind)3) { type = val4 }; } break; } case 'A': { int num = text.IndexOf(' '); if (num < 0) { val2 = new ImportTarget((ImportTargetKind)1) { @namespace = text }; break; } string alias = text.Substring(1, num - 1); string text3 = text.Substring(num + 2); switch (text[num + 1]) { case 'U': val2 = new ImportTarget((ImportTargetKind)7) { alias = alias, @namespace = text3 }; break; case 'T': { TypeReference val3 = TypeParser.ParseType(module, text3, false); if (val3 != null) { val2 = new ImportTarget((ImportTargetKind)9) { alias = alias, type = val3 }; } break; } } break; } case '*': val2 = new ImportTarget((ImportTargetKind)1) { @namespace = text2 }; break; case '@': if (!text2.StartsWith("P:")) { continue; } val2 = new ImportTarget((ImportTargetKind)1) { @namespace = text2.Substring(2) }; break; } if (val2 != null) { val.Targets.Add(val2); } } return val; } private void ReadSequencePoints(PdbFunction function, MethodDebugInformation info) { if (function.lines != null) { info.sequence_points = new Collection<SequencePoint>(); PdbLines[] lines = function.lines; foreach (PdbLines lines2 in lines) { ReadLines(lines2, info); } } } private void ReadLines(PdbLines lines, MethodDebugInformation info) { Document document = GetDocument(lines.file); PdbLine[] lines2 = lines.lines; foreach (PdbLine line in lines2) { ReadLine(line, document, info); } } private static void ReadLine(PdbLine line, Document document, MethodDebugInformation info) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown SequencePoint val = new SequencePoint((int)line.offset, document); val.StartLine = (int)line.lineBegin; val.StartColumn = line.colBegin; val.EndLine = (int)line.lineEnd; val.EndColumn = line.colEnd; info.sequence_points.Add(val); } private Document GetDocument(PdbSource source) { //IL_001f: 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_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Expected O, but got Unknown string name = source.name; if (documents.TryGetValue(name, out var value)) { return value; } value = new Document(name) { LanguageGuid = source.language, LanguageVendorGuid = source.vendor, TypeGuid = source.doctype, HashAlgorithmGuid = source.checksumAlgorithm, Hash = source.checksum }; documents.Add(name, value); return value; } public Collection<CustomDebugInformation> Read(ICustomDebugInformationProvider provider) { return new Collection<CustomDebugInformation>(); } public void Dispose() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) pdb_file.Dispose(); } } public class NativePdbWriter : ISymbolWriter, IDisposable { private readonly ModuleDefinition module; private readonly MetadataBuilder metadata; private readonly SymWriter writer; private readonly Dictionary<string, SymDocumentWriter> documents; private readonly Dictionary<ImportDebugInformation, MetadataToken> import_info_to_parent; private ImageDebugDirectory debug_directory; private byte[] debug_info; internal NativePdbWriter(ModuleDefinition module, SymWriter writer) { this.module = module; metadata = module.metadata_builder; this.writer = writer; documents = new Dictionary<string, SymDocumentWriter>(); import_info_to_parent = new Dictionary<ImportDebugInformation, MetadataToken>(); } public ISymbolReaderProvider GetReaderProvider() { return (ISymbolReaderProvider)(object)new NativePdbReaderProvider(); } public ImageDebugHeader GetDebugHeader() { //IL_0002: 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_0017: Expected O, but got Unknown //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown return new ImageDebugHeader(new ImageDebugHeaderEntry(debug_directory, debug_info)); } public void Write(MethodDebugInformation info) { //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_006f: 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) MetadataToken metadataToken = ((MemberReference)info.method).MetadataToken; int methodToken = ((MetadataToken)(ref metadataToken)).ToInt32(); if (info.HasSequencePoints || info.scope != null || ((DebugInformation)info).HasCustomDebugInformations || info.StateMachineKickOffMethod != null) { writer.OpenMethod(methodToken); if (!Mixin.IsNullOrEmpty<SequencePoint>(info.sequence_points)) { DefineSequencePoints(info.sequence_points); } MetadataToken import_parent = default(MetadataToken); if (info.scope != null) { DefineScope(info.scope, info, out import_parent); } DefineCustomMetadata(info, import_parent); writer.CloseMethod(); } } private void DefineCustomMetadata(MethodDebugInformation info, MetadataToken import_parent) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) CustomMetadataWriter customMetadataWriter = new CustomMetadataWriter(writer); if (((MetadataToken)(ref import_parent)).RID != 0) { customMetadataWriter.WriteForwardInfo(import_parent); } else if (info.scope != null && info.scope.Import != null && info.scope.Import.HasTargets) { customMetadataWriter.WriteUsingInfo(info.scope.Import); } if (info.Method.HasCustomAttributes) { Enumerator<CustomAttribute> enumerator = info.Method.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; TypeReference attributeType = current.AttributeType; if (Mixin.IsTypeOf(attributeType, "System.Runtime.CompilerServices", "IteratorStateMachineAttribute") || Mixin.IsTypeOf(attributeType, "System.Runtime.CompilerServices", "AsyncStateMachineAttribute")) { CustomAttributeArgument val = current.ConstructorArguments[0]; object value = ((CustomAttributeArgument)(ref val)).Value; TypeReference val2 = (TypeReference)((value is TypeReference) ? value : null); if (val2 != null) { customMetadataWriter.WriteForwardIterator(val2); } } } } finally { ((IDisposable)enumerator).Dispose(); } } if (((DebugInformation)info).HasCustomDebugInformations) { CustomDebugInformation? obj = ((IEnumerable<CustomDebugInformation>)((DebugInformation)info).CustomDebugInformations).FirstOrDefault((Func<CustomDebugInformation, bool>)((CustomDebugInformation cdi) => (int)cdi.Kind == 1)); StateMachineScopeDebugInformation val3 = (StateMachineScopeDebugInformation)(object)((obj is StateMachineScopeDebugInformation) ? obj : null); if (val3 != null) { customMetadataWriter.WriteIteratorScopes(val3, info); } } customMetadataWriter.WriteCustomMetadata(); DefineAsyncCustomMetadata(info); } private void DefineAsyncCustomMetadata(MethodDebugInformation info) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Expected O, but got Unknown //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) if (!((DebugInformation)info).HasCustomDebugInformations) { return; } Enumerator<CustomDebugInformation> enumerator = ((DebugInformation)info).CustomDebugInformations.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomDebugInformation current = enumerator.Current; AsyncMethodBodyDebugInformation val = (AsyncMethodBodyDebugInformation)(object)((current is AsyncMethodBodyDebugInformation) ? current : null); if (val == null) { continue; } using MemoryStream memoryStream = new MemoryStream(); BinaryStreamWriter val2 = new BinaryStreamWriter((Stream)memoryStream); int num; MetadataToken metadataToken; if (info.StateMachineKickOffMethod == null) { num = 0; } else { metadataToken = ((MemberReference)info.StateMachineKickOffMethod).MetadataToken; num = (int)((MetadataToken)(ref metadataToken)).ToUInt32(); } val2.WriteUInt32((uint)num); InstructionOffset val3 = val.CatchHandler; val2.WriteUInt32((uint)((InstructionOffset)(ref val3)).Offset); val2.WriteUInt32((uint)val.Resumes.Count); for (int i = 0; i < val.Resumes.Count; i++) { val3 = val.Yields[i]; val2.WriteUInt32((uint)((InstructionOffset)(ref val3)).Offset); metadataToken = ((MemberReference)val.resume_methods[i]).MetadataToken; val2.WriteUInt32(((MetadataToken)(ref metadataToken)).ToUInt32()); val3 = val.Resumes[i]; val2.WriteUInt32((uint)((InstructionOffset)(ref val3)).Offset); } writer.DefineCustomMetadata("asyncMethodInfo", memoryStream.ToArray()); } } finally { ((IDisposable)enumerator).Dispose(); } } private void DefineScope(ScopeDebugInformation scope, MethodDebugInformation info, out MetadataToken import_parent) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: 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_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //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_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Invalid comparison between Unknown and I4 //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Invalid comparison between Unknown and I4 //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Invalid comparison between Unknown and I4 //IL_01bb: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Invalid comparison between Unknown and I4 //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Invalid comparison between Unknown and I4 InstructionOffset val = scope.Start; int offset = ((InstructionOffset)(ref val)).Offset; val = scope.End; int num; if (!((InstructionOffset)(ref val)).IsEndOfMethod) { val = scope.End; num = ((InstructionOffset)(ref val)).Offset; } else { num = info.code_size; } int num2 = num; import_parent = new MetadataToken(0u); writer.OpenScope(offset); if (scope.Import != null && scope.Import.HasTargets && !import_info_to_parent.TryGetValue(info.scope.Import, out import_parent)) { Enumerator<ImportTarget> enumerator = scope.Import.Targets.GetEnumerator(); try { while (enumerator.MoveNext()) { ImportTarget current = enumerator.Current; ImportTargetKind kind = current.Kind; ImportTargetKind val2 = kind; if ((int)val2 <= 3) { if ((int)val2 != 1) { if ((int)val2 == 3) { writer.UsingNamespace("T" + TypeParser.ToParseable(current.type, true)); } } else { writer.UsingNamespace("U" + current.@namespace); } } else if ((int)val2 != 7) { if ((int)val2 == 9) { writer.UsingNamespace("A" + current.Alias + " T" + TypeParser.ToParseable(current.type, true)); } } else { writer.UsingNamespace("A" + current.Alias + " U" + current.@namespace); } } } finally { ((IDisposable)enumerator).Dispose(); } import_info_to_parent.Add(info.scope.Import, ((MemberReference)info.method).MetadataToken); } int local_var_token = ((MetadataToken)(ref info.local_var_token)).ToInt32(); if (!Mixin.IsNullOrEmpty<VariableDebugInformation>(scope.variables)) { for (int i = 0; i < scope.variables.Count; i++) { VariableDebugInformation variable = scope.variables[i]; DefineLocalVariable(variable, local_var_token, offset, num2); } } if (!Mixin.IsNullOrEmpty<ConstantDebugInformation>(scope.constants)) { for (int j = 0; j < scope.constants.Count; j++) { ConstantDebugInformation constant = scope.constants[j]; DefineConstant(constant); } } if (!Mixin.IsNullOrEmpty<ScopeDebugInformation>(scope.scopes)) { for (int k = 0; k < scope.scopes.Count; k++) { DefineScope(scope.scopes[k], info, out var _); } } writer.CloseScope(num2); } private void DefineSequencePoints(Collection<SequencePoint> sequence_points) { for (int i = 0; i < sequence_points.Count; i++) { SequencePoint val = sequence_points[i]; writer.DefineSequencePoints(GetDocument(val.Document), new int[1] { val.Offset }, new int[1] { val.StartLine }, new int[1] { val.StartColumn }, new int[1] { val.EndLine }, new int[1] { val.EndColumn }); } } private void DefineLocalVariable(VariableDebugInformation variable, int local_var_token, int start_offset, int end_offset) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) writer.DefineLocalVariable2(variable.Name, variable.Attributes, local_var_token, variable.Index, 0, 0, start_offset, end_offset); } private void DefineConstant(ConstantDebugInformation constant) { uint num = metadata.AddStandAloneSignature(metadata.GetConstantTypeBlobIndex(constant.ConstantType)); MetadataToken val = default(MetadataToken); ((MetadataToken)(ref val))..ctor((TokenType)285212672, num); writer.DefineConstant2(constant.Name, constant.Value, ((MetadataToken)(ref val)).ToInt32()); } private SymDocumentWriter GetDocument(Document document) { if (document == null) { return null; } if (documents.TryGetValue(document.Url, out var value)) { return value; } value = writer.DefineDocument(document.Url, document.LanguageGuid, document.LanguageVendorGuid, document.TypeGuid); if (!Mixin.IsNullOrEmpty<byte>(document.Hash)) { value.SetCheckSum(document.HashAlgorithmGuid, document.Hash); } documents[document.Url] = value; return value; } public void Write() { //IL_001c: 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) MethodDefinition entryPoint = module.EntryPoint; if (entryPoint != null) { SymWriter symWriter = writer; MetadataToken metadataToken = ((MemberReference)entryPoint).MetadataToken; symWriter.SetUserEntryPoint(((MetadataToken)(ref metadataToken)).ToInt32()); } debug_info = writer.GetDebugInfo(out debug_directory); debug_directory.TimeDateStamp = (int)module.timestamp; writer.Close(); } public void Write(ICustomDebugInformationProvider provider) { } public void Dispose() { writer.Close(); } } internal enum CustomMetadataType : byte { UsingInfo = 0, ForwardInfo = 1, IteratorScopes = 3, ForwardIterator = 4 } internal class CustomMetadataWriter : IDisposable { private readonly SymWriter sym_writer; private readonly MemoryStream stream; private readonly BinaryStreamWriter writer; private int count; private const byte version = 4; public CustomMetadataWriter(SymWriter sym_writer) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown this.sym_writer = sym_writer; stream = new MemoryStream(); writer = new BinaryStreamWriter((Stream)stream); writer.WriteByte((byte)4); writer.WriteByte((byte)0); writer.Align(4); } public void WriteUsingInfo(ImportDebugInformation import_info) { Write(CustomMetadataType.UsingInfo, delegate { writer.WriteUInt16((ushort)1); writer.WriteUInt16((ushort)import_info.Targets.Count); }); } public void WriteForwardInfo(MetadataToken import_parent) { //IL_000e: 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) Write(CustomMetadataType.ForwardInfo, delegate { writer.WriteUInt32(((MetadataToken)(ref import_parent)).ToUInt32()); }); } public void WriteIteratorScopes(StateMachineScopeDebugInformation state_machine, MethodDebugInformation debug_info) { Write(CustomMetadataType.IteratorScopes, delegate { //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) //IL_0038: 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_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) Collection<StateMachineScope> scopes = state_machine.Scopes; writer.WriteInt32(scopes.Count); Enumerator<StateMachineScope> enumerator = scopes.GetEnumerator(); try { while (enumerator.MoveNext()) { StateMachineScope current = enumerator.Current; InstructionOffset val = current.Start; int offset = ((InstructionOffset)(ref val)).Offset; val = current.End; int num; if (!((InstructionOffset)(ref val)).IsEndOfMethod) { val = current.End; num = ((InstructionOffset)(ref val)).Offset; } else { num = debug_info.code_size; } int num2 = num; writer.WriteInt32(offset); writer.WriteInt32(num2 - 1); } } finally { ((IDisposable)enumerator).Dispose(); } }); } public void WriteForwardIterator(TypeReference type) { Write(CustomMetadataType.ForwardIterator, delegate { writer.WriteBytes(Encoding.Unicode.GetBytes(((MemberReference)type).Name)); }); } private void Write(CustomMetadataType type, Action write) { count++; writer.WriteByte((byte)4); writer.WriteByte((byte)type); writer.Align(4); int position = writer.Position; writer.WriteUInt32(0u); write(); writer.Align(4); int position2 = writer.Position; int num = position2 - position + 4; writer.Position = position; writer.WriteInt32(num); writer.Position = position2; } public void WriteCustomMetadata() { if (count != 0) { ((BinaryWriter)(object)writer).BaseStream.Position = 1L; writer.WriteByte((byte)count); ((BinaryWriter)(object)writer).Flush(); sym_writer.DefineCustomMetadata("MD2", stream.ToArray()); } } public void Dispose() { stream.Dispose(); } } public sealed class NativePdbReaderProvider : ISymbolReaderProvider { public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) Mixin.CheckModule(module); Mixin.CheckFileName(fileName); return (ISymbolReader)(object)new NativePdbReader(Disposable.Owned<Stream>((Stream)File.OpenRead(Mixin.GetPdbFileName(fileName)))); } public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) Mixin.CheckModule(module); Mixin.CheckStream((object)symbolStream); return (ISymbolReader)(object)new NativePdbReader(Disposable.NotOwned<Stream>(symbolStream)); } } public sealed class PdbReaderProvider : ISymbolReaderProvider { public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName) { //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) Mixin.CheckModule(module); if (module.HasDebugHeader) { ImageDebugHeader debugHeader = module.GetDebugHeader(); ImageDebugHeaderEntry embeddedPortablePdbEntry = Mixin.GetEmbeddedPortablePdbEntry(debugHeader); if (embeddedPortablePdbEntry != null) { return new EmbeddedPortablePdbReaderProvider().GetSymbolReader(module, fileName); } } Mixin.CheckFileName(fileName); return Mixin.IsPortablePdb(Mixin.GetPdbFileName(fileName)) ? new PortablePdbReaderProvider().GetSymbolReader(module, fileName) : new NativePdbReaderProvider().GetSymbolReader(module, fileName); } public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) Mixin.CheckModule(module); Mixin.CheckStream((object)symbolStream); Mixin.CheckReadSeek(symbolStream); return Mixin.IsPortablePdb(symbolStream) ? new PortablePdbReaderProvider().GetSymbolReader(module, symbolStream) : new NativePdbReaderProvider().GetSymbolReader(module, symbolStream); } } public sealed class NativePdbWriterProvider : ISymbolWriterProvider { public ISymbolWriter GetSymbolWriter(ModuleDefinition module, string fileName) { Mixin.CheckModule(module); Mixin.CheckFileName(fileName); return (ISymbolWriter)(object)new NativePdbWriter(module, CreateWriter(module, Mixin.GetPdbFileName(fileName))); } private static SymWriter CreateWriter(ModuleDefinition module, string pdb) { SymWriter symWriter = new SymWriter(); if (File.Exists(pdb)) { File.Delete(pdb); } symWriter.Initialize(new ModuleMetadata(module), pdb, fFullBuild: true); return symWriter; } public ISymbolWriter GetSymbolWriter(ModuleDefinition module, Stream symbolStream) { throw new NotImplementedException(); } } public sealed class PdbWriterProvider : ISymbolWriterProvider { public ISymbolWriter GetSymbolWriter(ModuleDefinition module, string fileName) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) Mixin.CheckModule(module); Mixin.CheckFileName(fileName); if (HasPortablePdbSymbols(module)) { return new PortablePdbWriterProvider().GetSymbolWriter(module, fileName); } return new NativePdbWriterProvider().GetSymbolWriter(module, fileName); } private static bool HasPortablePdbSymbols(ModuleDefinition module) { return module.symbol_reader != null && module.symbol_reader is PortablePdbReader; } public ISymbolWriter GetSymbolWriter(ModuleDefinition module, Stream symbolStream) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) Mixin.CheckModule(module); Mixin.CheckStream((object)symbolStream); Mixin.CheckReadSeek(symbolStream); if (HasPortablePdbSymbols(module)) { return new PortablePdbWriterProvider().GetSymbolWriter(module, symbolStream); } return new NativePdbWriterProvider().GetSymbolWriter(module, symbolStream); } } internal class SymDocumentWriter { private readonly ISymUnmanagedDocumentWriter writer; public ISymUnmanagedDocumentWriter Writer => writer; public SymDocumentWriter(ISymUnmanagedDocumentWriter writer) { this.writer = writer; } public void SetSource(byte[] source) { writer.SetSource((uint)source.Length, source); } public void SetCheckSum(Guid hashAlgo, byte[] checkSum) { writer.SetCheckSum(hashAlgo, (uint)checkSum.Length, checkSum); } } internal class SymWriter { private static Guid s_symUnmangedWriterIID = new Guid("0b97726e-9e6d-4f05-9a26-424022093caa"); private static Guid s_CorSymWriter_SxS_ClassID = new Guid("108296c1-281e-11d3-bd22-0000f80849bd"); private readonly ISymUnmanagedWriter2 writer; private readonly Collection<ISymUnmanagedDocumentWriter> documents; private bool closed = false; [DllImport("ole32.dll")] private static extern int CoCreateInstance([In] ref Guid rclsid, [In][MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter, [In] uint dwClsContext, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppv); public SymWriter() { CoCreateInstance(ref s_CorSymWriter_SxS_ClassID, null, 1u, ref s_symUnmangedWriterIID, out var ppv); writer = (ISymUnmanagedWriter2)ppv; documents = new Collection<ISymUnmanagedDocumentWriter>(); } public byte[] GetDebugInfo(out ImageDebugDirectory idd) { writer.GetDebugInfo(out idd, 0, out var pcData, null); byte[] array = new byte[pcData]; writer.GetDebugInfo(out idd, pcData, out pcData, array); return array; } public void DefineLocalVariable2(string name, VariableAttributes attributes, int sigToken, int addr1, int addr2, int addr3, int startOffset, int endOffset) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected I4, but got Unknown writer.DefineLocalVariable2(name, (int)attributes, sigToken, 1, addr1, addr2, addr3, startOffset, endOffset); } public void DefineConstant2(string name, object value, int sigToken) { if (value == null) { writer.DefineConstant2(name, 0, sigToken); } else { writer.DefineConstant2(name, value, sigToken); } } public void Close() { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) if (closed) { return; } closed = true; writer.Close(); Marshal.ReleaseComObject(writer); Enumerator<ISymUnmanagedDocumentWriter> enumerator = documents.GetEnumerator(); try { while (enumerator.MoveNext()) { ISymUnmanagedDocumentWriter current = enumerator.Current; Marshal.ReleaseComObject(current); } } finally { ((IDisposable)enumerator).Dispose(); } } public void CloseMethod() { writer.CloseMethod(); } public void CloseNamespace() { writer.CloseNamespace(); } public void CloseScope(int endOffset) { writer.CloseScope(endOffset); } public SymDocumentWriter DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType) { writer.DefineDocument(url, ref language, ref languageVendor, ref documentType, out var pRetVal); documents.Add(pRetVal); return new SymDocumentWriter(pRetVal); } public void DefineSequencePoints(SymDocumentWriter document, int[] offsets, int[] lines, int[] columns, int[] endLines, int[] endColumns) { writer.DefineSequencePoints(document.Writer, offsets.Length, offsets, lines, columns, endLines, endColumns); } public void Initialize(object emitter, string filename, bool fFullBuild) { writer.Initialize(emitter, filename, null, fFullBuild); } public void SetUserEntryPoint(int methodToken) { writer.SetUserEntryPoint(methodToken); } public void OpenMethod(int methodToken) { writer.OpenMethod(methodToken); } public void OpenNamespace(string name) { writer.OpenNamespace(name); } public int OpenScope(int startOffset) { writer.OpenScope(startOffset, out var pRetVal); return pRetVal; } public void UsingNamespace(string fullName) { writer.UsingNamespace(fullName); } public void DefineCustomMetadata(string name, byte[] metadata) { GCHandle gCHandle = GCHandle.Alloc(metadata, GCHandleType.Pinned); writer.SetSymAttribute(0u, name, (uint)metadata.Length, gCHandle.AddrOfPinnedObject()); gCHandle.Free(); } } } namespace Microsoft.Cci.Pdb { internal class BitAccess { private byte[] buffer; private int offset; internal byte[] Buffer => buffer; internal int Position { get { return offset; } set { offset = value; } } internal BitAccess(int capacity) { buffer = new byte[capacity]; } internal BitAccess(byte[] buffer) { this.buffer = buffer; offset = 0; } internal void FillBuffer(Stream stream, int capacity) { MinCapacity(capacity); stream.Read(buffer, 0, capacity); offset = 0; } internal void Append(Stream stream, int count) { int num = offset + count; if (buffer.Length < num) { byte[] destinationArray = new byte[num]; Array.Copy(buffer, destinationArray, buffer.Length); buffer = destinationArray; } stream.Read(buffer, offset, count); offset += count; } internal void MinCapacity(int capacity) { if (buffer.Length < capacity) { buffer = new byte[capacity]; } offset = 0; } internal void Align(int alignment) { while (offset % alignment != 0) { offset++; } } internal void ReadInt16(out short value) { value = (short)((buffer[offset] & 0xFF) | (buffer[offset + 1] << 8)); offset += 2; } internal void ReadInt8(out sbyte value) { value = (sbyte)buffer[offset]; offset++; } internal void ReadInt32(out int value) { value = (buffer[offset] & 0xFF) | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24); offset += 4; } internal void ReadInt64(out long value) { value = ((long)buffer[offset] & 0xFFL) | (long)((ulong)buffer[offset + 1] << 8) | (long)((ulong)buffer[offset + 2] << 16) | (long)((ulong)buffer[offset + 3] << 24) | (long)((ulong)buffer[offset + 4] << 32) | (long)((ulong)buffer[offset + 5] << 40) | (long)((ulong)buffer[offset + 6] << 48) | (long)((ulong)buffer[offset + 7] << 56); offset += 8; } internal void ReadUInt16(out ushort value) { value = (ushort)((buffer[offset] & 0xFFu) | (uint)(buffer[offset + 1] << 8)); offset += 2; } internal void ReadUInt8(out byte value) { value = (byte)(buffer[offset] & 0xFFu); offset++; } internal void ReadUInt32(out uint value) { value = (buffer[offset] & 0xFFu) | (uint)(buffer[offset + 1] << 8) | (uint)(buffer[offset + 2] << 16) | (uint)(buffer[offset + 3] << 24); offset += 4; } internal void ReadUInt64(out ulong value) { value = ((ulong)buffer[offset] & 0xFFuL) | ((ulong)buffer[offset + 1] << 8) | ((ulong)buffer[offset + 2] << 16) | ((ulong)buffer[offset + 3] << 24) | ((ulong)buffer[offset + 4] << 32) | ((ulong)buffer[offset + 5] << 40) | ((ulong)buffer[offset + 6] << 48) | ((ulong)buffer[offset + 7] << 56); offset += 8; } internal void ReadInt32(int[] values) { for (int i = 0; i < values.Length; i++) { ReadInt32(out values[i]); } } internal void ReadUInt32(uint[] values) { for (int i = 0; i < values.Length; i++) { ReadUInt32(out values[i]); } } internal void ReadBytes(byte[] bytes) { for (int i = 0; i < bytes.Length; i++) { bytes[i] = buffer[offset++]; } } internal float ReadFloat() { float result = BitConverter.ToSingle(buffer, offset); offset += 4; return result; } internal double ReadDouble() { double result = BitConverter.ToDouble(buffer, offset); offset += 8; return result; } internal decimal ReadDecimal() { int[] array = new int[4]; ReadInt32(array); return new decimal(array[2], array[3], array[1], array[0] < 0, (byte)((array[0] & 0xFF0000) >> 16)); } internal void ReadBString(out string value) { ReadUInt16(out var value2); value = Encoding.UTF8.GetString(buffer, offset, value2); offset += value2; } internal string ReadBString(int len) { string @string = Encoding.UTF8.GetString(buffer, offset, len); offset += len; return @string; } internal void ReadCString(out string value) { int i; for (i = 0; offset + i < buffer.Length && buffer[offset + i] != 0; i++) { } value = Encoding.UTF8.GetString(buffer, offset, i); offset += i + 1; } internal void SkipCString(out string value) { int i; for (i = 0; offset + i < buffer.Length && buffer[offset + i] != 0; i++) { } offset += i + 1; value = null; } internal void ReadGuid(out Guid guid) { ReadUInt32(out var value); ReadUInt16(out var value2); ReadUInt16(out var value3); ReadUInt8(out var value4); ReadUInt8(out var value5); ReadUInt8(out var value6); ReadUInt8(out var value7); ReadUInt8(out var value8); ReadUInt8(out var value9); ReadUInt8(out var value10); ReadUInt8(out var value11); guid = new Guid(value, value2, value3, value4, value5, value6, value7, value8, value9, value10, value11); } internal string ReadString() { int i; for (i = 0; offset + i < buffer.Length && buffer[offset + i] != 0; i += 2) { } string @string = Encoding.Unicode.GetString(buffer, offset, i); offset += i + 2; return @string; } } internal struct BitSet { private int size; private uint[] words; internal bool IsEmpty => size == 0; internal BitSet(BitAccess bits) { bits.ReadInt32(out size); words = new uint[size]; bits.ReadUInt32(words); } internal bool IsSet(int index) { int num = index / 32; if (num >= size) { return false; } return (words[num] & GetBit(index)) != 0; } private static uint GetBit(int index) { return (uint)(1 << index % 32); } } internal struct FLOAT10 { internal byte Data_0; internal byte Data_1; internal byte Data_2; internal byte Data_3; internal byte Data_4; internal byte Data_5; internal byte Data_6; internal byte Data_7; internal byte Data_8; internal byte Data_9; } internal enum CV_SIGNATURE { C6 = 0, C7 = 1, C11 = 2, C13 = 4, RESERVERD = 5 } internal enum CV_prmode { CV_TM_DIRECT = 0, CV_TM_NPTR32 = 4, CV_TM_NPTR64 = 6, CV_TM_NPTR128 = 7 } internal enum CV_type { CV_SPECIAL = 0, CV_SIGNED = 1, CV_UNSIGNED = 2, CV_BOOLEAN = 3, CV_REAL = 4, CV_COMPLEX = 5, CV_SPECIAL2 = 6, CV_INT = 7, CV_CVRESERVED = 15 } internal enum CV_special { CV_SP_NOTYPE, CV_SP_ABS, CV_SP_SEGMENT, CV_SP_VOID, CV_SP_CURRENCY, CV_SP_NBASICSTR, CV_SP_FBASICSTR, CV_SP_NOTTRANS, CV_SP_HRESULT } internal enum CV_special2 { CV_S2_BIT, CV_S2_PASCHAR } internal enum CV_integral { CV_IN_1BYTE, CV_IN_2BYTE, CV_IN_4BYTE, CV_IN_8BYTE, CV_IN_16BYTE } internal enum CV_real { CV_RC_REAL32, CV_RC_REAL64, CV_RC_REAL80, CV_RC_REAL128 } internal enum CV_int { CV_RI_CHAR = 0, CV_RI_INT1 = 0, CV_RI_WCHAR = 1, CV_RI_UINT1 = 1, CV_RI_INT2 = 2, CV_RI_UINT2 = 3, CV_RI_INT4 = 4, CV_RI_UINT4 = 5, CV_RI_INT8 = 6, CV_RI_UINT8 = 7, CV_RI_INT16 = 8, CV_RI_UINT16 = 9 } [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct CV_PRIMITIVE_TYPE { private const uint CV_MMASK = 1792u; private const uint CV_TMASK = 240u; private const uint CV_SMASK = 15u; private const int CV_MSHIFT = 8; private const int CV_TSHIFT = 4; private const int CV_SSHIFT = 0; private const uint CV_FIRST_NONPRIM = 4096u; } internal enum TYPE_ENUM { T_NOTYPE = 0, T_ABS = 1, T_SEGMENT = 2, T_VOID = 3, T_HRESULT = 8, T_32PHRESULT = 1032, T_64PHRESULT = 1544, T_PVOID = 259, T_PFVOID = 515, T_PHVOID = 771, T_32PVOID = 1027, T_64PVOID = 1539, T_CURRENCY = 4, T_NOTTRANS = 7, T_BIT = 96, T_PASCHAR = 97, T_CHAR = 16, T_32PCHAR = 1040, T_64PCHAR = 1552, T_UCHAR = 32, T_32PUCHAR = 1056, T_64PUCHAR = 1568, T_RCHAR = 112, T_32PRCHAR = 1136, T_64PRCHAR = 1648, T_WCHAR = 113, T_32PWCHAR = 1137, T_64PWCHAR = 1649, T_INT1 = 104, T_32PINT1 = 1128, T_64PINT1 = 1640, T_UINT1 = 105, T_32PUINT1 = 1129, T_64PUINT1 = 1641, T_SHORT = 17, T_32PSHORT = 1041, T_64PSHORT = 1553, T_USHORT = 33, T_32PUSHORT = 1057, T_64PUSHORT = 1569, T_INT2 = 114, T_32PINT2 = 1138, T_64PINT2 = 1650, T_UINT2 = 115, T_32PUINT2 = 1139, T_64PUINT2 = 1651, T_LONG = 18, T_ULONG = 34, T_32PLONG = 1042, T_32PULONG = 1058, T_64PLONG = 1554, T_64PULONG = 1570, T_INT4 = 116, T_32PINT4 = 1140, T_64PINT4 = 1652, T_UINT4 = 117, T_32PUINT4 = 1141, T_64PUINT4 = 1653, T_QUAD = 19, T_32PQUAD = 1043, T_64PQUAD = 1555, T_UQUAD = 35, T_32PUQUAD = 1059, T_64PUQUAD = 1571, T_INT8 = 118, T_32PINT8 = 1142, T_64PINT8 = 1654, T_UINT8 = 119, T_32PUINT8 = 1143, T_64PUINT8 = 1655, T_OCT = 20, T_32POCT = 1044, T_64POCT = 1556, T_UOCT = 36, T_32PUOCT = 1060, T_64PUOCT = 1572, T_INT16 = 120, T_32PINT16 = 1144, T_64PINT16 = 1656, T_UINT16 = 121, T_32PUINT16 = 1145, T_64PUINT16 = 1657, T_REAL32 = 64, T_32PREAL32 = 1088, T_64PREAL32 = 1600, T_REAL64 = 65, T_32PREAL64 = 1089, T_64PREAL64 = 1601, T_REAL80 = 66, T_32PREAL80 = 1090, T_64PREAL80 = 1602, T_REAL128 = 67, T_32PREAL128 = 1091, T_64PREAL128 = 1603, T_CPLX32 = 80, T_32PCPLX32 = 1104, T_64PCPLX32 = 1616, T_CPLX64 = 81, T_32PCPLX64 = 1105, T_64PCPLX64 = 1617, T_CPLX80 = 82, T_32PCPLX80 = 1106, T_64PCPLX80 = 1618, T_CPLX128 = 83, T_32PCPLX128 = 1107, T_64PCPLX128 = 1619, T_BOOL08 = 48, T_32PBOOL08 = 1072, T_64PBOOL08 = 1584, T_BOOL16 = 49, T_32PBOOL16 = 1073, T_64PBOOL16 = 1585, T_BOOL32 = 50, T_32PBOOL32 = 1074, T_64PBOOL32 = 1586, T_BOOL64 = 51, T_32PBOOL64 = 1075, T_64PBOOL64 = 1587 } internal enum LEAF { LF_VTSHAPE = 10, LF_COBOL1 = 12, LF_LABEL = 14, LF_NULL = 15, LF_NOTTRAN = 16, LF_ENDPRECOMP = 20, LF_TYPESERVER_ST = 22, LF_LIST = 515, LF_REFSYM = 524, LF_ENUMERATE_ST = 1027, LF_TI16_MAX = 4096, LF_MODIFIER = 4097, LF_POINTER = 4098, LF_ARRAY_ST = 4099, LF_CLASS_ST = 4100, LF_STRUCTURE_ST = 4101, LF_UNION_ST = 4102, LF_ENUM_ST = 4103, LF_PROCEDURE = 4104, LF_MFUNCTION = 4105, LF_COBOL0 = 4106, LF_BARRAY = 4107, LF_DIMARRAY_ST = 4108, LF_VFTPATH = 4109, LF_PRECOMP_ST = 4110, LF_OEM = 4111, LF_ALIAS_ST = 4112, LF_OEM2 = 4113, LF_SKIP = 4608, LF_ARGLIST = 4609, LF_DEFARG_ST = 4610, LF_FIELDLIST = 4611, LF_DERIVED = 4612, LF_BITFIELD = 4613, LF_METHODLIST = 4614, LF_DIMCONU = 4615, LF_DIMCONLU = 4616, LF_DIMVARU = 4617, LF_DIMVARLU = 4618, LF_BCLASS = 5120, LF_VBCLASS = 5121, LF_IVBCLASS = 5122, LF_FRIENDFCN_ST = 5123, LF_INDEX = 5124, LF_MEMBER_ST = 5125, LF_STMEMBER_ST = 5126, LF_METHOD_ST = 5127, LF_NESTTYPE_ST = 5128, LF_VFUNCTAB = 5129, LF_FRIENDCLS = 5130, LF_ONEMETHOD_ST = 5131, LF_VFUNCOFF = 5132, LF_NESTTYPEEX_ST = 5133, LF_MEMBERMODIFY_ST = 5134, LF_MANAGED_ST = 5135, LF_ST_MAX = 5376, LF_TYPESERVER = 5377, LF_ENUMERATE = 5378, LF_ARRAY = 5379, LF_CLASS = 5380, LF_STRUCTURE = 5381, LF_UNION = 5382, LF_ENUM = 5383, LF_DIMARRAY = 5384, LF_PRECOMP = 5385, LF_ALIAS = 5386, LF_DEFARG = 5387, LF_FRIENDFCN = 5388, LF_MEMBER = 5389, LF_STMEMBER = 5390, LF_METHOD = 5391, LF_NESTTYPE = 5392, LF_ONEMETHOD = 5393, LF_NESTTYPEEX = 5394, LF_MEMBERMODIFY = 5395, LF_MANAGED = 5396, LF_TYPESERVER2 = 5397, LF_NUMERIC = 32768, LF_CHAR = 32768, LF_SHORT = 32769, LF_USHORT = 32770, LF_LONG = 32771, LF_ULONG = 32772, LF_REAL32 = 32773, LF_REAL64 = 32774, LF_REAL80 = 32775, LF_REAL128 = 32776, LF_QUADWORD = 32777, LF_UQUADWORD = 32778, LF_COMPLEX32 = 32780, LF_COMPLEX64 = 32781, LF_COMPLEX80 = 32782, LF_COMPLEX128 = 32783, LF_VARSTRING = 32784, LF_OCTWORD = 32791, LF_UOCTWORD = 32792, LF_DECIMAL = 32793, LF_DATE = 32794, LF_UTF8STRING = 32795, LF_PAD0 = 240, LF_PAD1 = 241, LF_PAD2 = 242, LF_PAD3 = 243, LF_PAD4 = 244, LF_PAD5 = 245, LF_PAD6 = 246, LF_PAD7 = 247, LF_PAD8 = 248, LF_PAD9 = 249, LF_PAD10 = 250, LF_PAD11 = 251, LF_PAD12 = 252, LF_PAD13 = 253, LF_PAD14 = 254, LF_PAD15 = 255 } internal enum CV_ptrtype { CV_PTR_BASE_SEG = 3, CV_PTR_BASE_VAL = 4, CV_PTR_BASE_SEGVAL = 5, CV_PTR_BASE_ADDR = 6, CV_PTR_BASE_SEGADDR = 7, CV_PTR_BASE_TYPE = 8, CV_PTR_BASE_SELF = 9, CV_PTR_NEAR32 = 10, CV_PTR_64 = 12, CV_PTR_UNUSEDPTR = 13 } internal enum CV_ptrmode { CV_PTR_MODE_PTR, CV_PTR_MODE_REF, CV_PTR_MODE_PMEM, CV_PTR_MODE_PMFUNC, CV_PTR_MODE_RESERVED } internal enum CV_pmtype { CV_PMTYPE_Undef, CV_PMTYPE_D_Single, CV_PMTYPE_D_Multiple, CV_PMTYPE_D_Virtual, CV_PMTYPE_D_General, CV_PMTYPE_F_Single, CV_PMTYPE_F_Multiple, CV_PMTYPE_F_Virtual, CV_PMTYPE_F_General } internal enum CV_methodprop { CV_MTvanilla, CV_MTvirtual, CV_MTstatic, CV_MTfriend, CV_MTintro, CV_MTpurevirt, CV_MTpureintro } internal enum CV_VTS_desc { CV_VTS_near, CV_VTS_far, CV_VTS_thin, CV_VTS_outer, CV_VTS_meta, CV_VTS_near32, CV_VTS_far32, CV_VTS_unused } internal enum CV_LABEL_TYPE { CV_LABEL_NEAR = 0, CV_LABEL_FAR = 4 } [Flags] internal enum CV_modifier : ushort { MOD_const = 1, MOD_volatile = 2, MOD_unaligned = 4 } [Flags] internal enum CV_prop : ushort { packed = 1, ctor = 2, ovlops = 4, isnested = 8, cnested = 0x10, opassign = 0x20, opcast = 0x40, fwdref = 0x80, scoped = 0x100 } [Flags] internal enum CV_fldattr { access = 3, mprop = 0x1C, pseudo = 0x20, noinherit = 0x40, noconstruct = 0x80, compgenx = 0x100 } internal struct TYPTYPE { internal ushort len; internal ushort leaf; } internal struct CV_PDMR32_NVVFCN { internal int mdisp; } internal struct CV_PDMR32_VBASE { internal int mdisp; internal int pdisp; internal int vdisp; } internal struct CV_PMFR32_NVSA { internal uint off; } internal struct CV_PMFR32_NVMA { internal uint off; internal int disp; } internal struct CV_PMFR32_VBASE { internal uint off; internal int mdisp; internal int pdisp; internal int vdisp; } internal struct LeafModifier { internal uint type; internal CV_modifier attr; } [Flags] internal enum LeafPointerAttr : uint { ptrtype = 0x1Fu, ptrmode = 0xE0u, isflat32 = 0x100u, isvolatile = 0x200u, isconst = 0x400u, isunaligned = 0x800u, isrestrict = 0x1000u } [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct LeafPointer { internal struct LeafPointerBody { internal uint utype; internal LeafPointerAttr attr; } } internal struct LeafArray { internal uint elemtype; internal uint idxtype; internal byte[] data; internal string name; } internal struct LeafClass { internal ushort count; internal ushort property; internal uint field; internal uint derived; internal uint vshape; internal byte[] data; internal string name; } internal struct LeafUnion { internal ushort count; internal ushort property; internal uint field; internal byte[] data; internal string name; } internal struct LeafAlias { internal uint utype; internal string name; } internal struct LeafManaged { internal string name; } internal struct LeafEnum { internal ushort count; internal ushort property; internal uint utype; internal uint field; internal string name; } internal struct LeafProc { internal uint rvtype; internal byte calltype; internal byte reserved; internal ushort parmcount; internal uint arglist; } internal struct LeafMFunc { internal uint rvtype; internal uint classtype; internal uint thistype; internal byte calltype; internal byte reserved; internal ushort parmcount; internal uint arglist; internal int thisadjust; } internal struct LeafVTShape { internal ushort count; internal byte[] desc; } internal struct LeafCobol0 { internal uint type; internal byte[] data; } internal struct LeafCobol1 { internal byte[] data; } internal struct LeafBArray { internal uint utype; } internal struct LeafLabel { internal ushort mode; } internal struct LeafDimArray { internal uint utype; internal uint diminfo; internal string name; } internal struct LeafVFTPath { internal uint count; internal uint[] bases; } internal struct LeafPreComp { internal uint start; internal uint count; internal uint signature; internal string name; } internal struct LeafEndPreComp { internal uint signature; } internal struct LeafOEM { internal ushort cvOEM; internal ushort recOEM; internal uint count; internal uint[] index; } internal enum OEM_ID { OEM_MS_FORTRAN90 = 61584, OEM_ODI = 16, OEM_THOMSON_SOFTWARE = 21587, OEM_ODI_REC_BASELIST = 0 } internal struct LeafOEM2 { internal Guid idOem; internal uint count; internal uint[] index; } internal struct LeafTypeServer { internal uint signature; internal uint age; internal string name; } internal struct LeafTypeServer2 { internal Guid sig70; internal uint age; internal string name; } internal struct LeafSkip { internal uint type; internal byte[] data; } internal struct LeafArgList { internal uint count; internal uint[] arg; } internal struct LeafDerived { internal uint count; internal uint[] drvdcls; } internal struct LeafDefArg { internal uint type; internal byte[] expr; } internal struct LeafList { internal byte[] data; } internal struct LeafFieldList { internal char[] data; } internal struct mlMethod { internal ushort attr; internal ushort pad0; internal uint index; internal uint[] vbaseoff; } internal struct LeafMethodList { internal byte[] mList; } internal struct LeafBitfield { internal uint type; internal byte length; internal byte position; } internal struct LeafDimCon { internal uint typ; internal ushort rank; internal byte[] dim; } internal struct LeafDimVar { internal uint rank; internal uint typ; internal uint[] dim; } internal struct LeafRefSym { internal byte[] Sym; } internal struct LeafChar { internal sbyte val; } internal struct LeafShort { internal short val; } internal struct LeafUShort { internal ushort val; } internal struct LeafLong { internal int val; } internal struct LeafULong { internal uint val; } internal struct LeafQuad { internal long val; } internal struct LeafUQuad { internal ulong val; } internal struct LeafOct { internal ulong val0; internal ulong val1; } internal struct LeafUOct { internal ulong val0; internal ulong val1; } internal struct LeafReal32 { internal float val; } internal struct LeafReal64 { internal double val; } internal struct LeafReal80 { internal FLOAT10 val; } internal struct LeafReal128 { internal ulong val0; internal ulong val1; } internal struct LeafCmplx32 { internal float val_real; internal float val_imag; } internal struct LeafCmplx64 { internal double val_real; internal double val_imag; } internal struct LeafCmplx80 { internal FLOAT10 val_real; internal FLOAT10 val_imag; } internal struct LeafCmplx128 { internal ulong val0_real; internal ulon
BepInEx/core/Mono.Cecil.Rocks.dll
Decompiled a week 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.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using Microsoft.CodeAnalysis; using Mono.Cecil.Cil; using Mono.Cecil.PE; using Mono.Collections.Generic; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyProduct("Mono.Cecil")] [assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")] [assembly: ComVisible(false)] [assembly: AssemblyFileVersion("0.11.6.0")] [assembly: AssemblyInformationalVersion("0.11.6.0")] [assembly: AssemblyTitle("Mono.Cecil.Rocks")] [assembly: CLSCompliant(false)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyVersion("0.11.6.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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Mono.Cecil.Rocks { public class DocCommentId { private class GenericTypeOptions { public bool IsArgument { get; set; } public bool IsNestedType { get; set; } public IList<TypeReference> Arguments { get; set; } public int ArgumentIndex { get; set; } public static GenericTypeOptions Empty() { return new GenericTypeOptions(); } } private IMemberDefinition commentMember; private StringBuilder id; private DocCommentId(IMemberDefinition member) { commentMember = member; id = new StringBuilder(); } private void WriteField(FieldDefinition field) { WriteDefinition('F', (IMemberDefinition)(object)field); } private void WriteEvent(EventDefinition @event) { WriteDefinition('E', (IMemberDefinition)(object)@event); } private void WriteType(TypeDefinition type) { id.Append('T').Append(':'); WriteTypeFullName((TypeReference)(object)type); } private void WriteMethod(MethodDefinition method) { WriteDefinition('M', (IMemberDefinition)(object)method); if (((MethodReference)method).HasGenericParameters) { id.Append('`').Append('`'); id.Append(((MethodReference)method).GenericParameters.Count); } if (((MethodReference)method).HasParameters) { WriteParameters((IList<ParameterDefinition>)((MethodReference)method).Parameters); } if (IsConversionOperator(method)) { WriteReturnType(method); } } private static bool IsConversionOperator(MethodDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } return self.IsSpecialName && (((MemberReference)self).Name == "op_Explicit" || ((MemberReference)self).Name == "op_Implicit"); } private void WriteReturnType(MethodDefinition method) { id.Append('~'); WriteTypeSignature(((MethodReference)method).ReturnType); } private void WriteProperty(PropertyDefinition property) { WriteDefinition('P', (IMemberDefinition)(object)property); if (property.HasParameters) { WriteParameters((IList<ParameterDefinition>)((PropertyReference)property).Parameters); } } private void WriteParameters(IList<ParameterDefinition> parameters) { id.Append('('); WriteList(parameters, delegate(ParameterDefinition p) { WriteTypeSignature(((ParameterReference)p).ParameterType); }); id.Append(')'); } private void WriteTypeSignature(TypeReference type) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000a: 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_002f: Expected I4, but got Unknown //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Expected O, but got Unknown //IL_00e0: 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) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Expected I4, but got Unknown //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Expected O, but got Unknown //IL_010e: 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_013f: Expected O, but got Unknown //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Expected O, but got Unknown MetadataType metadataType = type.MetadataType; MetadataType val = metadataType; switch (val - 15) { default: switch (val - 27) { case 0: WriteFunctionPointerTypeSignature((FunctionPointerType)type); return; case 3: id.Append('`').Append('`'); id.Append(((GenericParameter)type).Position); return; case 5: WriteModiferTypeSignature((IModifierType)(OptionalModifierType)type, '!'); return; case 4: WriteModiferTypeSignature((IModifierType)(RequiredModifierType)type, '|'); return; } break; case 5: WriteArrayTypeSignature((ArrayType)type); return; case 1: WriteTypeSignature(((TypeSpecification)(ByReferenceType)type).ElementType); id.Append('@'); return; case 6: WriteGenericInstanceTypeSignature((GenericInstanceType)type); return; case 4: if (IsGenericMethodTypeParameter(type)) { id.Append('`'); } id.Append('`'); id.Append(((GenericParameter)type).Position); return; case 0: WriteTypeSignature(((TypeSpecification)(PointerType)type).ElementType); id.Append('*'); return; case 2: case 3: break; } WriteTypeFullName(type); } private bool IsGenericMethodTypeParameter(TypeReference type) { IMemberDefinition obj = commentMember; MethodDefinition val = (MethodDefinition)(object)((obj is MethodDefinition) ? obj : null); if (val != null) { GenericParameter genericParameter = (GenericParameter)(object)((type is GenericParameter) ? type : null); if (genericParameter != null) { return ((IEnumerable<GenericParameter>)((MethodReference)val).GenericParameters).Any((GenericParameter i) => ((MemberReference)i).Name == ((MemberReference)genericParameter).Name); } } return false; } private void WriteGenericInstanceTypeSignature(GenericInstanceType type) { if (Mixin.IsTypeSpecification(((TypeSpecification)type).ElementType)) { throw new NotSupportedException(); } GenericTypeOptions options = new GenericTypeOptions { IsArgument = true, IsNestedType = ((TypeReference)type).IsNested, Arguments = (IList<TypeReference>)type.GenericArguments }; WriteTypeFullName(((TypeSpecification)type).ElementType, options); } private void WriteList<T>(IList<T> list, Action<T> action) { for (int i = 0; i < list.Count; i++) { if (i > 0) { id.Append(','); } action(list[i]); } } private void WriteModiferTypeSignature(IModifierType type, char id) { WriteTypeSignature(type.ElementType); this.id.Append(id); WriteTypeSignature(type.ModifierType); } private void WriteFunctionPointerTypeSignature(FunctionPointerType type) { id.Append("=FUNC:"); WriteTypeSignature(type.ReturnType); if (type.HasParameters) { WriteParameters((IList<ParameterDefinition>)type.Parameters); } } private void WriteArrayTypeSignature(ArrayType type) { WriteTypeSignature(((TypeSpecification)type).ElementType); if (type.IsVector) { id.Append("[]"); return; } id.Append("["); WriteList((IList<ArrayDimension>)type.Dimensions, delegate(ArrayDimension dimension) { if (((ArrayDimension)(ref dimension)).LowerBound.HasValue) { id.Append(((ArrayDimension)(ref dimension)).LowerBound.Value); } id.Append(':'); if (((ArrayDimension)(ref dimension)).UpperBound.HasValue) { id.Append(((ArrayDimension)(ref dimension)).UpperBound.Value - (((ArrayDimension)(ref dimension)).LowerBound.GetValueOrDefault() + 1)); } }); id.Append("]"); } private void WriteDefinition(char id, IMemberDefinition member) { this.id.Append(id).Append(':'); WriteTypeFullName((TypeReference)(object)member.DeclaringType); this.id.Append('.'); WriteItemName(member.Name); } private void WriteTypeFullName(TypeReference type) { WriteTypeFullName(type, GenericTypeOptions.Empty()); } private void WriteTypeFullName(TypeReference type, GenericTypeOptions options) { if (((MemberReference)type).DeclaringType != null) { WriteTypeFullName(((MemberReference)type).DeclaringType, options); id.Append('.'); } if (!string.IsNullOrEmpty(type.Namespace)) { id.Append(type.Namespace); id.Append('.'); } string text = ((MemberReference)type).Name; if (options.IsArgument) { int num = text.LastIndexOf('`'); if (num > 0) { text = text.Substring(0, num); } } id.Append(text); WriteGenericTypeParameters(type, options); } private void WriteGenericTypeParameters(TypeReference type, GenericTypeOptions options) { if (options.IsArgument && IsGenericType(type)) { id.Append('{'); WriteList(GetGenericTypeArguments(type, options), WriteTypeSignature); id.Append('}'); } } private static bool IsGenericType(TypeReference type) { if (type.HasGenericParameters) { string text = string.Empty; int num = ((MemberReference)type).Name.LastIndexOf('`'); if (num >= 0) { text = ((MemberReference)type).Name.Substring(0, num); } return ((MemberReference)type).Name.LastIndexOf('`') == text.Length; } return false; } private IList<TypeReference> GetGenericTypeArguments(TypeReference type, GenericTypeOptions options) { if (options.IsNestedType) { int count = type.GenericParameters.Count; List<TypeReference> result = options.Arguments.Skip(options.ArgumentIndex).Take(count).ToList(); options.ArgumentIndex += count; return result; } return options.Arguments; } private void WriteItemName(string name) { id.Append(name.Replace('.', '#').Replace('<', '{').Replace('>', '}')); } public override string ToString() { return id.ToString(); } public static string GetDocCommentId(IMemberDefinition member) { //IL_001c: 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_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: 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_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Invalid comparison between Unknown and I4 //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Invalid comparison between Unknown and I4 //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Invalid comparison between Unknown and I4 //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Expected O, but got Unknown //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Expected O, but got Unknown //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Invalid comparison between Unknown and I4 //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Invalid comparison between Unknown and I4 //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Expected O, but got Unknown //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Expected O, but got Unknown //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Invalid comparison between Unknown and I4 //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Expected O, but got Unknown if (member == null) { throw new ArgumentNullException("member"); } DocCommentId docCommentId = new DocCommentId(member); MetadataToken metadataToken = ((IMetadataTokenProvider)member).MetadataToken; TokenType tokenType = ((MetadataToken)(ref metadataToken)).TokenType; TokenType val = tokenType; if ((int)val <= 67108864) { if ((int)val != 33554432) { if ((int)val != 67108864) { goto IL_00b2; } docCommentId.WriteField((FieldDefinition)member); } else { docCommentId.WriteType((TypeDefinition)member); } } else if ((int)val != 100663296) { if ((int)val != 335544320) { if ((int)val != 385875968) { goto IL_00b2; } docCommentId.WriteProperty((PropertyDefinition)member); } else { docCommentId.WriteEvent((EventDefinition)member); } } else { docCommentId.WriteMethod((MethodDefinition)member); } return docCommentId.ToString(); IL_00b2: throw new NotSupportedException(member.FullName); } } internal static class Functional { public static Func<A, R> Y<A, R>(Func<Func<A, R>, Func<A, R>> f) { Func<A, R> g = null; g = f((A a) => g(a)); return g; } public static IEnumerable<TSource> Prepend<TSource>(this IEnumerable<TSource> source, TSource element) { if (source == null) { throw new ArgumentNullException("source"); } return PrependIterator(source, element); } private static IEnumerable<TSource> PrependIterator<TSource>(IEnumerable<TSource> source, TSource element) { yield return element; foreach (TSource item in source) { yield return item; } } } public interface IILVisitor { void OnInlineNone(OpCode opcode); void OnInlineSByte(OpCode opcode, sbyte value); void OnInlineByte(OpCode opcode, byte value); void OnInlineInt32(OpCode opcode, int value); void OnInlineInt64(OpCode opcode, long value); void OnInlineSingle(OpCode opcode, float value); void OnInlineDouble(OpCode opcode, double value); void OnInlineString(OpCode opcode, string value); void OnInlineBranch(OpCode opcode, int offset); void OnInlineSwitch(OpCode opcode, int[] offsets); void OnInlineVariable(OpCode opcode, VariableDefinition variable); void OnInlineArgument(OpCode opcode, ParameterDefinition parameter); void OnInlineSignature(OpCode opcode, CallSite callSite); void OnInlineType(OpCode opcode, TypeReference type); void OnInlineField(OpCode opcode, FieldReference field); void OnInlineMethod(OpCode opcode, MethodReference method); } public static class ILParser { private class ParseContext { public CodeReader Code { get; set; } public int Position { get; set; } public MetadataReader Metadata { get; set; } public Collection<VariableDefinition> Variables { get; set; } public IILVisitor Visitor { get; set; } } public static void Parse(MethodDefinition method, IILVisitor visitor) { if (method == null) { throw new ArgumentNullException("method"); } if (visitor == null) { throw new ArgumentNullException("visitor"); } if (!method.HasBody || !((MemberReference)method).HasImage) { throw new ArgumentException(); } ((MemberReference)method).Module.Read<MethodDefinition, bool>(method, (Func<MethodDefinition, MetadataReader, bool>)delegate(MethodDefinition m, MetadataReader _) { ParseMethod(m, visitor); return true; }); } private static void ParseMethod(MethodDefinition method, IILVisitor visitor) { ParseContext parseContext = CreateContext(method, visitor); CodeReader code = parseContext.Code; byte b = ((BinaryReader)(object)code).ReadByte(); switch (b & 3) { case 2: { int code_size = b >> 2; ParseCode(code_size, parseContext); break; } case 3: ((BinaryStreamReader)code).Advance(-1); ParseFatMethod(parseContext); break; default: throw new NotSupportedException(); } code.MoveBackTo(parseContext.Position); } private static ParseContext CreateContext(MethodDefinition method, IILVisitor visitor) { CodeReader val = ((MemberReference)method).Module.Read<MethodDefinition, CodeReader>(method, (Func<MethodDefinition, MetadataReader, CodeReader>)((MethodDefinition _, MetadataReader reader) => reader.code)); int position = val.MoveTo(method); return new ParseContext { Code = val, Position = position, Metadata = val.reader, Visitor = visitor }; } private static void ParseFatMethod(ParseContext context) { //IL_0018: 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_001e: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) CodeReader code = context.Code; ((BinaryStreamReader)code).Advance(4); int code_size = ((BinaryReader)(object)code).ReadInt32(); MetadataToken val = code.ReadToken(); if (val != MetadataToken.Zero) { context.Variables = (Collection<VariableDefinition>)(object)code.ReadVariables(val); } ParseCode(code_size, context); } private static void ParseCode(int code_size, ParseContext context) { //IL_0052: 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected I4, but got Unknown //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_026e: Unknown result type (might be due to invalid IL or missing references) //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_0277: Unknown result type (might be due to invalid IL or missing references) //IL_027c: 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_0280: Unknown result type (might be due to invalid IL or missing references) //IL_0282: Unknown result type (might be due to invalid IL or missing references) //IL_0289: Invalid comparison between Unknown and I4 //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_01af: 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_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_0245: Unknown result type (might be due to invalid IL or missing references) //IL_0211: 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_013b: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_022b: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_02af: Unknown result type (might be due to invalid IL or missing references) //IL_02b6: Invalid comparison between Unknown and I4 //IL_028b: Unknown result type (might be due to invalid IL or missing references) //IL_0292: Invalid comparison between Unknown and I4 //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_02d1: Unknown result type (might be due to invalid IL or missing references) //IL_02d8: Invalid comparison between Unknown and I4 //IL_02b8: Unknown result type (might be due to invalid IL or missing references) //IL_02bf: Invalid comparison between Unknown and I4 //IL_02eb: Unknown result type (might be due to invalid IL or missing references) //IL_02ef: Unknown result type (might be due to invalid IL or missing references) //IL_02f9: Expected O, but got Unknown //IL_0104: 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_0301: Unknown result type (might be due to invalid IL or missing references) //IL_030b: Expected O, but got Unknown //IL_0296: Unknown result type (might be due to invalid IL or missing references) //IL_029d: Invalid comparison between Unknown and I4 //IL_02dc: Unknown result type (might be due to invalid IL or missing references) //IL_02e3: Invalid comparison between Unknown and I4 //IL_02c3: Unknown result type (might be due to invalid IL or missing references) //IL_02ca: Invalid comparison between Unknown and I4 //IL_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_02a8: Invalid comparison between Unknown and I4 //IL_0336: Unknown result type (might be due to invalid IL or missing references) //IL_030f: Unknown result type (might be due to invalid IL or missing references) //IL_0313: Unknown result type (might be due to invalid IL or missing references) //IL_031d: Expected O, but got Unknown //IL_0358: Unknown result type (might be due to invalid IL or missing references) CodeReader code = context.Code; MetadataReader metadata = context.Metadata; IILVisitor visitor = context.Visitor; int position = ((BinaryStreamReader)code).Position; int num = position + code_size; while (((BinaryStreamReader)code).Position < num) { byte b = ((BinaryReader)(object)code).ReadByte(); OpCode val = ((b != 254) ? OpCodes.OneByteOpCode[b] : OpCodes.TwoBytesOpCode[((BinaryReader)(object)code).ReadByte()]); OperandType operandType = ((OpCode)(ref val)).OperandType; OperandType val2 = operandType; IMetadataTokenProvider val3; switch ((int)val2) { case 5: visitor.OnInlineNone(val); break; case 10: { int num2 = ((BinaryReader)(object)code).ReadInt32(); int[] array = new int[num2]; for (int i = 0; i < num2; i++) { array[i] = ((BinaryReader)(object)code).ReadInt32(); } visitor.OnInlineSwitch(val, array); break; } case 15: visitor.OnInlineBranch(val, ((BinaryReader)(object)code).ReadSByte()); break; case 0: visitor.OnInlineBranch(val, ((BinaryReader)(object)code).ReadInt32()); break; case 16: if (val == OpCodes.Ldc_I4_S) { visitor.OnInlineSByte(val, ((BinaryReader)(object)code).ReadSByte()); } else { visitor.OnInlineByte(val, ((BinaryReader)(object)code).ReadByte()); } break; case 2: visitor.OnInlineInt32(val, ((BinaryReader)(object)code).ReadInt32()); break; case 3: visitor.OnInlineInt64(val, ((BinaryReader)(object)code).ReadInt64()); break; case 17: visitor.OnInlineSingle(val, ((BinaryReader)(object)code).ReadSingle()); break; case 7: visitor.OnInlineDouble(val, ((BinaryReader)(object)code).ReadDouble()); break; case 8: visitor.OnInlineSignature(val, code.GetCallSite(code.ReadToken())); break; case 9: visitor.OnInlineString(val, code.GetString(code.ReadToken())); break; case 19: visitor.OnInlineArgument(val, code.GetParameter((int)((BinaryReader)(object)code).ReadByte())); break; case 14: visitor.OnInlineArgument(val, code.GetParameter((int)((BinaryReader)(object)code).ReadInt16())); break; case 18: visitor.OnInlineVariable(val, GetVariable(context, ((BinaryReader)(object)code).ReadByte())); break; case 13: visitor.OnInlineVariable(val, GetVariable(context, ((BinaryReader)(object)code).ReadInt16())); break; case 1: case 4: case 11: case 12: { val3 = metadata.LookupToken(code.ReadToken()); MetadataToken metadataToken = val3.MetadataToken; TokenType tokenType = ((MetadataToken)(ref metadataToken)).TokenType; TokenType val4 = tokenType; if ((int)val4 <= 67108864) { if ((int)val4 != 16777216 && (int)val4 != 33554432) { if ((int)val4 == 67108864) { visitor.OnInlineField(val, (FieldReference)val3); } break; } goto IL_02ea; } if ((int)val4 <= 167772160) { if ((int)val4 != 100663296) { if ((int)val4 != 167772160) { break; } FieldReference val5 = (FieldReference)(object)((val3 is FieldReference) ? val3 : null); if (val5 != null) { visitor.OnInlineField(val, val5); break; } MethodReference val6 = (MethodReference)(object)((val3 is MethodReference) ? val3 : null); if (val6 != null) { visitor.OnInlineMethod(val, val6); break; } throw new InvalidOperationException(); } } else { if ((int)val4 == 452984832) { goto IL_02ea; } if ((int)val4 != 721420288) { break; } } visitor.OnInlineMethod(val, (MethodReference)val3); break; } IL_02ea: visitor.OnInlineType(val, (TypeReference)val3); break; } } } private static VariableDefinition GetVariable(ParseContext context, int index) { return context.Variables[index]; } } public static class MethodBodyRocks { public static void SimplifyMacros(this MethodBody self) { //IL_001b: 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_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Invalid comparison between Unknown and I4 //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) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Expected I4, but got Unknown //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_016b: 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) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01d0: 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_020a: 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_0244: Unknown result type (might be due to invalid IL or missing references) //IL_0261: 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_02ac: Unknown result type (might be due to invalid IL or missing references) //IL_02bd: 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_02df: Unknown result type (might be due to invalid IL or missing references) //IL_02f0: Unknown result type (might be due to invalid IL or missing references) //IL_0301: Unknown result type (might be due to invalid IL or missing references) //IL_0318: Unknown result type (might be due to invalid IL or missing references) //IL_032f: Unknown result type (might be due to invalid IL or missing references) //IL_0346: Unknown result type (might be due to invalid IL or missing references) //IL_035d: 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) //IL_038b: Unknown result type (might be due to invalid IL or missing references) //IL_03a2: Unknown result type (might be due to invalid IL or missing references) //IL_03b9: Unknown result type (might be due to invalid IL or missing references) //IL_03d0: Unknown result type (might be due to invalid IL or missing references) //IL_03e7: Unknown result type (might be due to invalid IL or missing references) //IL_0408: Unknown result type (might be due to invalid IL or missing references) //IL_0419: Unknown result type (might be due to invalid IL or missing references) //IL_042a: Unknown result type (might be due to invalid IL or missing references) //IL_043b: Unknown result type (might be due to invalid IL or missing references) //IL_044c: Unknown result type (might be due to invalid IL or missing references) //IL_045a: Unknown result type (might be due to invalid IL or missing references) //IL_0468: Unknown result type (might be due to invalid IL or missing references) //IL_0476: Unknown result type (might be due to invalid IL or missing references) //IL_0484: Unknown result type (might be due to invalid IL or missing references) //IL_0492: Unknown result type (might be due to invalid IL or missing references) //IL_04a0: Unknown result type (might be due to invalid IL or missing references) //IL_04ae: Unknown result type (might be due to invalid IL or missing references) //IL_04bc: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Invalid comparison between Unknown and I4 //IL_04ca: Unknown result type (might be due to invalid IL or missing references) if (self == null) { throw new ArgumentNullException("self"); } Enumerator<Instruction> enumerator = self.Instructions.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current = enumerator.Current; OpCode opCode = current.OpCode; if ((int)((OpCode)(ref opCode)).OpCodeType != 1) { continue; } opCode = current.OpCode; Code code = ((OpCode)(ref opCode)).Code; Code val = code; switch (val - 2) { case 0: ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 0)); continue; case 1: ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 1)); continue; case 2: ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 2)); continue; case 3: ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 3)); continue; case 4: ExpandMacro(current, OpCodes.Ldloc, self.Variables[0]); continue; case 5: ExpandMacro(current, OpCodes.Ldloc, self.Variables[1]); continue; case 6: ExpandMacro(current, OpCodes.Ldloc, self.Variables[2]); continue; case 7: ExpandMacro(current, OpCodes.Ldloc, self.Variables[3]); continue; case 8: ExpandMacro(current, OpCodes.Stloc, self.Variables[0]); continue; case 9: ExpandMacro(current, OpCodes.Stloc, self.Variables[1]); continue; case 10: ExpandMacro(current, OpCodes.Stloc, self.Variables[2]); continue; case 11: ExpandMacro(current, OpCodes.Stloc, self.Variables[3]); continue; case 12: current.OpCode = OpCodes.Ldarg; continue; case 13: current.OpCode = OpCodes.Ldarga; continue; case 14: current.OpCode = OpCodes.Starg; continue; case 15: current.OpCode = OpCodes.Ldloc; continue; case 16: current.OpCode = OpCodes.Ldloca; continue; case 17: current.OpCode = OpCodes.Stloc; continue; case 19: ExpandMacro(current, OpCodes.Ldc_I4, -1); continue; case 20: ExpandMacro(current, OpCodes.Ldc_I4, 0); continue; case 21: ExpandMacro(current, OpCodes.Ldc_I4, 1); continue; case 22: ExpandMacro(current, OpCodes.Ldc_I4, 2); continue; case 23: ExpandMacro(current, OpCodes.Ldc_I4, 3); continue; case 24: ExpandMacro(current, OpCodes.Ldc_I4, 4); continue; case 25: ExpandMacro(current, OpCodes.Ldc_I4, 5); continue; case 26: ExpandMacro(current, OpCodes.Ldc_I4, 6); continue; case 27: ExpandMacro(current, OpCodes.Ldc_I4, 7); continue; case 28: ExpandMacro(current, OpCodes.Ldc_I4, 8); continue; case 29: ExpandMacro(current, OpCodes.Ldc_I4, (int)(sbyte)current.Operand); continue; case 40: current.OpCode = OpCodes.Br; continue; case 41: current.OpCode = OpCodes.Brfalse; continue; case 42: current.OpCode = OpCodes.Brtrue; continue; case 43: current.OpCode = OpCodes.Beq; continue; case 44: current.OpCode = OpCodes.Bge; continue; case 45: current.OpCode = OpCodes.Bgt; continue; case 46: current.OpCode = OpCodes.Ble; continue; case 47: current.OpCode = OpCodes.Blt; continue; case 48: current.OpCode = OpCodes.Bne_Un; continue; case 49: current.OpCode = OpCodes.Bge_Un; continue; case 50: current.OpCode = OpCodes.Bgt_Un; continue; case 51: current.OpCode = OpCodes.Ble_Un; continue; case 52: current.OpCode = OpCodes.Blt_Un; continue; case 18: case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39: continue; } if ((int)val == 188) { current.OpCode = OpCodes.Leave; } } } finally { ((IDisposable)enumerator).Dispose(); } } private static void ExpandMacro(Instruction instruction, OpCode opcode, object operand) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) instruction.OpCode = opcode; instruction.Operand = operand; } private static void MakeMacro(Instruction instruction, OpCode opcode) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) instruction.OpCode = opcode; instruction.Operand = null; } public static void Optimize(this MethodBody self) { if (self == null) { throw new ArgumentNullException("self"); } self.OptimizeLongs(); self.OptimizeMacros(); } private static void OptimizeLongs(this MethodBody self) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: 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_0027: Invalid comparison between Unknown and I4 //IL_005f: 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) for (int i = 0; i < self.Instructions.Count; i++) { Instruction val = self.Instructions[i]; OpCode opCode = val.OpCode; if ((int)((OpCode)(ref opCode)).Code == 33) { long num = (long)val.Operand; if (num < int.MaxValue && num > int.MinValue) { ExpandMacro(val, OpCodes.Ldc_I4, (int)num); self.Instructions.Insert(++i, Instruction.Create(OpCodes.Conv_I8)); } } } } public static void OptimizeMacros(this MethodBody self) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //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_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Invalid comparison between Unknown and I4 //IL_0357: 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) //IL_0379: Unknown result type (might be due to invalid IL or missing references) //IL_038a: Unknown result type (might be due to invalid IL or missing references) //IL_039b: Unknown result type (might be due to invalid IL or missing references) //IL_03a9: Unknown result type (might be due to invalid IL or missing references) //IL_03b7: Unknown result type (might be due to invalid IL or missing references) //IL_03c5: Unknown result type (might be due to invalid IL or missing references) //IL_03d3: Unknown result type (might be due to invalid IL or missing references) //IL_03e1: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Expected I4, but got Unknown //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0272: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_02dd: Unknown result type (might be due to invalid IL or missing references) //IL_01df: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_02f5: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Unknown result type (might be due to invalid IL or missing references) //IL_021b: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) //IL_0237: 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_01c1: Unknown result type (might be due to invalid IL or missing references) //IL_0254: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_02c1: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) if (self == null) { throw new ArgumentNullException("self"); } MethodDefinition method = self.Method; Enumerator<Instruction> enumerator = self.Instructions.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current = enumerator.Current; OpCode opCode = current.OpCode; Code code = ((OpCode)(ref opCode)).Code; Code val = code; if ((int)val != 32) { switch (val - 199) { case 0: { int index = ((ParameterReference)(ParameterDefinition)current.Operand).Index; if (index == -1 && current.Operand == self.ThisParameter) { index = 0; } else if (((MethodReference)method).HasThis) { index++; } switch (index) { case 0: MakeMacro(current, OpCodes.Ldarg_0); break; case 1: MakeMacro(current, OpCodes.Ldarg_1); break; case 2: MakeMacro(current, OpCodes.Ldarg_2); break; case 3: MakeMacro(current, OpCodes.Ldarg_3); break; default: if (index < 256) { ExpandMacro(current, OpCodes.Ldarg_S, current.Operand); } break; } break; } case 3: { int index = ((VariableReference)(VariableDefinition)current.Operand).Index; switch (index) { case 0: MakeMacro(current, OpCodes.Ldloc_0); break; case 1: MakeMacro(current, OpCodes.Ldloc_1); break; case 2: MakeMacro(current, OpCodes.Ldloc_2); break; case 3: MakeMacro(current, OpCodes.Ldloc_3); break; default: if (index < 256) { ExpandMacro(current, OpCodes.Ldloc_S, current.Operand); } break; } break; } case 5: { int index = ((VariableReference)(VariableDefinition)current.Operand).Index; switch (index) { case 0: MakeMacro(current, OpCodes.Stloc_0); break; case 1: MakeMacro(current, OpCodes.Stloc_1); break; case 2: MakeMacro(current, OpCodes.Stloc_2); break; case 3: MakeMacro(current, OpCodes.Stloc_3); break; default: if (index < 256) { ExpandMacro(current, OpCodes.Stloc_S, current.Operand); } break; } break; } case 1: { int index = ((ParameterReference)(ParameterDefinition)current.Operand).Index; if (index == -1 && current.Operand == self.ThisParameter) { index = 0; } else if (((MethodReference)method).HasThis) { index++; } if (index < 256) { ExpandMacro(current, OpCodes.Ldarga_S, current.Operand); } break; } case 4: if (((VariableReference)(VariableDefinition)current.Operand).Index < 256) { ExpandMacro(current, OpCodes.Ldloca_S, current.Operand); } break; } continue; } int num = (int)current.Operand; switch (num) { case -1: MakeMacro(current, OpCodes.Ldc_I4_M1); continue; case 0: MakeMacro(current, OpCodes.Ldc_I4_0); continue; case 1: MakeMacro(current, OpCodes.Ldc_I4_1); continue; case 2: MakeMacro(current, OpCodes.Ldc_I4_2); continue; case 3: MakeMacro(current, OpCodes.Ldc_I4_3); continue; case 4: MakeMacro(current, OpCodes.Ldc_I4_4); continue; case 5: MakeMacro(current, OpCodes.Ldc_I4_5); continue; case 6: MakeMacro(current, OpCodes.Ldc_I4_6); continue; case 7: MakeMacro(current, OpCodes.Ldc_I4_7); continue; case 8: MakeMacro(current, OpCodes.Ldc_I4_8); continue; } if (num >= -128 && num < 128) { ExpandMacro(current, OpCodes.Ldc_I4_S, (sbyte)num); } } } finally { ((IDisposable)enumerator).Dispose(); } OptimizeBranches(self); } private static void OptimizeBranches(MethodBody body) { //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_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Invalid comparison between Unknown and I4 ComputeOffsets(body); Enumerator<Instruction> enumerator = body.Instructions.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current = enumerator.Current; OpCode opCode = current.OpCode; if ((int)((OpCode)(ref opCode)).OperandType <= 0 && OptimizeBranch(current)) { ComputeOffsets(body); } } } finally { ((IDisposable)enumerator).Dispose(); } } private static bool OptimizeBranch(Instruction instruction) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0018: 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_0043: 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_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Expected I4, but got Unknown //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_014e: 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_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Invalid comparison between Unknown and I4 //IL_016a: Unknown result type (might be due to invalid IL or missing references) int offset = ((Instruction)instruction.Operand).Offset; int offset2 = instruction.Offset; OpCode opCode = instruction.OpCode; int num = offset - (offset2 + ((OpCode)(ref opCode)).Size + 4); if (num < -128 || num > 127) { return false; } opCode = instruction.OpCode; Code code = ((OpCode)(ref opCode)).Code; Code val = code; switch (val - 55) { default: if ((int)val == 187) { instruction.OpCode = OpCodes.Leave_S; } break; case 0: instruction.OpCode = OpCodes.Br_S; break; case 1: instruction.OpCode = OpCodes.Brfalse_S; break; case 2: instruction.OpCode = OpCodes.Brtrue_S; break; case 3: instruction.OpCode = OpCodes.Beq_S; break; case 4: instruction.OpCode = OpCodes.Bge_S; break; case 5: instruction.OpCode = OpCodes.Bgt_S; break; case 6: instruction.OpCode = OpCodes.Ble_S; break; case 7: instruction.OpCode = OpCodes.Blt_S; break; case 8: instruction.OpCode = OpCodes.Bne_Un_S; break; case 9: instruction.OpCode = OpCodes.Bge_Un_S; break; case 10: instruction.OpCode = OpCodes.Bgt_Un_S; break; case 11: instruction.OpCode = OpCodes.Ble_Un_S; break; case 12: instruction.OpCode = OpCodes.Blt_Un_S; break; } return true; } private static void ComputeOffsets(MethodBody body) { //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) int num = 0; Enumerator<Instruction> enumerator = body.Instructions.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current = enumerator.Current; current.Offset = num; num += current.GetSize(); } } finally { ((IDisposable)enumerator).Dispose(); } } } public static class MethodDefinitionRocks { public static MethodDefinition GetBaseMethod(this MethodDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } if (!self.IsVirtual) { return self; } if (self.IsNewSlot) { return self; } for (TypeDefinition val = ResolveBaseType(self.DeclaringType); val != null; val = ResolveBaseType(val)) { MethodDefinition matchingMethod = GetMatchingMethod(val, self); if (matchingMethod != null) { return matchingMethod; } } return self; } public static MethodDefinition GetOriginalBaseMethod(this MethodDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } while (true) { MethodDefinition baseMethod = self.GetBaseMethod(); if (baseMethod == self) { break; } self = baseMethod; } return self; } private static TypeDefinition ResolveBaseType(TypeDefinition type) { if (type == null) { return null; } TypeReference baseType = type.BaseType; if (baseType == null) { return null; } return baseType.Resolve(); } private static MethodDefinition GetMatchingMethod(TypeDefinition type, MethodDefinition method) { return MetadataResolver.GetMethod(type.Methods, (MethodReference)(object)method); } } public static class ModuleDefinitionRocks { public static IEnumerable<TypeDefinition> GetAllTypes(this ModuleDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } return ((IEnumerable<TypeDefinition>)self.Types).SelectMany(Functional.Y((Func<TypeDefinition, IEnumerable<TypeDefinition>> f) => (TypeDefinition type) => ((IEnumerable<TypeDefinition>)type.NestedTypes).SelectMany(f).Prepend(type))); } } public static class ParameterReferenceRocks { public static int GetSequence(this ParameterReference self) { return self.Index + 1; } } public static class SecurityDeclarationRocks { public static PermissionSet ToPermissionSet(this SecurityDeclaration self) { if (self == null) { throw new ArgumentNullException("self"); } if (TryProcessPermissionSetAttribute(self, out var set)) { return set; } return CreatePermissionSet(self); } private static bool TryProcessPermissionSetAttribute(SecurityDeclaration declaration, out PermissionSet set) { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected I4, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected O, but got Unknown //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: 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) set = null; if (!declaration.HasSecurityAttributes && declaration.SecurityAttributes.Count != 1) { return false; } SecurityAttribute val = declaration.SecurityAttributes[0]; if (!Mixin.IsTypeOf(val.AttributeType, "System.Security.Permissions", "PermissionSetAttribute")) { return false; } PermissionSetAttribute val2 = new PermissionSetAttribute((SecurityAction)declaration.Action); CustomAttributeNamedArgument val3 = val.Properties[0]; CustomAttributeArgument argument = ((CustomAttributeNamedArgument)(ref val3)).Argument; string text = (string)((CustomAttributeArgument)(ref argument)).Value; string name = ((CustomAttributeNamedArgument)(ref val3)).Name; string text2 = name; if (!(text2 == "XML")) { if (!(text2 == "Name")) { throw new NotImplementedException(((CustomAttributeNamedArgument)(ref val3)).Name); } val2.Name = text; } else { val2.XML = text; } set = val2.CreatePermissionSet(); return true; } private static PermissionSet CreatePermissionSet(SecurityDeclaration declaration) { //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) PermissionSet permissionSet = new PermissionSet(PermissionState.None); Enumerator<SecurityAttribute> enumerator = declaration.SecurityAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { SecurityAttribute current = enumerator.Current; IPermission perm = CreatePermission(declaration, current); permissionSet.AddPermission(perm); } } finally { ((IDisposable)enumerator).Dispose(); } return permissionSet; } private static IPermission CreatePermission(SecurityDeclaration declaration, SecurityAttribute attribute) { Type type = Type.GetType(((MemberReference)attribute.AttributeType).FullName); if (type == null) { throw new ArgumentException("attribute"); } SecurityAttribute securityAttribute = CreateSecurityAttribute(type, declaration); if (securityAttribute == null) { throw new InvalidOperationException(); } CompleteSecurityAttribute(securityAttribute, attribute); return securityAttribute.CreatePermission(); } private static void CompleteSecurityAttribute(SecurityAttribute security_attribute, SecurityAttribute attribute) { if (attribute.HasFields) { CompleteSecurityAttributeFields(security_attribute, attribute); } if (attribute.HasProperties) { CompleteSecurityAttributeProperties(security_attribute, attribute); } } private static void CompleteSecurityAttributeFields(SecurityAttribute security_attribute, SecurityAttribute attribute) { //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_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) Type type = security_attribute.GetType(); Enumerator<CustomAttributeNamedArgument> enumerator = attribute.Fields.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttributeNamedArgument current = enumerator.Current; FieldInfo? field = type.GetField(((CustomAttributeNamedArgument)(ref current)).Name); CustomAttributeArgument argument = ((CustomAttributeNamedArgument)(ref current)).Argument; field.SetValue(security_attribute, ((CustomAttributeArgument)(ref argument)).Value); } } finally { ((IDisposable)enumerator).Dispose(); } } private static void CompleteSecurityAttributeProperties(SecurityAttribute security_attribute, SecurityAttribute attribute) { //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_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) Type type = security_attribute.GetType(); Enumerator<CustomAttributeNamedArgument> enumerator = attribute.Properties.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttributeNamedArgument current = enumerator.Current; PropertyInfo? property = type.GetProperty(((CustomAttributeNamedArgument)(ref current)).Name); CustomAttributeArgument argument = ((CustomAttributeNamedArgument)(ref current)).Argument; property.SetValue(security_attribute, ((CustomAttributeArgument)(ref argument)).Value, null); } } finally { ((IDisposable)enumerator).Dispose(); } } private static SecurityAttribute CreateSecurityAttribute(Type attribute_type, SecurityDeclaration declaration) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected I4, but got Unknown try { return (SecurityAttribute)Activator.CreateInstance(attribute_type, (SecurityAction)declaration.Action); } catch (MissingMethodException) { return (SecurityAttribute)Activator.CreateInstance(attribute_type, new object[0]); } } public static SecurityDeclaration ToSecurityDeclaration(this PermissionSet self, SecurityAction action, ModuleDefinition module) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected O, but got Unknown //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) if (self == null) { throw new ArgumentNullException("self"); } if (module == null) { throw new ArgumentNullException("module"); } SecurityDeclaration val = new SecurityDeclaration(action); SecurityAttribute val2 = new SecurityAttribute(module.TypeSystem.LookupType("System.Security.Permissions", "PermissionSetAttribute")); val2.Properties.Add(new CustomAttributeNamedArgument("XML", new CustomAttributeArgument(module.TypeSystem.String, (object)self.ToXml().ToString()))); val.SecurityAttributes.Add(val2); return val; } } public static class TypeDefinitionRocks { public static IEnumerable<MethodDefinition> GetConstructors(this TypeDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } if (!self.HasMethods) { return Empty<MethodDefinition>.Array; } return ((IEnumerable<MethodDefinition>)self.Methods).Where((MethodDefinition method) => method.IsConstructor); } public static MethodDefinition GetStaticConstructor(this TypeDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } if (!self.HasMethods) { return null; } return self.GetConstructors().FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition ctor) => ctor.IsStatic)); } public static IEnumerable<MethodDefinition> GetMethods(this TypeDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } if (!self.HasMethods) { return Empty<MethodDefinition>.Array; } return ((IEnumerable<MethodDefinition>)self.Methods).Where((MethodDefinition method) => !method.IsConstructor); } public static TypeReference GetEnumUnderlyingType(this TypeDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } if (!self.IsEnum) { throw new ArgumentException(); } return Mixin.GetEnumUnderlyingType(self); } } public static class TypeReferenceRocks { public static ArrayType MakeArrayType(this TypeReference self) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown return new ArrayType(self); } public static ArrayType MakeArrayType(this TypeReference self, int rank) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) if (rank == 0) { throw new ArgumentOutOfRangeException("rank"); } ArrayType val = new ArrayType(self); for (int i = 1; i < rank; i++) { val.Dimensions.Add(default(ArrayDimension)); } return val; } public static PointerType MakePointerType(this TypeReference self) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown return new PointerType(self); } public static ByReferenceType MakeByReferenceType(this TypeReference self) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown return new ByReferenceType(self); } public static OptionalModifierType MakeOptionalModifierType(this TypeReference self, TypeReference modifierType) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Expected O, but got Unknown return new OptionalModifierType(modifierType, self); } public static RequiredModifierType MakeRequiredModifierType(this TypeReference self, TypeReference modifierType) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Expected O, but got Unknown return new RequiredModifierType(modifierType, self); } public static GenericInstanceType MakeGenericInstanceType(this TypeReference self, params TypeReference[] arguments) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown if (self == null) { throw new ArgumentNullException("self"); } if (arguments == null) { throw new ArgumentNullException("arguments"); } if (arguments.Length == 0) { throw new ArgumentException(); } if (self.GenericParameters.Count != arguments.Length) { throw new ArgumentException(); } GenericInstanceType val = new GenericInstanceType(self, arguments.Length); foreach (TypeReference val2 in arguments) { val.GenericArguments.Add(val2); } return val; } public static PinnedType MakePinnedType(this TypeReference self) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown return new PinnedType(self); } public static SentinelType MakeSentinelType(this TypeReference self) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown return new SentinelType(self); } } }
BepInEx/patchers/BepInEx.GUI.Loader.dll
Decompiled a week agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using BepInEx.Configuration; using BepInEx.Logging; using Microsoft.CodeAnalysis; using Mono.Cecil; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("BepInEx.GUI.Loader")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+5d794489113d82bd626272a0636351c0a699afa3")] [assembly: AssemblyProduct("BepInEx.GUI.Loader")] [assembly: AssemblyTitle("BepInEx.GUI.Loader")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace BepInEx.GUI.Loader { public class CloseProcessOnChainloaderDone : ILogListener, IDisposable { private bool _disposed; private Process _process; public CloseProcessOnChainloaderDone(Process process) { _process = process; } public void Dispose() { _disposed = true; } public void LogEvent(object sender, LogEventArgs eventArgs) { //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 (!_disposed && eventArgs.Data.ToString() == "Chainloader startup complete") { LogLevel level = eventArgs.Level; if (((object)(LogLevel)(ref level)).Equals((object)(LogLevel)8) && Config.CloseWindowWhenGameLoadedConfig.Value) { Log.Message("Closing BepInEx.GUI"); KillBepInExGUIProcess(); } } } private void KillBepInExGUIProcess() { try { _process.Kill(); } catch (Exception ex) { Log.Error($"Error while trying to kill BepInEx GUI Process: {ex}"); Log.Error(ex); } finally { SendLogToClientSocket.Instance.Dispose(); Dispose(); } } } internal static class Config { internal const string FileName = "BepInEx.GUI.cfg"; internal const string EnableBepInExGUIConfigKey = "Enable BepInEx GUI"; internal const string EnableBepInExGUIConfigDescription = "Enable the custom BepInEx GUI"; internal const string CloseWindowWhenGameLoadedConfigKey = "Close Window When Game Loaded"; internal const string CloseWindowWhenGameLoadedConfigDescription = "Close the graphic user interface window when the game is loaded"; internal const string CloseWindowWhenGameClosesConfigKey = "Close Window When Game Closes"; internal const string CloseWindowWhenGameClosesConfigDescription = "Close the graphic user interface window when the game closes"; internal static string ConfigFilePath { get; private set; } private static ConfigFile File { get; set; } internal static ConfigEntry<bool> EnableBepInExGUIConfig { get; private set; } internal static ConfigEntry<bool> CloseWindowWhenGameLoadedConfig { get; private set; } internal static ConfigEntry<bool> CloseWindowWhenGameClosesConfig { get; private set; } internal static void Init(string folderFullPath) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown ConfigFilePath = Path.Combine(folderFullPath, "BepInEx.GUI.cfg"); File = new ConfigFile(ConfigFilePath, true); EnableBepInExGUIConfig = File.Bind<bool>("Settings", "Enable BepInEx GUI", true, "Enable the custom BepInEx GUI"); CloseWindowWhenGameLoadedConfig = File.Bind<bool>("Settings", "Close Window When Game Loaded", false, "Close the graphic user interface window when the game is loaded"); CloseWindowWhenGameClosesConfig = File.Bind<bool>("Settings", "Close Window When Game Closes", true, "Close the graphic user interface window when the game closes"); } } internal static class EntryPoint { public static IEnumerable<string> TargetDLLs { get; } = Array.Empty<string>(); public static void Patch(AssemblyDefinition _) { } public static void Initialize() { Log.Init(); try { InitializeInternal(); } catch (Exception ex) { Log.Error($"Failed to initialize : ({ex.GetType()}) {ex.Message}{Environment.NewLine}{ex}"); } } private static void InitializeInternal() { Config.Init(Paths.ConfigPath); ConfigEntry<bool> val = (ConfigEntry<bool>)typeof(BepInPlugin).Assembly.GetType("BepInEx.ConsoleManager", throwOnError: true).GetField("ConfigConsoleEnabled", BindingFlags.Static | BindingFlags.Public).GetValue(null); if (val.Value) { Log.Info("BepInEx regular console is enabled, aborting launch."); } else if (Config.EnableBepInExGUIConfig.Value) { FindAndLaunchGUI(); } else { Log.Info("Custom BepInEx.GUI is disabled in the config, aborting launch."); } } private static string FindGUIExecutable() { string[] files = Directory.GetFiles(Paths.PatcherPluginPath, "*", SearchOption.AllDirectories); foreach (string text in files) { string fileName = Path.GetFileName(text); if (fileName == "bepinex_gui.exe") { FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(text); if (versionInfo.FileMajorPart == 3) { Log.Info("Found bepinex_gui v3 executable in " + text); return text; } } } return null; } private static void FindAndLaunchGUI() { Log.Info("Finding and launching GUI"); string text = FindGUIExecutable(); if (text != null) { int num = FindFreePort(); Process process = LaunchGUI(text, num); if (process != null) { Logger.Listeners.Add((ILogListener)(object)new SendLogToClientSocket(num)); Logger.Listeners.Add((ILogListener)(object)new CloseProcessOnChainloaderDone(process)); } else { Log.Info("LaunchGUI failed"); } } else { Log.Info("bepinex_gui executable not found."); } } private static int FindFreePort() { int result = 0; Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 0); socket.Bind(localEP); localEP = (IPEndPoint)socket.LocalEndPoint; result = localEP.Port; } finally { socket.Close(); } return result; } private static Process LaunchGUI(string executablePath, int socketPort) { ProcessStartInfo processStartInfo = new ProcessStartInfo(); processStartInfo.FileName = executablePath; processStartInfo.WorkingDirectory = Path.GetDirectoryName(executablePath); processStartInfo.Arguments = $"\"{typeof(Paths).Assembly.GetName().Version}\" " + "\"" + Paths.ProcessName + "\" \"" + Paths.GameRootPath + "\" \"" + GetLogOutputFilePath() + "\" \"" + Config.ConfigFilePath + "\" " + $"\"{Process.GetCurrentProcess().Id}\" " + $"\"{socketPort}\""; return Process.Start(processStartInfo); } private static string GetLogOutputFilePath() { foreach (ILogListener listener in Logger.Listeners) { DiskLogListener val = (DiskLogListener)(object)((listener is DiskLogListener) ? listener : null); if (val != null) { return val.FileFullPath; } } return ""; } } internal static class Log { private static ManualLogSource _logSource; internal static void Init() { _logSource = Logger.CreateLogSource("BepInEx.GUI.Loader"); } internal static void Debug(object data) { _logSource.LogDebug(data); } internal static void Error(object data) { _logSource.LogError(data); } internal static void Fatal(object data) { _logSource.LogFatal(data); } internal static void Info(object data) { _logSource.LogInfo(data); } internal static void Message(object data) { _logSource.LogMessage(data); } internal static void Warning(object data) { _logSource.LogWarning(data); } } internal struct LogPacket { internal byte[] Bytes; internal unsafe LogPacket(LogEventArgs log) { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected I4, but got Unknown byte[] bytes = Encoding.UTF8.GetBytes(((object)log).ToString()); int num = bytes.Length; Bytes = new byte[8 + num]; fixed (byte* ptr = Bytes) { *(int*)ptr = num; *(int*)(ptr + 4) = (int)log.Level; Marshal.Copy(bytes, 0, (IntPtr)(ptr + 8), num); } } } internal class SendLogToClientSocket : ILogListener, IDisposable { private int _freePort; private readonly Thread _thread; private readonly object _queueLock = new object(); private readonly Queue<LogEventArgs> _logQueue = new Queue<LogEventArgs>(); private bool _isDisposed = false; private bool _gotFirstLog = false; internal static SendLogToClientSocket Instance { get; private set; } internal SendLogToClientSocket(int freePort) { Instance = this; _freePort = freePort; _thread = new Thread((ThreadStart)delegate { IPAddress localaddr = IPAddress.Parse("127.0.0.1"); TcpListener tcpListener = new TcpListener(localaddr, _freePort); tcpListener.Start(); while (true) { Log.Info("[SendLogToClient] Accepting Socket."); Socket clientSocket = tcpListener.AcceptSocket(); if (_isDisposed) { break; } SendPacketsToClientUntilConnectionIsClosed(clientSocket); } }); _thread.Start(); } private void SendPacketsToClientUntilConnectionIsClosed(Socket clientSocket) { while (!_isDisposed) { while (_logQueue.Count > 0) { LogEventArgs log; lock (_queueLock) { log = _logQueue.Peek(); } LogPacket logPacket = new LogPacket(log); try { clientSocket.Send(logPacket.Bytes); } catch (Exception arg) { Log.Error($"Error while trying to send log to socket: {arg}{Environment.NewLine}Disconnecting socket."); return; } lock (_queueLock) { _logQueue.Dequeue(); } } Thread.Sleep(17); } } public void Dispose() { _isDisposed = true; } internal void StoreLog(LogEventArgs eventArgs) { lock (_queueLock) { _logQueue.Enqueue(eventArgs); } } public void LogEvent(object sender, LogEventArgs eventArgs) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Invalid comparison between Unknown and I4 if (_isDisposed || eventArgs.Data == null) { return; } if (!_gotFirstLog) { if ((int)eventArgs.Level == 8 && eventArgs.Source.SourceName == "BepInEx" && eventArgs.Data.ToString().StartsWith("BepInEx")) { _gotFirstLog = true; } } else { StoreLog(eventArgs); } } } }
BepInEx/patchers/RemoveOldCecil.dll
Decompiled a week agousing 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 BepInEx; using BepInEx.Logging; using Microsoft.CodeAnalysis; using Mono.Cecil; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyCompany("RemoveOldCecil")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("RemoveOldCecil")] [assembly: AssemblyTitle("RemoveOldCecil")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } public static class Patcher { public const string GUID = "_.prodzpod.RemoveOldCecil"; public static ManualLogSource Log; public static IEnumerable<string> TargetDLLs { get; } = new string[0]; public static void Initialize() { Log = Logger.CreateLogSource("_.prodzpod.RemoveOldCecil"); string dir = Path.Combine(Paths.GameRootPath, "CoreKeeper_Data\\Managed"); string[] source = new string[4] { "Mono.Cecil.dll", "Mono.Cecil.Mdb.dll", "Mono.Cecil.Pdb.dll", "Mono.Cecil.Rocks.dll" }; source = source.Select((string x) => Path.Combine(dir, x)).ToArray(); if (source.Any(File.Exists)) { Log.LogInfo((object)"Old Cecil Detected, Launching Deleter..."); Process process = Process.Start(new ProcessStartInfo { FileName = Assembly.GetExecutingAssembly().Location.Replace("RemoveOldCecil.dll", "RemoveOldCecilConsole.exe"), Arguments = string.Join(" ", source.Select((string x) => "\"" + x + "\"").ToArray()), CreateNoWindow = false }); Log.LogInfo((object)"Deleter Launched."); } } public static void Patch(AssemblyDefinition _) { } }
BepInEx/patchers/RemoveOldCecilConsole.dll
Decompiled a week agousing System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Threading; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: TargetFramework(".NETCoreApp,Version=v8.0", FrameworkDisplayName = ".NET 8.0")] [assembly: AssemblyCompany("RemoveOldCecilConsole")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("RemoveOldCecilConsole")] [assembly: AssemblyTitle("RemoveOldCecilConsole")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] public class RemoveOldCecilConsole { public static void Main(string[] args) { Console.WriteLine($"Trying to delete {args.Length} files, try closing & rebooting the game if it doesn't finish."); foreach (string text in args) { Console.WriteLine("Waiting for " + text + " to be available"); while (true) { try { if (File.Exists(text)) { File.Delete(text); } } catch { Thread.Sleep(1000); continue; } break; } } Console.WriteLine("Setup complete!"); } }
FixModIOMods.dll
Decompiled a week agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using Mono.Cecil.Cil; using MonoMod.Cil; using RoslynCSharp.Compiler; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("FixModIOMods")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("FixModIOMods")] [assembly: AssemblyTitle("FixModIOMods")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FixModIOMods { [BepInPlugin("000.prodzpod.FixModIOMods", "FixModIOMods", "1.0.0")] public class Main : BaseUnityPlugin { public class MonoIssue { public static string LastLocation = ""; public static void ILManipulator(ILContext il, MethodBase original, ILLabel retLabel) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown //IL_000c: Unknown result type (might be due to invalid IL or missing references) ILCursor val = new ILCursor(il); while (val.TryGotoNext((MoveType)2, new Func<Instruction, bool>[1] { (Instruction x) => ILPatternMatchingExt.MatchCallOrCallvirt<Assembly>(x, "get_Location") })) { val.Emit(OpCodes.Ldarg_1); val.EmitDelegate<Func<string, Assembly, string>>((Func<string, Assembly, string>)delegate(string res, Assembly self) { if (string.IsNullOrEmpty(res)) { string text = LastLocation.Substring(0, LastLocation.LastIndexOf('\\')) + "\\" + self.GetName().Name + ".dll"; Log.LogInfo((object)("Fixing " + text)); return text; } LastLocation = res; return res; }); } } public static MethodBase TargetMethod() { return typeof(AssemblyReferenceFromAssemblyObject).GetConstructor(new Type[1] { typeof(Assembly) }); } } public const string PluginGUID = "000.prodzpod.FixModIOMods"; public const string PluginAuthor = "prodzpod"; public const string PluginName = "FixModIOMods"; public const string PluginVersion = "1.0.0"; public static ManualLogSource Log; public static PluginInfo pluginInfo; public static Harmony Harmony; public static ConfigFile Config; public static Main Instance; public void Awake() { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown pluginInfo = ((BaseUnityPlugin)this).Info; Log = ((BaseUnityPlugin)this).Logger; Instance = this; Harmony = new Harmony("000.prodzpod.FixModIOMods"); Harmony.PatchAll(typeof(MonoIssue)); } } }