using System; using System.Buffers; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic; 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.Threading; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; using MonoMod; using MonoMod.Cil; using MonoMod.Logs; using MonoMod.SourceGen.Attributes; using MonoMod.Utils; using MonoMod.Utils.Cil; using MonoMod.Utils.Interop; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: DisableRuntimeMarshalling] [assembly: TargetFramework(".NETCoreApp,Version=v8.0", FrameworkDisplayName = ".NET 8.0")] [assembly: InternalsVisibleTo("MonoMod.Utils.Cil.ILGeneratorProxy")] [assembly: AssemblyCompany("0x0ade, DaNike")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2026 0x0ade, DaNike")] [assembly: AssemblyDescription("Utilities and smaller MonoMod \"components\" (f.e. ModInterop, DynDll, DynData). Can be used for your own mods. Required by all other MonoMod components.")] [assembly: AssemblyFileVersion("25.0.12.0")] [assembly: AssemblyInformationalVersion("25.0.12+69fdc9deb")] [assembly: AssemblyProduct("MonoMod.Utils")] [assembly: AssemblyTitle("MonoMod.Utils")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/MonoMod/MonoMod")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("25.0.12.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] internal class { static () { MMDbgLog.LogVersion(); } } namespace MonoMod { public static class Switches { private static readonly ConcurrentDictionary switchValues; private const string Prefix = "MONOMOD_"; public const string RunningOnWine = "RunningOnWine"; public const string DebugClr = "DebugClr"; public const string JitPath = "JitPath"; public const string HelperDropPath = "HelperDropPath"; public const string LogRecordHoles = "LogRecordHoles"; public const string LogInMemory = "LogInMemory"; public const string LogSpam = "LogSpam"; public const string LogReplayQueueLength = "LogReplayQueueLength"; public const string LogToFile = "LogToFile"; public const string LogToFileFilter = "LogToFileFilter"; public const string DMDType = "DMDType"; public const string DMDDebug = "DMDDebug"; public const string DMDDumpTo = "DMDDumpTo"; static Switches() { switchValues = new ConcurrentDictionary(); foreach (DictionaryEntry environmentVariable in Environment.GetEnvironmentVariables()) { string text = (string)environmentVariable.Key; if (text.StartsWith("MONOMOD_", StringComparison.Ordinal) && environmentVariable.Value != null) { string key = text.Substring("MONOMOD_".Length); switchValues.TryAdd(key, BestEffortParseEnvVar((string)environmentVariable.Value)); } } } private static object? BestEffortParseEnvVar(string value) { if (value.Length == 0) { return null; } if (int.TryParse(value, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var result)) { return result; } if (long.TryParse(value, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var result2)) { return result2; } if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out result)) { return result; } if (long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out result2)) { return result2; } bool flag; switch (value[0]) { case 'F': case 'N': case 'T': case 'Y': case 'f': case 'n': case 't': case 'y': flag = true; break; default: flag = false; break; } if (flag) { if (bool.TryParse(value, out var result3)) { return result3; } if (value.Equals("yes", StringComparison.OrdinalIgnoreCase) || value.Equals("y", StringComparison.OrdinalIgnoreCase)) { return true; } if (value.Equals("no", StringComparison.OrdinalIgnoreCase) || value.Equals("n", StringComparison.OrdinalIgnoreCase)) { return false; } } return value; } public static void SetSwitchValue(string @switch, object? value) { switchValues[@switch] = value; } public static void ClearSwitchValue(string @switch) { switchValues.TryRemove(@switch, out object _); } public static bool TryGetSwitchValue(string @switch, out object? value) { if (switchValues.TryGetValue(@switch, out value)) { return true; } string text = "MonoMod." + @switch; object data = AppContext.GetData(text); if (data != null) { value = data; return true; } if (AppContext.TryGetSwitch(text, out var isEnabled)) { value = isEnabled; return true; } value = null; return false; } public static bool TryGetSwitchEnabled(string @switch, out bool isEnabled) { if (switchValues.TryGetValue(@switch, out object value) && value != null && TryProcessBoolData(value, out isEnabled)) { return true; } string text = "MonoMod." + @switch; if (AppContext.TryGetSwitch(text, out isEnabled)) { return true; } object data = AppContext.GetData(text); if (data != null && TryProcessBoolData(data, out isEnabled)) { return true; } isEnabled = false; return false; } private static bool TryProcessBoolData(object data, out bool boolVal) { if (!(data is bool flag)) { if (!(data is int num)) { if (!(data is long num2)) { IConvertible convertible; if (!(data is string value)) { convertible = data as IConvertible; if (convertible == null) { boolVal = false; return false; } } else { if (bool.TryParse(value, out boolVal)) { return true; } convertible = (IConvertible)data; } IConvertible convertible2 = convertible; boolVal = convertible2.ToBoolean(CultureInfo.CurrentCulture); return true; } long num3 = num2; boolVal = num3 != 0; return true; } int num4 = num; boolVal = num4 != 0; return true; } bool flag2 = flag; boolVal = flag2; return true; } } internal static class MMDbgLog { [InterpolatedStringHandler] internal ref struct DebugLogSpamStringHandler { internal DebugLogInterpolatedStringHandler handler; public DebugLogSpamStringHandler(int literalLen, int formattedCount, out bool isEnabled) { handler = new DebugLogInterpolatedStringHandler(literalLen, formattedCount, LogLevel.Spam, out isEnabled); } public override string ToString() { return handler.ToString(); } public string ToStringAndClear() { return handler.ToStringAndClear(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendLiteral(string s) { handler.AppendLiteral(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(string? s) { handler.AppendFormatted(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(string? s, int alignment = 0, string? format = null) { handler.AppendFormatted(s, alignment, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(ReadOnlySpan s) { handler.AppendFormatted(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(ReadOnlySpan s, int alignment = 0, string? format = null) { handler.AppendFormatted(s, alignment, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value) { handler.AppendFormatted(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, int alignment) { handler.AppendFormatted(value, alignment); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, string? format) { handler.AppendFormatted(value, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, int alignment, string? format) { handler.AppendFormatted(value, alignment, format); } } [InterpolatedStringHandler] internal ref struct DebugLogTraceStringHandler { internal DebugLogInterpolatedStringHandler handler; public DebugLogTraceStringHandler(int literalLen, int formattedCount, out bool isEnabled) { handler = new DebugLogInterpolatedStringHandler(literalLen, formattedCount, LogLevel.Trace, out isEnabled); } public override string ToString() { return handler.ToString(); } public string ToStringAndClear() { return handler.ToStringAndClear(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendLiteral(string s) { handler.AppendLiteral(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(string? s) { handler.AppendFormatted(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(string? s, int alignment = 0, string? format = null) { handler.AppendFormatted(s, alignment, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(ReadOnlySpan s) { handler.AppendFormatted(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(ReadOnlySpan s, int alignment = 0, string? format = null) { handler.AppendFormatted(s, alignment, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value) { handler.AppendFormatted(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, int alignment) { handler.AppendFormatted(value, alignment); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, string? format) { handler.AppendFormatted(value, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, int alignment, string? format) { handler.AppendFormatted(value, alignment, format); } } [InterpolatedStringHandler] internal ref struct DebugLogInfoStringHandler { internal DebugLogInterpolatedStringHandler handler; public DebugLogInfoStringHandler(int literalLen, int formattedCount, out bool isEnabled) { handler = new DebugLogInterpolatedStringHandler(literalLen, formattedCount, LogLevel.Info, out isEnabled); } public override string ToString() { return handler.ToString(); } public string ToStringAndClear() { return handler.ToStringAndClear(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendLiteral(string s) { handler.AppendLiteral(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(string? s) { handler.AppendFormatted(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(string? s, int alignment = 0, string? format = null) { handler.AppendFormatted(s, alignment, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(ReadOnlySpan s) { handler.AppendFormatted(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(ReadOnlySpan s, int alignment = 0, string? format = null) { handler.AppendFormatted(s, alignment, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value) { handler.AppendFormatted(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, int alignment) { handler.AppendFormatted(value, alignment); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, string? format) { handler.AppendFormatted(value, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, int alignment, string? format) { handler.AppendFormatted(value, alignment, format); } } [InterpolatedStringHandler] internal ref struct DebugLogWarningStringHandler { internal DebugLogInterpolatedStringHandler handler; public DebugLogWarningStringHandler(int literalLen, int formattedCount, out bool isEnabled) { handler = new DebugLogInterpolatedStringHandler(literalLen, formattedCount, LogLevel.Warning, out isEnabled); } public override string ToString() { return handler.ToString(); } public string ToStringAndClear() { return handler.ToStringAndClear(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendLiteral(string s) { handler.AppendLiteral(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(string? s) { handler.AppendFormatted(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(string? s, int alignment = 0, string? format = null) { handler.AppendFormatted(s, alignment, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(ReadOnlySpan s) { handler.AppendFormatted(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(ReadOnlySpan s, int alignment = 0, string? format = null) { handler.AppendFormatted(s, alignment, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value) { handler.AppendFormatted(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, int alignment) { handler.AppendFormatted(value, alignment); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, string? format) { handler.AppendFormatted(value, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, int alignment, string? format) { handler.AppendFormatted(value, alignment, format); } } [InterpolatedStringHandler] internal ref struct DebugLogErrorStringHandler { internal DebugLogInterpolatedStringHandler handler; public DebugLogErrorStringHandler(int literalLen, int formattedCount, out bool isEnabled) { handler = new DebugLogInterpolatedStringHandler(literalLen, formattedCount, LogLevel.Error, out isEnabled); } public override string ToString() { return handler.ToString(); } public string ToStringAndClear() { return handler.ToStringAndClear(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendLiteral(string s) { handler.AppendLiteral(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(string? s) { handler.AppendFormatted(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(string? s, int alignment = 0, string? format = null) { handler.AppendFormatted(s, alignment, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(ReadOnlySpan s) { handler.AppendFormatted(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(ReadOnlySpan s, int alignment = 0, string? format = null) { handler.AppendFormatted(s, alignment, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value) { handler.AppendFormatted(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, int alignment) { handler.AppendFormatted(value, alignment); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, string? format) { handler.AppendFormatted(value, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, int alignment, string? format) { handler.AppendFormatted(value, alignment, format); } } public static bool IsWritingLog => DebugLog.IsWritingLog; [ModuleInitializer] internal static void LogVersion() { Info("Version 25.0.12"); } public static void Log(LogLevel level, string message) { DebugLog.Log("MonoMod.Utils", level, message); } public static void Log(LogLevel level, [InterpolatedStringHandlerArgument("level")] ref DebugLogInterpolatedStringHandler message) { DebugLog.Log("MonoMod.Utils", level, ref message); } public static void Spam(string message) { Log(LogLevel.Spam, message); } public static void Spam(ref DebugLogSpamStringHandler message) { Log(LogLevel.Spam, ref message.handler); } public static void Trace(string message) { Log(LogLevel.Trace, message); } public static void Trace(ref DebugLogTraceStringHandler message) { Log(LogLevel.Trace, ref message.handler); } public static void Info(string message) { Log(LogLevel.Info, message); } public static void Info(ref DebugLogInfoStringHandler message) { Log(LogLevel.Info, ref message.handler); } public static void Warning(string message) { Log(LogLevel.Warning, message); } public static void Warning(ref DebugLogWarningStringHandler message) { Log(LogLevel.Warning, ref message.handler); } public static void Error(string message) { Log(LogLevel.Error, message); } public static void Error(ref DebugLogErrorStringHandler message) { Log(LogLevel.Error, ref message.handler); } } internal static class MultiTargetShims { public static TypeReference GetConstraintType(this GenericParameterConstraint constraint) { return constraint.ConstraintType; } } } namespace MonoMod.SourceGen.Attributes { [AttributeUsage(AttributeTargets.Class)] internal sealed class EmitILOverloadsAttribute : Attribute { public EmitILOverloadsAttribute(string filename, string kind) { } } internal static class ILOverloadKind { public const string Cursor = "ILCursor"; public const string Matcher = "ILMatcher"; } } namespace MonoMod.ModInterop { [AttributeUsage(AttributeTargets.Class)] public sealed class ModExportNameAttribute : Attribute { public string Name { get; } public ModExportNameAttribute(string name) { Name = name; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Field)] public sealed class ModImportNameAttribute : Attribute { public string Name { get; } public ModImportNameAttribute(string name) { Name = name; } } public static class ModInteropManager { private static HashSet Registered = new HashSet(); private static Dictionary> Methods = new Dictionary>(); private static List Fields = new List(); public static void ModInterop(this Type type) { Helpers.ThrowIfArgumentNull(type, "type"); if (Registered.Contains(type)) { return; } Registered.Add(type); string name = type.Assembly.GetName().Name; object[] customAttributes = type.GetCustomAttributes(typeof(ModExportNameAttribute), inherit: false); for (int i = 0; i < customAttributes.Length; i++) { name = ((ModExportNameAttribute)customAttributes[i]).Name; } FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public); foreach (FieldInfo fieldInfo in fields) { if (typeof(Delegate).IsAssignableFrom(fieldInfo.FieldType)) { Fields.Add(fieldInfo); } } MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public); foreach (MethodInfo method in methods) { method.RegisterModExport(); method.RegisterModExport(name); } foreach (FieldInfo field in Fields) { if (!Methods.TryGetValue(field.GetModImportName(), out List value)) { field.SetValue(null, null); continue; } bool flag = false; foreach (MethodInfo item in value) { try { field.SetValue(null, Delegate.CreateDelegate(field.FieldType, null, item)); flag = true; } catch { continue; } break; } if (!flag) { field.SetValue(null, null); } } } public static void RegisterModExport(this MethodInfo method, string? prefix = null) { Helpers.ThrowIfArgumentNull(method, "method"); if (!method.IsPublic || !method.IsStatic) { throw new MemberAccessException("Utility must be public static"); } string text = method.Name; if (!string.IsNullOrEmpty(prefix)) { text = prefix + "." + text; } if (!Methods.TryGetValue(text, out List value)) { value = (Methods[text] = new List()); } if (!value.Contains(method)) { value.Add(method); } } private static string GetModImportName(this FieldInfo field) { object[] customAttributes = field.GetCustomAttributes(typeof(ModImportNameAttribute), inherit: false); int num = 0; if (num < customAttributes.Length) { return ((ModImportNameAttribute)customAttributes[num]).Name; } if ((object)field.DeclaringType != null) { customAttributes = field.DeclaringType.GetCustomAttributes(typeof(ModImportNameAttribute), inherit: false); num = 0; if (num < customAttributes.Length) { return ((ModImportNameAttribute)customAttributes[num]).Name + "." + field.Name; } } return field.Name; } } } namespace MonoMod.Logs { public static class DebugFormatter { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool CanDebugFormat(in T value, out object? extraData) { extraData = null; if (typeof(T) == typeof(Type)) { return true; } if (typeof(T) == typeof(MethodBase)) { return true; } if (typeof(T) == typeof(MethodInfo)) { return true; } if (typeof(T) == typeof(ConstructorInfo)) { return true; } if (typeof(T) == typeof(FieldInfo)) { return true; } if (typeof(T) == typeof(PropertyInfo)) { return true; } if (typeof(T) == typeof(Exception)) { return true; } if (typeof(T) == typeof(IDebugFormattable)) { return true; } T val = value; if ((val is Type || val is MethodBase || val is FieldInfo || val is PropertyInfo) ? true : false) { return true; } if (value is Exception ex) { extraData = ex.ToString(); return true; } if (value is IDebugFormattable) { return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryFormatInto(in T value, object? extraData, Span into, out int wrote) { if (default(T) == null && value == null) { wrote = 0; return true; } if (typeof(T) == typeof(Type)) { return TryFormatType(Transmute(in value), into, out wrote); } if (typeof(T) == typeof(MethodInfo)) { return TryFormatMethodInfo(Transmute(in value), into, out wrote); } if (typeof(T) == typeof(ConstructorInfo)) { return TryFormatMethodBase(Transmute(in value), into, out wrote); } if (typeof(T) == typeof(FieldInfo)) { return TryFormatFieldInfo(Transmute(in value), into, out wrote); } if (typeof(T) == typeof(PropertyInfo)) { return TryFormatPropertyInfo(Transmute(in value), into, out wrote); } if (typeof(T) == typeof(Exception)) { return TryFormatException(Transmute(in value), Unsafe.As(extraData), into, out wrote); } if (typeof(T) == typeof(IDebugFormattable)) { return Transmute(in value).TryFormatInto(into, out wrote); } if (value is Type type) { return TryFormatType(type, into, out wrote); } if (value is MethodInfo method) { return TryFormatMethodInfo(method, into, out wrote); } if (value is ConstructorInfo method2) { return TryFormatMethodBase(method2, into, out wrote); } if (value is MethodBase method3) { return TryFormatMethodBase(method3, into, out wrote); } if (value is FieldInfo field) { return TryFormatFieldInfo(field, into, out wrote); } if (value is PropertyInfo prop) { return TryFormatPropertyInfo(prop, into, out wrote); } if (value is Exception e) { return TryFormatException(e, Unsafe.As(extraData), into, out wrote); } if (value is IDebugFormattable) { return ((IDebugFormattable)(object)value).TryFormatInto(into, out wrote); } bool flag = false; bool isEnabled; AssertionInterpolatedStringHandler message = new AssertionInterpolatedStringHandler(48, 1, flag, out isEnabled); if (isEnabled) { message.AppendLiteral("Called TryFormatInto with value of unknown type "); message.AppendFormatted(value.GetType()); } Helpers.Assert(flag, ref message, "false"); wrote = 0; return false; [MethodImpl(MethodImplOptions.AggressiveInlining)] static ref TOut Transmute(in T val) { return ref Unsafe.As(ref Unsafe.AsRef(in val)); } } private static bool TryFormatException(Exception e, string? eStr, Span into, out int wrote) { wrote = 0; if (eStr == null) { eStr = e.ToString(); } string newLine = Environment.NewLine; if (into.Slice(wrote).Length < eStr.Length) { return false; } eStr.AsSpan().CopyTo(into.Slice(wrote)); wrote += eStr.Length; int wrote2; if (e is ReflectionTypeLoadException ex) { for (int i = 0; i < 4 && i < ex.Types.Length; i++) { Span span = into.Slice(wrote); Span span2 = span; bool enabled; FormatIntoInterpolatedStringHandler handler = new FormatIntoInterpolatedStringHandler(56, 3, span, out enabled); if (enabled && handler.AppendFormatted(newLine) && handler.AppendLiteral("System.Reflection.ReflectionTypeLoadException.Types[") && handler.AppendFormatted(i) && handler.AppendLiteral("] = ")) { handler.AppendFormatted(ex.Types[i]); } else _ = 0; if (!Into(span2, out wrote2, ref handler)) { return false; } wrote += wrote2; } if (ex.Types.Length >= 4) { Span span = into.Slice(wrote); Span span3 = span; bool enabled2; FormatIntoInterpolatedStringHandler handler2 = new FormatIntoInterpolatedStringHandler(62, 1, span, out enabled2); if (enabled2 && handler2.AppendFormatted(newLine)) { handler2.AppendLiteral("System.Reflection.ReflectionTypeLoadException.Types[...] = ..."); } else _ = 0; if (!Into(span3, out wrote2, ref handler2)) { return false; } wrote += wrote2; } if (ex.LoaderExceptions.Length != 0) { if (into.Slice(wrote).Length < newLine.Length + "System.Reflection.ReflectionTypeLoadException.LoaderExceptions = [".Length) { return false; } newLine.AsSpan().CopyTo(into.Slice(wrote)); wrote += newLine.Length; "System.Reflection.ReflectionTypeLoadException.LoaderExceptions = [".AsSpan().CopyTo(into.Slice(wrote)); wrote += "System.Reflection.ReflectionTypeLoadException.LoaderExceptions = [".Length; for (int j = 0; j < ex.LoaderExceptions.Length; j++) { Exception ex2 = ex.LoaderExceptions[j]; if (ex2 != null) { if (into.Slice(wrote).Length < newLine.Length) { return false; } newLine.AsSpan().CopyTo(into.Slice(wrote)); wrote += newLine.Length; if (!TryFormatException(ex2, null, into.Slice(wrote), out wrote2)) { return false; } wrote += wrote2; } } if (into.Slice(wrote).Length < newLine.Length + 1) { return false; } newLine.AsSpan().CopyTo(into.Slice(wrote)); wrote += newLine.Length; into[wrote++] = ']'; } } if (e is TypeLoadException ex3) { Span span = into.Slice(wrote); Span span4 = span; bool enabled3; FormatIntoInterpolatedStringHandler handler3 = new FormatIntoInterpolatedStringHandler(36, 2, span, out enabled3); if (enabled3 && handler3.AppendFormatted(newLine) && handler3.AppendLiteral("System.TypeLoadException.TypeName = ")) { handler3.AppendFormatted(ex3.TypeName); } else _ = 0; if (!Into(span4, out wrote2, ref handler3)) { return false; } wrote += wrote2; } if (e is BadImageFormatException ex4) { Span span = into.Slice(wrote); Span span5 = span; bool enabled4; FormatIntoInterpolatedStringHandler handler4 = new FormatIntoInterpolatedStringHandler(42, 2, span, out enabled4); if (enabled4 && handler4.AppendFormatted(newLine) && handler4.AppendLiteral("System.BadImageFormatException.FileName = ")) { handler4.AppendFormatted(ex4.FileName); } else _ = 0; if (!Into(span5, out wrote2, ref handler4)) { return false; } wrote += wrote2; } return true; } private static bool TryFormatType(Type type, Span into, out int wrote) { wrote = 0; string text; if (type.HasElementType && type.GetElementType() == null) { text = type.Name; } else { string fullName = type.FullName; if (fullName == null) { return true; } text = fullName; } if (into.Length < text.Length) { return false; } text.AsSpan().CopyTo(into); wrote = text.Length; return true; } private static bool TryFormatMethodInfo(MethodInfo method, Span into, out int wrote) { Type returnType = method.ReturnType; wrote = 0; if (!TryFormatType(returnType, into.Slice(wrote), out var wrote2)) { return false; } wrote += wrote2; if (into.Slice(wrote).Length < 1) { return false; } into[wrote++] = ' '; if (!TryFormatMethodBase(method, into.Slice(wrote), out wrote2)) { return false; } wrote += wrote2; return true; } private static bool TryFormatMemberInfoName(MemberInfo member, Span into, out int wrote) { wrote = 0; Type declaringType = member.DeclaringType; if ((object)declaringType != null) { if (!TryFormatType(declaringType, into.Slice(wrote), out var wrote2)) { return false; } wrote += wrote2; if (into.Slice(wrote).Length < 1) { return false; } into[wrote++] = ':'; } string name = member.Name; if (into.Slice(wrote).Length < name.Length) { return false; } name.AsSpan().CopyTo(into.Slice(wrote)); wrote += name.Length; return true; } private static bool TryFormatMethodBase(MethodBase method, Span into, out int wrote) { wrote = 0; if (!TryFormatMemberInfoName(method, into.Slice(wrote), out var wrote2)) { return false; } wrote += wrote2; if (method.IsGenericMethod) { if (into.Slice(wrote).Length < 1) { return false; } into[wrote++] = '<'; Type[] genericArguments = method.GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { if (i != 0) { if (into.Slice(wrote).Length < 2) { return false; } into[wrote++] = ','; into[wrote++] = ' '; } if (!TryFormatType(genericArguments[i], into.Slice(wrote), out wrote2)) { return false; } wrote += wrote2; } if (into.Slice(wrote).Length < 1) { return false; } into[wrote++] = '>'; } ParameterInfo[] parameters = method.GetParameters(); if (into.Slice(wrote).Length < 1) { return false; } into[wrote++] = '('; for (int j = 0; j < parameters.Length; j++) { if (j != 0) { if (into.Slice(wrote).Length < 2) { return false; } into[wrote++] = ','; into[wrote++] = ' '; } if (!TryFormatType(parameters[j].ParameterType, into.Slice(wrote), out wrote2)) { return false; } wrote += wrote2; } if (into.Slice(wrote).Length < 1) { return false; } into[wrote++] = ')'; return true; } private static bool TryFormatFieldInfo(FieldInfo field, Span into, out int wrote) { wrote = 0; if (!TryFormatType(field.FieldType, into.Slice(wrote), out var wrote2)) { return false; } wrote += wrote2; if (into.Slice(wrote).Length < 1) { return false; } into[wrote++] = ' '; if (!TryFormatMemberInfoName(field, into.Slice(wrote), out wrote2)) { return false; } wrote += wrote2; return true; } private static bool TryFormatPropertyInfo(PropertyInfo prop, Span into, out int wrote) { wrote = 0; if (!TryFormatType(prop.PropertyType, into.Slice(wrote), out var wrote2)) { return false; } wrote += wrote2; if (into.Slice(wrote).Length < 1) { return false; } into[wrote++] = ' '; if (!TryFormatMemberInfoName(prop, into.Slice(wrote), out wrote2)) { return false; } wrote += wrote2; bool canRead = prop.CanRead; bool canWrite = prop.CanWrite; int num = 5 + (canRead ? 4 : 0) + (canWrite ? 4 : 0) + ((canRead && canWrite) ? 1 : 0); if (into.Slice(wrote).Length < num) { return false; } " { ".AsSpan().CopyTo(into.Slice(wrote)); wrote += 3; if (canRead) { "get;".AsSpan().CopyTo(into.Slice(wrote)); wrote += 4; } if (canRead && canWrite) { into[wrote++] = ' '; } if (canWrite) { "set;".AsSpan().CopyTo(into.Slice(wrote)); wrote += 4; } " }".AsSpan().CopyTo(into.Slice(wrote)); wrote += 2; return true; } public static string Format(ref FormatInterpolatedStringHandler handler) { return handler.ToStringAndClear(); } public static bool Into(Span into, out int wrote, [InterpolatedStringHandlerArgument("into")] ref FormatIntoInterpolatedStringHandler handler) { wrote = handler.pos; return !handler.incomplete; } } [InterpolatedStringHandler] public ref struct FormatInterpolatedStringHandler { private DebugLogInterpolatedStringHandler handler; [MethodImpl(MethodImplOptions.AggressiveInlining)] public FormatInterpolatedStringHandler(int literalLen, int formattedCount) { handler = new DebugLogInterpolatedStringHandler(literalLen, formattedCount, enabled: true, recordHoles: false, out var _); } public override string ToString() { return handler.ToString(); } public string ToStringAndClear() { return handler.ToStringAndClear(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendLiteral(string s) { handler.AppendLiteral(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(string? s) { handler.AppendFormatted(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(string? s, int alignment = 0, string? format = null) { handler.AppendFormatted(s, alignment, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(ReadOnlySpan s) { handler.AppendFormatted(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(ReadOnlySpan s, int alignment = 0, string? format = null) { handler.AppendFormatted(s, alignment, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value) { handler.AppendFormatted(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, int alignment) { handler.AppendFormatted(value, alignment); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, string? format) { handler.AppendFormatted(value, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, int alignment, string? format) { handler.AppendFormatted(value, alignment, format); } } public readonly record struct MessageHole { public int Start { get; } public int End { get; } public object? Value { get; } public bool IsValueUnrepresentable { get; } public MessageHole(int start, int end) { Value = null; IsValueUnrepresentable = true; Start = start; End = end; } public MessageHole(int start, int end, object? value) { Value = value; IsValueUnrepresentable = false; Start = start; End = end; } } public sealed class DebugLog { public delegate void OnLogMessage(string source, DateTime time, LogLevel level, string message); public delegate void OnLogMessageDetailed(string source, DateTime time, LogLevel level, string formattedMessage, ReadOnlyMemory holes); private sealed class LogMessage { public string Source { get; private set; } public DateTime Time { get; private set; } public LogLevel Level { get; private set; } public string FormattedMessage { get; private set; } public ReadOnlyMemory FormatHoles { get; private set; } public LogMessage(string source, DateTime time, LogLevel level, string formatted, ReadOnlyMemory holes) { Source = source; Time = time; Level = level; FormattedMessage = formatted; FormatHoles = holes; } public void Clear() { Source = ""; Time = default(DateTime); Level = LogLevel.Spam; FormattedMessage = ""; FormatHoles = default(ReadOnlyMemory); } public void Init(string source, DateTime time, LogLevel level, string formatted, ReadOnlyMemory holes) { Source = source; Time = time; Level = level; FormattedMessage = formatted; FormatHoles = holes; } public void ReportTo(OnLogMessage del) { try { del(Source, Time, Level, FormattedMessage); } catch (Exception ex) { Debugger.Log(int.MaxValue, "MonoMod.DebugLog", "Exception caught while reporting to message handler"); Debugger.Log(int.MaxValue, "MonoMod.DebugLog", ex.ToString()); } } public void ReportTo(OnLogMessageDetailed del) { try { del(Source, Time, Level, FormattedMessage, FormatHoles); } catch (Exception ex) { Debugger.Log(int.MaxValue, "MonoMod.DebugLog", "Exception caught while reporting to message handler"); Debugger.Log(int.MaxValue, "MonoMod.DebugLog", ex.ToString()); } } } private sealed class LevelSubscriptions { public LogLevelFilter ActiveLevels; public LogLevelFilter DetailLevels; public readonly OnLogMessage?[] SimpleRegs; public readonly OnLogMessageDetailed?[] DetailedRegs; private const LogLevelFilter ValidFilter = LogLevelFilter.Spam | LogLevelFilter.Trace | LogLevelFilter.Info | LogLevelFilter.Warning | LogLevelFilter.Error | LogLevelFilter.Assert; public static readonly LevelSubscriptions None = new LevelSubscriptions(); private LevelSubscriptions(LogLevelFilter active, LogLevelFilter detail, OnLogMessage?[] simple, OnLogMessageDetailed?[] detailed) { ActiveLevels = active | detail; DetailLevels = detail; SimpleRegs = simple; DetailedRegs = detailed; } private LevelSubscriptions() { ActiveLevels = LogLevelFilter.None; DetailLevels = LogLevelFilter.None; SimpleRegs = new OnLogMessage[6]; DetailedRegs = new OnLogMessageDetailed[SimpleRegs.Length]; } private LevelSubscriptions Clone(bool changingDetail) { OnLogMessage[] array = SimpleRegs; OnLogMessageDetailed[] array2 = DetailedRegs; if (!changingDetail) { array = new OnLogMessage[SimpleRegs.Length]; Array.Copy(SimpleRegs, array, array.Length); } else { array2 = new OnLogMessageDetailed[DetailedRegs.Length]; Array.Copy(DetailedRegs, array2, array2.Length); } return new LevelSubscriptions(ActiveLevels, DetailLevels, array, array2); } private void FixFilters() { ActiveLevels &= LogLevelFilter.Spam | LogLevelFilter.Trace | LogLevelFilter.Info | LogLevelFilter.Warning | LogLevelFilter.Error | LogLevelFilter.Assert; DetailLevels &= LogLevelFilter.Spam | LogLevelFilter.Trace | LogLevelFilter.Info | LogLevelFilter.Warning | LogLevelFilter.Error | LogLevelFilter.Assert; } public LevelSubscriptions AddSimple(LogLevelFilter filter, OnLogMessage del) { LevelSubscriptions levelSubscriptions = Clone(changingDetail: false); levelSubscriptions.ActiveLevels |= filter; for (int i = 0; i < levelSubscriptions.SimpleRegs.Length; i++) { if (((uint)filter & (uint)(1 << i)) != 0) { Helpers.EventAdd(ref levelSubscriptions.SimpleRegs[i], del); } } levelSubscriptions.FixFilters(); return levelSubscriptions; } public LevelSubscriptions RemoveSimple(LogLevelFilter filter, OnLogMessage del) { LevelSubscriptions levelSubscriptions = Clone(changingDetail: false); for (int i = 0; i < levelSubscriptions.SimpleRegs.Length; i++) { if (((uint)filter & (uint)(1 << i)) != 0 && Helpers.EventRemove(ref levelSubscriptions.SimpleRegs[i], del) == null) { levelSubscriptions.ActiveLevels &= (LogLevelFilter)(~(1 << i)); } } levelSubscriptions.ActiveLevels |= levelSubscriptions.DetailLevels; levelSubscriptions.FixFilters(); return levelSubscriptions; } public LevelSubscriptions AddDetailed(LogLevelFilter filter, OnLogMessageDetailed del) { LevelSubscriptions levelSubscriptions = Clone(changingDetail: true); levelSubscriptions.DetailLevels |= filter; for (int i = 0; i < levelSubscriptions.DetailedRegs.Length; i++) { if (((uint)filter & (uint)(1 << i)) != 0) { Helpers.EventAdd(ref levelSubscriptions.DetailedRegs[i], del); } } levelSubscriptions.ActiveLevels |= levelSubscriptions.DetailLevels; levelSubscriptions.FixFilters(); return levelSubscriptions; } public LevelSubscriptions RemoveDetailed(LogLevelFilter filter, OnLogMessageDetailed del) { LevelSubscriptions levelSubscriptions = Clone(changingDetail: true); for (int i = 0; i < levelSubscriptions.DetailedRegs.Length; i++) { if (((uint)filter & (uint)(1 << i)) != 0 && Helpers.EventRemove(ref levelSubscriptions.DetailedRegs[i], del) == null) { levelSubscriptions.DetailLevels &= (LogLevelFilter)(~(1 << i)); } } levelSubscriptions.ActiveLevels |= levelSubscriptions.DetailLevels; levelSubscriptions.FixFilters(); return levelSubscriptions; } } private sealed class LogSubscriptionSimple : IDisposable { private readonly DebugLog log; private readonly OnLogMessage del; private readonly LogLevelFilter filter; public LogSubscriptionSimple(DebugLog log, OnLogMessage del, LogLevelFilter filter) { this.log = log; this.del = del; this.filter = filter; } public void Dispose() { LevelSubscriptions subscriptions; LevelSubscriptions value; do { subscriptions = log.subscriptions; value = subscriptions.RemoveSimple(filter, del); } while (Interlocked.CompareExchange(ref log.subscriptions, value, subscriptions) != subscriptions); } } private sealed class LogSubscriptionDetailed : IDisposable { private readonly DebugLog log; private readonly OnLogMessageDetailed del; private readonly LogLevelFilter filter; public LogSubscriptionDetailed(DebugLog log, OnLogMessageDetailed del, LogLevelFilter filter) { this.log = log; this.del = del; this.filter = filter; } public void Dispose() { LevelSubscriptions subscriptions; LevelSubscriptions value; do { subscriptions = log.subscriptions; value = subscriptions.RemoveDetailed(filter, del); } while (Interlocked.CompareExchange(ref log.subscriptions, value, subscriptions) != subscriptions); } } internal static readonly DebugLog Instance = new DebugLog(); private static readonly ConcurrentBag> weakRefCache = new ConcurrentBag>(); private static readonly ConcurrentBag> messageObjectCache = new ConcurrentBag>(); private static readonly char[] listEnvSeparator = new char[3] { ' ', ';', ',' }; private readonly bool recordHoles; private readonly int replayQueueLength; private readonly ConcurrentQueue? replayQueue; private LogLevelFilter globalFilter = LogLevelFilter.DefaultFilter; private static byte[]? memlog; private static int memlogPos; private LevelSubscriptions subscriptions = LevelSubscriptions.None; private static readonly ConcurrentDictionary simpleRegDict = new ConcurrentDictionary(); public static bool IsFinalizing { get { if (!Environment.HasShutdownStarted) { return AppDomain.CurrentDomain.IsFinalizingForUnload(); } return true; } } public static bool IsWritingLog => Instance.ShouldLog; internal bool AlwaysLog { get { if (replayQueue == null) { return Debugger.IsAttached; } return true; } } internal bool ShouldLog { get { if (subscriptions.ActiveLevels == LogLevelFilter.None) { return AlwaysLog; } return true; } } internal bool RecordHoles { get { if (!recordHoles) { return subscriptions.DetailLevels != LogLevelFilter.None; } return true; } } public static event OnLogMessage OnLog { add { IDisposable res = Subscribe(Instance.globalFilter, value); simpleRegDict.AddOrUpdate(value, res, delegate(OnLogMessage _, IDisposable d) { d.Dispose(); return res; }); } remove { if (simpleRegDict.TryRemove(value, out IDisposable value2)) { value2.Dispose(); } } } private LogMessage MakeMessage(string source, DateTime time, LogLevel level, string formatted, ReadOnlyMemory holes) { try { if (replayQueue == null && !IsFinalizing) { WeakReference result; while (messageObjectCache.TryTake(out result)) { if (result.TryGetTarget(out var target)) { target.Init(source, time, level, formatted, holes); weakRefCache.Add(result); return target; } weakRefCache.Add(result); } } } catch { } return new LogMessage(source, time, level, formatted, holes); } private void ReturnMessage(LogMessage message) { message.Clear(); try { if (replayQueue == null && !IsFinalizing) { if (weakRefCache.TryTake(out WeakReference result)) { result.SetTarget(message); messageObjectCache.Add(result); } else { messageObjectCache.Add(new WeakReference(message)); } } } catch { } } private void PostMessage(LogMessage message) { if (Debugger.IsAttached) { try { LogLevel level = message.Level; string source = message.Source; FormatInterpolatedStringHandler handler = new FormatInterpolatedStringHandler(6, 3); handler.AppendLiteral("["); handler.AppendFormatted(message.Source); handler.AppendLiteral("] "); handler.AppendFormatted(message.Level.FastToString()); handler.AppendLiteral(": "); handler.AppendFormatted(message.FormattedMessage); handler.AppendLiteral("\n"); Debugger.Log((int)level, source, DebugFormatter.Format(ref handler)); } catch { } } try { LevelSubscriptions levelSubscriptions = subscriptions; int level2 = (int)message.Level; OnLogMessage onLogMessage = levelSubscriptions.SimpleRegs[level2]; if (onLogMessage != null) { message.ReportTo(onLogMessage); } OnLogMessageDetailed onLogMessageDetailed = levelSubscriptions.DetailedRegs[level2]; if (onLogMessageDetailed != null) { message.ReportTo(onLogMessageDetailed); } if (IsFinalizing) { return; } ConcurrentQueue concurrentQueue = replayQueue; if (concurrentQueue != null) { concurrentQueue.Enqueue(message); LogMessage result; while (concurrentQueue.Count > replayQueueLength && concurrentQueue.TryDequeue(out result)) { } } else { ReturnMessage(message); } } catch { } } internal bool ShouldLogLevel(LogLevel level) { if (((uint)(1 << (int)level) & (uint)subscriptions.ActiveLevels) == 0) { if (((uint)(1 << (int)level) & (uint)globalFilter) != 0) { return AlwaysLog; } return false; } return true; } internal bool ShouldLevelRecordHoles(LogLevel level) { if (!recordHoles) { return ((uint)(1 << (int)level) & (uint)subscriptions.DetailLevels) != 0; } return true; } public void Write(string source, DateTime time, LogLevel level, string message) { if (ShouldLogLevel(level)) { PostMessage(MakeMessage(source, time, level, message, default(ReadOnlyMemory))); } } public void Write(string source, DateTime time, LogLevel level, [InterpolatedStringHandlerArgument("level")] ref DebugLogInterpolatedStringHandler message) { if (message.enabled && ShouldLogLevel(level)) { ReadOnlyMemory holes; string formatted = message.ToStringAndClear(out holes); PostMessage(MakeMessage(source, time, level, formatted, holes)); } } internal void LogCore(string source, LogLevel level, string message) { if (ShouldLogLevel(level)) { Write(source, DateTime.UtcNow, level, message); } } internal void LogCore(string source, LogLevel level, [InterpolatedStringHandlerArgument("level")] ref DebugLogInterpolatedStringHandler message) { if (message.enabled && ShouldLogLevel(level)) { Write(source, DateTime.UtcNow, level, ref message); } } public static void Log(string source, LogLevel level, string message) { DebugLog instance = Instance; if (instance.ShouldLogLevel(level)) { instance.Write(source, DateTime.UtcNow, level, message); } } public static void Log(string source, LogLevel level, [InterpolatedStringHandlerArgument("level")] ref DebugLogInterpolatedStringHandler message) { DebugLog instance = Instance; if (message.enabled && instance.ShouldLogLevel(level)) { instance.Write(source, DateTime.UtcNow, level, ref message); } } private static string[]? GetListEnvVar(string text) { string text2 = text.Trim(); if (string.IsNullOrEmpty(text2)) { return null; } string[] array = text2.Split(listEnvSeparator, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < array.Length; i++) { array[i] = array[i].Trim(); } return array; } private DebugLog() { recordHoles = Switches.TryGetSwitchEnabled("LogRecordHoles", out var isEnabled) && isEnabled; replayQueueLength = 0; if (Switches.TryGetSwitchValue("LogReplayQueueLength", out object value)) { replayQueueLength = (value as int?).GetValueOrDefault(); } if (Switches.TryGetSwitchEnabled("LogSpam", out isEnabled) && isEnabled) { globalFilter |= LogLevelFilter.Spam; } if (replayQueueLength > 0) { replayQueue = new ConcurrentQueue(); } string text = (Switches.TryGetSwitchValue("LogToFile", out value) ? (value as string) : null); string[] sourceFilter = null; if (Switches.TryGetSwitchValue("LogToFileFilter", out value)) { sourceFilter = ((value is string[] array) ? array : ((!(value is string text2)) ? null : GetListEnvVar(text2))); } if (text != null) { TryInitializeLogToFile(text, sourceFilter, globalFilter); } if (Switches.TryGetSwitchEnabled("LogInMemory", out isEnabled) && isEnabled) { TryInitializeMemoryLog(globalFilter); } } private void TryInitializeLogToFile(string file, string[]? sourceFilter, LogLevelFilter filter) { try { StringComparer comparer = StringComparerEx.FromComparison(StringComparison.OrdinalIgnoreCase); if (sourceFilter != null) { Array.Sort(sourceFilter, (IComparer?)comparer); } object sync = new object(); TextWriter writer; if (file == "-") { writer = Console.Out; } else { FileStream stream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Write); writer = new StreamWriter(stream, Encoding.UTF8) { AutoFlush = true }; } SubscribeCore(filter, delegate(string source, DateTime time, LogLevel level2, string msg) { if (sourceFilter != null && sourceFilter.AsSpan().BinarySearch(source, comparer) < 0) { return; } DateTime value2 = time.ToLocalTime(); string value3 = $"[{source}]({value2}) {level2.FastToString()}: {msg}"; lock (sync) { writer.WriteLine(value3); } }); } catch (Exception value) { LogLevel logLevel = LogLevel.Error; LogLevel level = logLevel; bool isEnabled; DebugLogInterpolatedStringHandler message = new DebugLogInterpolatedStringHandler(61, 1, logLevel, out isEnabled); if (isEnabled) { message.AppendLiteral("Exception while trying to initialize writing logs to a file: "); message.AppendFormatted(value); } Instance.LogCore("DebugLog", level, ref message); } } private void TryInitializeMemoryLog(LogLevelFilter filter) { try { memlogPos = 0; memlog = new byte[4096]; object sync = new object(); _ = Encoding.UTF8; SubscribeCore(filter, delegate(string source, DateTime time, LogLevel logLevel2, string msg) { byte value2 = (byte)logLevel2; long ticks = time.Ticks; if (source.Length > 255) { source = source.Substring(0, 255); } byte b = (byte)source.Length; int length = msg.Length; int num = 14 + b * 2 + length * 2; lock (sync) { if (memlog.Length - memlogPos < num) { int num2 = memlog.Length * 4; while (num2 - memlogPos < num) { num2 *= 4; } Array.Resize(ref memlog, num2); } ref byte reference = ref MemoryMarshal.GetReference(memlog.AsSpan().Slice(memlogPos)); int num3 = 0; Unsafe.WriteUnaligned(ref Unsafe.Add(ref reference, num3), value2); num3++; Unsafe.WriteUnaligned(ref Unsafe.Add(ref reference, num3), ticks); num3 += 8; Unsafe.WriteUnaligned(ref Unsafe.Add(ref reference, num3), b); num3++; Unsafe.CopyBlock(ref Unsafe.Add(ref reference, num3), in Unsafe.As(ref MemoryMarshal.GetReference(source.AsSpan())), (uint)(b * 2)); num3 += b * 2; Unsafe.WriteUnaligned(ref Unsafe.Add(ref reference, num3), length); num3 += 4; Unsafe.CopyBlock(ref Unsafe.Add(ref reference, num3), in Unsafe.As(ref MemoryMarshal.GetReference(msg.AsSpan())), (uint)(length * 2)); num3 += length * 2; memlogPos += num3; } }); } catch (Exception value) { LogLevel logLevel = LogLevel.Error; LogLevel level = logLevel; bool isEnabled; DebugLogInterpolatedStringHandler message = new DebugLogInterpolatedStringHandler(45, 1, logLevel, out isEnabled); if (isEnabled) { message.AppendLiteral("Exception while initializing the memory log: "); message.AppendFormatted(value); } Instance.LogCore("DebugLog", level, ref message); } } private void MaybeReplayTo(LogLevelFilter filter, OnLogMessage del) { if (replayQueue == null || filter == LogLevelFilter.None) { return; } LogMessage[] array = replayQueue.ToArray(); foreach (LogMessage logMessage in array) { if (((uint)(1 << (int)logMessage.Level) & (uint)filter) != 0) { logMessage.ReportTo(del); } } } private void MaybeReplayTo(LogLevelFilter filter, OnLogMessageDetailed del) { if (replayQueue == null || filter == LogLevelFilter.None) { return; } LogMessage[] array = replayQueue.ToArray(); foreach (LogMessage logMessage in array) { if (((uint)(1 << (int)logMessage.Level) & (uint)filter) != 0) { logMessage.ReportTo(del); } } } public static IDisposable Subscribe(LogLevelFilter filter, OnLogMessage value) { return Instance.SubscribeCore(filter, value); } private IDisposable SubscribeCore(LogLevelFilter filter, OnLogMessage value) { LevelSubscriptions levelSubscriptions; LevelSubscriptions value2; do { levelSubscriptions = subscriptions; value2 = levelSubscriptions.AddSimple(filter, value); } while (Interlocked.CompareExchange(ref subscriptions, value2, levelSubscriptions) != levelSubscriptions); MaybeReplayTo(filter, value); return new LogSubscriptionSimple(this, value, filter); } public static IDisposable Subscribe(LogLevelFilter filter, OnLogMessageDetailed value) { return Instance.SubscribeCore(filter, value); } private IDisposable SubscribeCore(LogLevelFilter filter, OnLogMessageDetailed value) { LevelSubscriptions levelSubscriptions; LevelSubscriptions value2; do { levelSubscriptions = subscriptions; value2 = levelSubscriptions.AddDetailed(filter, value); } while (Interlocked.CompareExchange(ref subscriptions, value2, levelSubscriptions) != levelSubscriptions); MaybeReplayTo(filter, value); return new LogSubscriptionDetailed(this, value, filter); } } [InterpolatedStringHandler] public ref struct DebugLogInterpolatedStringHandler { private const int GuessedLengthPerHole = 11; private const int MinimumArrayPoolLength = 256; private char[]? _arrayToReturnToPool; private Span _chars; private int _pos; private int holeBegin; private int holePos; private Memory holes; internal readonly bool enabled; internal ReadOnlySpan Text => _chars.Slice(0, _pos); public DebugLogInterpolatedStringHandler(int literalLength, int formattedCount, bool enabled, bool recordHoles, out bool isEnabled) { _pos = (holeBegin = (holePos = 0)); this.enabled = (isEnabled = enabled); if (enabled) { _chars = (_arrayToReturnToPool = ArrayPool.Shared.Rent(GetDefaultLength(literalLength, formattedCount))); if (recordHoles) { holes = new MessageHole[formattedCount]; } else { holes = default(Memory); } } else { _chars = (_arrayToReturnToPool = null); holes = default(Memory); } } public DebugLogInterpolatedStringHandler(int literalLength, int formattedCount, out bool isEnabled) { DebugLog instance = DebugLog.Instance; _pos = (holeBegin = (holePos = 0)); if (instance.ShouldLog) { enabled = (isEnabled = true); _chars = (_arrayToReturnToPool = ArrayPool.Shared.Rent(GetDefaultLength(literalLength, formattedCount))); if (instance.RecordHoles) { holes = new MessageHole[formattedCount]; } else { holes = default(Memory); } } else { enabled = (isEnabled = false); _chars = (_arrayToReturnToPool = null); holes = default(Memory); } } public DebugLogInterpolatedStringHandler(int literalLength, int formattedCount, LogLevel level, out bool isEnabled) { DebugLog instance = DebugLog.Instance; _pos = (holeBegin = (holePos = 0)); if (instance.ShouldLogLevel(level)) { enabled = (isEnabled = true); _chars = (_arrayToReturnToPool = ArrayPool.Shared.Rent(GetDefaultLength(literalLength, formattedCount))); if (instance.ShouldLevelRecordHoles(level)) { holes = new MessageHole[formattedCount]; } else { holes = default(Memory); } } else { enabled = (isEnabled = false); _chars = (_arrayToReturnToPool = null); holes = default(Memory); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int GetDefaultLength(int literalLength, int formattedCount) { return Math.Max(256, literalLength + formattedCount * 11); } public override string ToString() { return Text.ToString(); } public string ToStringAndClear() { string result = Text.ToString(); Clear(); return result; } internal string ToStringAndClear(out ReadOnlyMemory holes) { holes = this.holes; return ToStringAndClear(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void Clear() { char[] arrayToReturnToPool = _arrayToReturnToPool; this = default(DebugLogInterpolatedStringHandler); if (arrayToReturnToPool != null) { ArrayPool.Shared.Return(arrayToReturnToPool); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendLiteral(string value) { if (value.Length == 1) { Span chars = _chars; int pos = _pos; if ((uint)pos < (uint)chars.Length) { chars[pos] = value[0]; _pos = pos + 1; } else { GrowThenCopyString(value); } } else if (value.Length == 2) { Span chars2 = _chars; int pos2 = _pos; if ((uint)pos2 < chars2.Length - 1) { value.AsSpan().CopyTo(chars2.Slice(pos2)); _pos = pos2 + 2; } else { GrowThenCopyString(value); } } else { AppendStringDirect(value); } } private void AppendStringDirect(string value) { if (value.AsSpan().TryCopyTo(_chars.Slice(_pos))) { _pos += value.Length; } else { GrowThenCopyString(value); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void BeginHole() { holeBegin = _pos; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void EndHole(object? obj, bool reprd) { EndHole(in obj, reprd); } [MethodImpl(MethodImplOptions.NoInlining)] private void EndHole(in T obj, bool reprd) { if (!holes.IsEmpty) { holes.Span[holePos++] = (reprd ? new MessageHole(holeBegin, _pos, obj) : new MessageHole(holeBegin, _pos)); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(string? value) { BeginHole(); if (value != null && value.AsSpan().TryCopyTo(_chars.Slice(_pos))) { _pos += value.Length; } else { AppendFormattedSlow(value); } EndHole(in value, reprd: true); } [MethodImpl(MethodImplOptions.NoInlining)] private void AppendFormattedSlow(string? value) { if (value != null) { EnsureCapacityForAdditionalChars(value.Length); value.AsSpan().CopyTo(_chars.Slice(_pos)); _pos += value.Length; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(string? value, int alignment = 0, string? format = null) { this.AppendFormatted(value, alignment, format); } public void AppendFormatted(ReadOnlySpan value) { BeginHole(); if (value.TryCopyTo(_chars.Slice(_pos))) { _pos += value.Length; } else { GrowThenCopySpan(value); } EndHole(null, reprd: false); } public void AppendFormatted(ReadOnlySpan value, int alignment = 0, string? format = null) { bool flag = false; if (alignment < 0) { flag = true; alignment = -alignment; } int num = alignment - value.Length; if (num <= 0) { AppendFormatted(value); return; } BeginHole(); EnsureCapacityForAdditionalChars(value.Length + num); if (flag) { value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; _chars.Slice(_pos, num).Fill(' '); _pos += num; } else { _chars.Slice(_pos, num).Fill(' '); _pos += num; value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; } EndHole(null, reprd: false); } public void AppendFormatted(T value) { if (typeof(T) == typeof(nint)) { AppendFormatted(Unsafe.As(ref value)); return; } if (typeof(T) == typeof(nuint)) { AppendFormatted(Unsafe.As(ref value)); return; } BeginHole(); if (DebugFormatter.CanDebugFormat(in value, out object extraData)) { int wrote; while (!DebugFormatter.TryFormatInto(in value, extraData, _chars.Slice(_pos), out wrote)) { Grow(); } _pos += wrote; return; } string text = ((!(value is IFormattable)) ? value?.ToString() : ((IFormattable)(object)value).ToString(null, null)); if (text != null) { AppendStringDirect(text); } EndHole(in value, reprd: true); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AppendFormatted(nint value) { if (IntPtr.Size == 4) { AppendFormatted((int)value); } else { AppendFormatted((long)value); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AppendFormatted(nint value, string? format) { if (IntPtr.Size == 4) { AppendFormatted((int)value, format); } else { AppendFormatted((long)value, format); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AppendFormatted(nuint value) { if (UIntPtr.Size == 4) { AppendFormatted((uint)value); } else { AppendFormatted((ulong)value); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AppendFormatted(nuint value, string? format) { if (UIntPtr.Size == 4) { AppendFormatted((uint)value, format); } else { AppendFormatted((ulong)value, format); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, int alignment) { int pos = _pos; AppendFormatted(value); if (alignment != 0) { AppendOrInsertAlignmentIfNeeded(pos, alignment); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, string? format) { if (typeof(T) == typeof(nint)) { AppendFormatted(Unsafe.As(ref value), format); return; } if (typeof(T) == typeof(nuint)) { AppendFormatted(Unsafe.As(ref value), format); return; } BeginHole(); if (DebugFormatter.CanDebugFormat(in value, out object extraData)) { int wrote; while (!DebugFormatter.TryFormatInto(in value, extraData, _chars.Slice(_pos), out wrote)) { Grow(); } _pos += wrote; return; } string text = ((!(value is IFormattable)) ? value?.ToString() : ((IFormattable)(object)value).ToString(format, null)); if (text != null) { AppendStringDirect(text); } EndHole(in value, reprd: true); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, int alignment, string? format) { int pos = _pos; AppendFormatted(value, format); if (alignment != 0) { AppendOrInsertAlignmentIfNeeded(pos, alignment); } } private void AppendOrInsertAlignmentIfNeeded(int startingPos, int alignment) { int num = _pos - startingPos; bool flag = false; if (alignment < 0) { flag = true; alignment = -alignment; } int num2 = alignment - num; if (num2 > 0) { EnsureCapacityForAdditionalChars(num2); if (flag) { _chars.Slice(_pos, num2).Fill(' '); } else { _chars.Slice(startingPos, num).CopyTo(_chars.Slice(startingPos + num2)); _chars.Slice(startingPos, num2).Fill(' '); } _pos += num2; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void EnsureCapacityForAdditionalChars(int additionalChars) { if (_chars.Length - _pos < additionalChars) { Grow(additionalChars); } } [MethodImpl(MethodImplOptions.NoInlining)] private void GrowThenCopyString(string value) { Grow(value.Length); value.AsSpan().CopyTo(_chars.Slice(_pos)); _pos += value.Length; } [MethodImpl(MethodImplOptions.NoInlining)] private void GrowThenCopySpan(ReadOnlySpan value) { Grow(value.Length); value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; } [MethodImpl(MethodImplOptions.NoInlining)] private void Grow(int additionalChars) { GrowCore((uint)(_pos + additionalChars)); } [MethodImpl(MethodImplOptions.NoInlining)] private void Grow() { GrowCore((uint)(_chars.Length + 1)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void GrowCore(uint requiredMinCapacity) { int minimumLength = (int)MathEx.Clamp(Math.Max(requiredMinCapacity, Math.Min((uint)(_chars.Length * 2), uint.MaxValue)), 256u, 2147483647u); char[] array = ArrayPool.Shared.Rent(minimumLength); _chars.Slice(0, _pos).CopyTo(array); char[] arrayToReturnToPool = _arrayToReturnToPool; _chars = (_arrayToReturnToPool = array); if (arrayToReturnToPool != null) { ArrayPool.Shared.Return(arrayToReturnToPool); } } } [InterpolatedStringHandler] public ref struct FormatIntoInterpolatedStringHandler { private readonly Span _chars; internal int pos; internal bool incomplete; public FormatIntoInterpolatedStringHandler(int literalLen, int numHoles, Span into, out bool enabled) { _chars = into; pos = 0; if (into.Length < literalLen) { incomplete = true; enabled = false; } else { incomplete = false; enabled = true; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool AppendLiteral(string value) { if (value.Length == 1) { Span chars = _chars; int num = pos; if ((uint)num < (uint)chars.Length) { chars[num] = value[0]; pos = num + 1; return true; } incomplete = true; return false; } if (value.Length == 2) { Span chars2 = _chars; int num2 = pos; if ((uint)num2 < chars2.Length - 1) { value.AsSpan().CopyTo(chars2.Slice(num2)); pos = num2 + 2; return true; } incomplete = true; return false; } return AppendStringDirect(value); } private bool AppendStringDirect(string value) { if (value.AsSpan().TryCopyTo(_chars.Slice(pos))) { pos += value.Length; return true; } incomplete = true; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool AppendFormatted(string? value) { if (value == null) { return true; } if (value.AsSpan().TryCopyTo(_chars.Slice(pos))) { pos += value.Length; return true; } incomplete = true; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool AppendFormatted(string? value, int alignment = 0, string? format = null) { return this.AppendFormatted(value, alignment, format); } public bool AppendFormatted(ReadOnlySpan value) { if (value.TryCopyTo(_chars.Slice(pos))) { pos += value.Length; return true; } incomplete = true; return false; } public bool AppendFormatted(ReadOnlySpan value, int alignment = 0, string? format = null) { bool flag = false; if (alignment < 0) { flag = true; alignment = -alignment; } int num = alignment - value.Length; if (num <= 0) { return AppendFormatted(value); } if (_chars.Slice(pos).Length < value.Length + num) { incomplete = true; return false; } if (flag) { value.CopyTo(_chars.Slice(pos)); pos += value.Length; _chars.Slice(pos, num).Fill(' '); pos += num; } else { _chars.Slice(pos, num).Fill(' '); pos += num; value.CopyTo(_chars.Slice(pos)); pos += value.Length; } return true; } public bool AppendFormatted(T value) { if (typeof(T) == typeof(nint)) { return AppendFormatted(Unsafe.As(ref value)); } if (typeof(T) == typeof(nuint)) { return AppendFormatted(Unsafe.As(ref value)); } if (DebugFormatter.CanDebugFormat(in value, out object extraData)) { if (!DebugFormatter.TryFormatInto(in value, extraData, _chars.Slice(pos), out var wrote)) { incomplete = true; return false; } pos += wrote; return true; } string text = ((!(value is IFormattable)) ? value?.ToString() : ((IFormattable)(object)value).ToString(null, null)); if (text != null) { return AppendStringDirect(text); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool AppendFormatted(nint value) { if (IntPtr.Size == 4) { return AppendFormatted((int)value); } return AppendFormatted((long)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool AppendFormatted(nint value, string? format) { if (IntPtr.Size == 4) { return AppendFormatted((int)value, format); } return AppendFormatted((long)value, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool AppendFormatted(nuint value) { if (UIntPtr.Size == 4) { return AppendFormatted((uint)value); } return AppendFormatted((ulong)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool AppendFormatted(nuint value, string? format) { if (UIntPtr.Size == 4) { return AppendFormatted((uint)value, format); } return AppendFormatted((ulong)value, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool AppendFormatted(T value, int alignment) { int startingPos = pos; if (!AppendFormatted(value)) { return false; } if (alignment != 0) { return AppendOrInsertAlignmentIfNeeded(startingPos, alignment); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool AppendFormatted(T value, string? format) { if (typeof(T) == typeof(nint)) { return AppendFormatted(Unsafe.As(ref value), format); } if (typeof(T) == typeof(nuint)) { return AppendFormatted(Unsafe.As(ref value), format); } if (DebugFormatter.CanDebugFormat(in value, out object extraData)) { if (!DebugFormatter.TryFormatInto(in value, extraData, _chars.Slice(pos), out var wrote)) { incomplete = true; return false; } pos += wrote; return true; } string text = ((!(value is IFormattable)) ? value?.ToString() : ((IFormattable)(object)value).ToString(format, null)); if (text != null) { return AppendStringDirect(text); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool AppendFormatted(T value, int alignment, string? format) { int startingPos = pos; if (!AppendFormatted(value, format)) { return false; } if (alignment != 0) { return AppendOrInsertAlignmentIfNeeded(startingPos, alignment); } return true; } private bool AppendOrInsertAlignmentIfNeeded(int startingPos, int alignment) { int num = pos - startingPos; bool flag = false; if (alignment < 0) { flag = true; alignment = -alignment; } int num2 = alignment - num; if (num2 > 0) { if (_chars.Slice(pos).Length < num2) { incomplete = true; return false; } if (flag) { _chars.Slice(pos, num2).Fill(' '); } else { _chars.Slice(startingPos, num).CopyTo(_chars.Slice(startingPos + num2)); _chars.Slice(startingPos, num2).Fill(' '); } pos += num2; } return true; } } public interface IDebugFormattable { bool TryFormatInto(Span span, out int wrote); } public enum LogLevel { Spam, Trace, Info, Warning, Error, Assert } [Flags] public enum LogLevelFilter { None = 0, Spam = 1, Trace = 2, Info = 4, Warning = 8, Error = 0x10, Assert = 0x20, DefaultFilter = -2 } public static class LogLevelExtensions { public const LogLevel MaxLevel = LogLevel.Assert; public static string FastToString(this LogLevel level, IFormatProvider? provider = null) { switch (level) { case LogLevel.Spam: return "Spam"; case LogLevel.Trace: return "Trace"; case LogLevel.Info: return "Info"; case LogLevel.Warning: return "Warning"; case LogLevel.Error: return "Error"; case LogLevel.Assert: return "Assert"; default: { int num = (int)level; return num.ToString(provider); } } } } } namespace MonoMod.Cil { [AttributeUsage(AttributeTargets.Method)] internal sealed class GetFastDelegateInvokersArrayAttribute : Attribute { public int MaxParams { get; } public GetFastDelegateInvokersArrayAttribute(int maxParams) { MaxParams = maxParams; } } public static class FastDelegateInvokers { private delegate void VoidVal1(T0 _0); private delegate TResult TypeVal1(T0 _0); private delegate void VoidRef1(ref T0 _0); private delegate TResult TypeRef1(ref T0 _0); private delegate void VoidVal2(T0 _0, T1 _1); private delegate TResult TypeVal2(T0 _0, T1 _1); private delegate void VoidRef2(ref T0 _0, T1 _1); private delegate TResult TypeRef2(ref T0 _0, T1 _1); private delegate void VoidVal3(T0 _0, T1 _1, T2 _2); private delegate TResult TypeVal3(T0 _0, T1 _1, T2 _2); private delegate void VoidRef3(ref T0 _0, T1 _1, T2 _2); private delegate TResult TypeRef3(ref T0 _0, T1 _1, T2 _2); private delegate void VoidVal4(T0 _0, T1 _1, T2 _2, T3 _3); private delegate TResult TypeVal4(T0 _0, T1 _1, T2 _2, T3 _3); private delegate void VoidRef4(ref T0 _0, T1 _1, T2 _2, T3 _3); private delegate TResult TypeRef4(ref T0 _0, T1 _1, T2 _2, T3 _3); private delegate void VoidVal5(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4); private delegate TResult TypeVal5(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4); private delegate void VoidRef5(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4); private delegate TResult TypeRef5(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4); private delegate void VoidVal6(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5); private delegate TResult TypeVal6(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5); private delegate void VoidRef6(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5); private delegate TResult TypeRef6(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5); private delegate void VoidVal7(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6); private delegate TResult TypeVal7(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6); private delegate void VoidRef7(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6); private delegate TResult TypeRef7(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6); private delegate void VoidVal8(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7); private delegate TResult TypeVal8(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7); private delegate void VoidRef8(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7); private delegate TResult TypeRef8(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7); private delegate void VoidVal9(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8); private delegate TResult TypeVal9(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8); private delegate void VoidRef9(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8); private delegate TResult TypeRef9(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8); private delegate void VoidVal10(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9); private delegate TResult TypeVal10(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9); private delegate void VoidRef10(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9); private delegate TResult TypeRef10(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9); private delegate void VoidVal11(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10); private delegate TResult TypeVal11(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10); private delegate void VoidRef11(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10); private delegate TResult TypeRef11(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10); private delegate void VoidVal12(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11); private delegate TResult TypeVal12(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11); private delegate void VoidRef12(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11); private delegate TResult TypeRef12(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11); private delegate void VoidVal13(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12); private delegate TResult TypeVal13(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12); private delegate void VoidRef13(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12); private delegate TResult TypeRef13(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12); private delegate void VoidVal14(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13); private delegate TResult TypeVal14(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13); private delegate void VoidRef14(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13); private delegate TResult TypeRef14(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13); private delegate void VoidVal15(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, T14 _14); private delegate TResult TypeVal15(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, T14 _14); private delegate void VoidRef15(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, T14 _14); private delegate TResult TypeRef15(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, T14 _14); private delegate void VoidVal16(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, T14 _14, T15 _15); private delegate TResult TypeVal16(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, T14 _14, T15 _15); private delegate void VoidRef16(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, T14 _14, T15 _15); private delegate TResult TypeRef16(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, T14 _14, T15 _15); private static readonly (MethodInfo, Type)[] invokers = GetInvokers(); private const int MaxFastInvokerParams = 16; private static readonly ConditionalWeakTable> invokerCache = new ConditionalWeakTable>(); [GetFastDelegateInvokersArray(16)] private static (MethodInfo, Type)[] GetInvokers() { return new(MethodInfo, Type)[64] { (typeof(FastDelegateInvokers).GetMethod("InvokeVoidVal1", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidVal1<>)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeVal1", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeVal1<, >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidRef1", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidRef1<>)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeRef1", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeRef1<, >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidVal2", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidVal2<, >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeVal2", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeVal2<, , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidRef2", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidRef2<, >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeRef2", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeRef2<, , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidVal3", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidVal3<, , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeVal3", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeVal3<, , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidRef3", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidRef3<, , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeRef3", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeRef3<, , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidVal4", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidVal4<, , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeVal4", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeVal4<, , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidRef4", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidRef4<, , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeRef4", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeRef4<, , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidVal5", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidVal5<, , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeVal5", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeVal5<, , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidRef5", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidRef5<, , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeRef5", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeRef5<, , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidVal6", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidVal6<, , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeVal6", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeVal6<, , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidRef6", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidRef6<, , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeRef6", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeRef6<, , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidVal7", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidVal7<, , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeVal7", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeVal7<, , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidRef7", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidRef7<, , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeRef7", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeRef7<, , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidVal8", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidVal8<, , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeVal8", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeVal8<, , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidRef8", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidRef8<, , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeRef8", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeRef8<, , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidVal9", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidVal9<, , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeVal9", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeVal9<, , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidRef9", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidRef9<, , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeRef9", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeRef9<, , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidVal10", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidVal10<, , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeVal10", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeVal10<, , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidRef10", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidRef10<, , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeRef10", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeRef10<, , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidVal11", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidVal11<, , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeVal11", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeVal11<, , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidRef11", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidRef11<, , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeRef11", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeRef11<, , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidVal12", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidVal12<, , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeVal12", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeVal12<, , , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidRef12", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidRef12<, , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeRef12", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeRef12<, , , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidVal13", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidVal13<, , , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeVal13", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeVal13<, , , , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidRef13", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidRef13<, , , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeRef13", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeRef13<, , , , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidVal14", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidVal14<, , , , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeVal14", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeVal14<, , , , , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidRef14", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidRef14<, , , , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeRef14", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeRef14<, , , , , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidVal15", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidVal15<, , , , , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeVal15", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeVal15<, , , , , , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidRef15", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidRef15<, , , , , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeRef15", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeRef15<, , , , , , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidVal16", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidVal16<, , , , , , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeVal16", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeVal16<, , , , , , , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeVoidRef16", BindingFlags.Static | BindingFlags.NonPublic), typeof(VoidRef16<, , , , , , , , , , , , , , , >)), (typeof(FastDelegateInvokers).GetMethod("InvokeTypeRef16", BindingFlags.Static | BindingFlags.NonPublic), typeof(TypeRef16<, , , , , , , , , , , , , , , , >)) }; } private static (MethodInfo Invoker, Type Delegate)? TryGetInvokerForSig(MethodSignature sig) { if (sig.ParameterCount == 0) { return null; } if (sig.ParameterCount > 16) { return null; } if (sig.ReturnType.IsByRef || TypeExtensions.IsByRefLike(sig.ReturnType)) { return null; } if (TypeExtensions.IsByRefLike(sig.FirstParameter)) { return null; } if (sig.Parameters.Skip(1).Any((Type t) => t.IsByRef || TypeExtensions.IsByRefLike(t))) { return null; } int num = 0; num |= ((sig.ReturnType != typeof(void)) ? 1 : 0); num |= (sig.FirstParameter.IsByRef ? 2 : 0); num |= sig.ParameterCount - 1 << 2; (MethodInfo, Type) tuple = invokers[num]; MethodInfo item = tuple.Item1; Type item2 = tuple.Item2; Type[] array = new Type[sig.ParameterCount + (num & 1)]; int num2 = 0; if ((num & 1) != 0) { array[num2++] = sig.ReturnType; } foreach (Type parameter in sig.Parameters) { Type type = parameter; if (type.IsByRef) { type = type.GetElementType(); } array[num2++] = type; } Helpers.Assert(num2 == array.Length, null, "i == typeParams.Length"); return (item.MakeGenericMethod(array), item2.MakeGenericType(array)); } public static (MethodInfo Invoker, Type Delegate)? GetDelegateInvoker(Type delegateType) { Helpers.ThrowIfArgumentNull(delegateType, "delegateType"); if (!typeof(Delegate).IsAssignableFrom(delegateType)) { throw new ArgumentException("Argument not a delegate type", "delegateType"); } Tuple value = invokerCache.GetValue(delegateType, delegate(Type type) { //IL_00e0: 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_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) MethodInfo method = type.GetMethod("Invoke"); MethodSignature methodSignature = MethodSignature.ForMethod(method, ignoreThis: true); if (methodSignature.ParameterCount == 0) { return new Tuple(null, type); } (MethodInfo, Type)? tuple = TryGetInvokerForSig(methodSignature); if (tuple.HasValue) { (MethodInfo, Type) valueOrDefault = tuple.GetValueOrDefault(); return new Tuple(valueOrDefault.Item1, valueOrDefault.Item2); } Type[] array = new Type[methodSignature.ParameterCount + 1]; int num = 0; foreach (Type parameter in methodSignature.Parameters) { array[num++] = parameter; } array[methodSignature.ParameterCount] = type; using DynamicMethodDefinition dynamicMethodDefinition = new DynamicMethodDefinition("MMIL:Invoke<" + method.DeclaringType?.FullName + ">", method.ReturnType, array); ILProcessor iLProcessor = dynamicMethodDefinition.GetILProcessor(); iLProcessor.Emit(OpCodes.Ldarg, methodSignature.ParameterCount); for (num = 0; num < methodSignature.ParameterCount; num++) { iLProcessor.Emit(OpCodes.Ldarg, num); } iLProcessor.Emit(OpCodes.Callvirt, method); iLProcessor.Emit(OpCodes.Ret); return new Tuple(dynamicMethodDefinition.Generate(), type); }); if ((object)value.Item1 == null) { return null; } return (value.Item1, value.Item2); } private static void InvokeVoidVal1(T0 _0, VoidVal1 del) { Helpers.ThrowIfNull(del, "del")(_0); } private static TResult InvokeTypeVal1(T0 _0, TypeVal1 del) { return Helpers.ThrowIfNull(del, "del")(_0); } private static void InvokeVoidRef1(ref T0 _0, VoidRef1 del) { Helpers.ThrowIfNull(del, "del")(ref _0); } private static TResult InvokeTypeRef1(ref T0 _0, TypeRef1 del) { return Helpers.ThrowIfNull(del, "del")(ref _0); } private static void InvokeVoidVal2(T0 _0, T1 _1, VoidVal2 del) { Helpers.ThrowIfNull(del, "del")(_0, _1); } private static TResult InvokeTypeVal2(T0 _0, T1 _1, TypeVal2 del) { return Helpers.ThrowIfNull(del, "del")(_0, _1); } private static void InvokeVoidRef2(ref T0 _0, T1 _1, VoidRef2 del) { Helpers.ThrowIfNull(del, "del")(ref _0, _1); } private static TResult InvokeTypeRef2(ref T0 _0, T1 _1, TypeRef2 del) { return Helpers.ThrowIfNull(del, "del")(ref _0, _1); } private static void InvokeVoidVal3(T0 _0, T1 _1, T2 _2, VoidVal3 del) { Helpers.ThrowIfNull(del, "del")(_0, _1, _2); } private static TResult InvokeTypeVal3(T0 _0, T1 _1, T2 _2, TypeVal3 del) { return Helpers.ThrowIfNull(del, "del")(_0, _1, _2); } private static void InvokeVoidRef3(ref T0 _0, T1 _1, T2 _2, VoidRef3 del) { Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2); } private static TResult InvokeTypeRef3(ref T0 _0, T1 _1, T2 _2, TypeRef3 del) { return Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2); } private static void InvokeVoidVal4(T0 _0, T1 _1, T2 _2, T3 _3, VoidVal4 del) { Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3); } private static TResult InvokeTypeVal4(T0 _0, T1 _1, T2 _2, T3 _3, TypeVal4 del) { return Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3); } private static void InvokeVoidRef4(ref T0 _0, T1 _1, T2 _2, T3 _3, VoidRef4 del) { Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3); } private static TResult InvokeTypeRef4(ref T0 _0, T1 _1, T2 _2, T3 _3, TypeRef4 del) { return Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3); } private static void InvokeVoidVal5(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, VoidVal5 del) { Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4); } private static TResult InvokeTypeVal5(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, TypeVal5 del) { return Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4); } private static void InvokeVoidRef5(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, VoidRef5 del) { Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4); } private static TResult InvokeTypeRef5(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, TypeRef5 del) { return Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4); } private static void InvokeVoidVal6(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, VoidVal6 del) { Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5); } private static TResult InvokeTypeVal6(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, TypeVal6 del) { return Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5); } private static void InvokeVoidRef6(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, VoidRef6 del) { Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5); } private static TResult InvokeTypeRef6(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, TypeRef6 del) { return Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5); } private static void InvokeVoidVal7(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, VoidVal7 del) { Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6); } private static TResult InvokeTypeVal7(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, TypeVal7 del) { return Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6); } private static void InvokeVoidRef7(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, VoidRef7 del) { Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6); } private static TResult InvokeTypeRef7(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, TypeRef7 del) { return Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6); } private static void InvokeVoidVal8(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, VoidVal8 del) { Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6, _7); } private static TResult InvokeTypeVal8(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, TypeVal8 del) { return Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6, _7); } private static void InvokeVoidRef8(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, VoidRef8 del) { Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6, _7); } private static TResult InvokeTypeRef8(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, TypeRef8 del) { return Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6, _7); } private static void InvokeVoidVal9(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, VoidVal9 del) { Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6, _7, _8); } private static TResult InvokeTypeVal9(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, TypeVal9 del) { return Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6, _7, _8); } private static void InvokeVoidRef9(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, VoidRef9 del) { Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6, _7, _8); } private static TResult InvokeTypeRef9(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, TypeRef9 del) { return Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6, _7, _8); } private static void InvokeVoidVal10(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, VoidVal10 del) { Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9); } private static TResult InvokeTypeVal10(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, TypeVal10 del) { return Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9); } private static void InvokeVoidRef10(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, VoidRef10 del) { Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6, _7, _8, _9); } private static TResult InvokeTypeRef10(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, TypeRef10 del) { return Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6, _7, _8, _9); } private static void InvokeVoidVal11(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, VoidVal11 del) { Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10); } private static TResult InvokeTypeVal11(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, TypeVal11 del) { return Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10); } private static void InvokeVoidRef11(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, VoidRef11 del) { Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10); } private static TResult InvokeTypeRef11(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, TypeRef11 del) { return Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10); } private static void InvokeVoidVal12(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, VoidVal12 del) { Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11); } private static TResult InvokeTypeVal12(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, TypeVal12 del) { return Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11); } private static void InvokeVoidRef12(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, VoidRef12 del) { Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11); } private static TResult InvokeTypeRef12(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, TypeRef12 del) { return Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11); } private static void InvokeVoidVal13(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, VoidVal13 del) { Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12); } private static TResult InvokeTypeVal13(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, TypeVal13 del) { return Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12); } private static void InvokeVoidRef13(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, VoidRef13 del) { Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12); } private static TResult InvokeTypeRef13(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, TypeRef13 del) { return Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12); } private static void InvokeVoidVal14(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, VoidVal14 del) { Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13); } private static TResult InvokeTypeVal14(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, TypeVal14 del) { return Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13); } private static void InvokeVoidRef14(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, VoidRef14 del) { Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13); } private static TResult InvokeTypeRef14(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, TypeRef14 del) { return Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13); } private static void InvokeVoidVal15(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, T14 _14, VoidVal15 del) { Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14); } private static TResult InvokeTypeVal15(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, T14 _14, TypeVal15 del) { return Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14); } private static void InvokeVoidRef15(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, T14 _14, VoidRef15 del) { Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14); } private static TResult InvokeTypeRef15(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, T14 _14, TypeRef15 del) { return Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14); } private static void InvokeVoidVal16(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, T14 _14, T15 _15, VoidVal16 del) { Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15); } private static TResult InvokeTypeVal16(T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, T14 _14, T15 _15, TypeVal16 del) { return Helpers.ThrowIfNull(del, "del")(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15); } private static void InvokeVoidRef16(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, T14 _14, T15 _15, VoidRef16 del) { Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15); } private static TResult InvokeTypeRef16(ref T0 _0, T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, T14 _14, T15 _15, TypeRef16 del) { return Helpers.ThrowIfNull(del, "del")(ref _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15); } } public class ILContext : IDisposable { public delegate void Manipulator(ILContext il); internal List _Labels = new List(); private bool disposedValue; private readonly List> managedObjectRefs = new List>(); public MethodDefinition Method { get; private set; } public ILProcessor IL { get; private set; } public MethodBody Body => Method.Body; public ModuleDefinition Module => ((MemberReference)Method).Module; public Collection Instrs => Body.Instructions; public ReadOnlyCollection Labels => _Labels.AsReadOnly(); public bool IsReadOnly => IL == null; public event Action? OnDispose; public ILContext(MethodDefinition method) { Helpers.ThrowIfArgumentNull(method, "method"); Method = method; IL = method.Body.GetILProcessor(); } public void Invoke(Manipulator manip) { //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_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(manip, "manip"); if (IsReadOnly) { throw new InvalidOperationException(); } Enumerator enumerator = Instrs.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current = enumerator.Current; object operand = current.Operand; Instruction val = (Instruction)((operand is Instruction) ? operand : null); if (val != null) { current.Operand = new ILLabel(this, val); } else if (current.Operand is Instruction[] source) { current.Operand = source.Select((Instruction t) => new ILLabel(this, t)).ToArray(); } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } manip(this); if (IsReadOnly) { return; } enumerator = Instrs.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current2 = enumerator.Current; if (current2.Operand is ILLabel iLLabel) { current2.Operand = iLLabel.Target; } else if (current2.Operand is ILLabel[] source2) { current2.Operand = source2.Select((ILLabel l) => l.Target).ToArray(); } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } Method.FixShortLongOps(); } public void MakeReadOnly() { Method = null; IL = null; _Labels.Clear(); _Labels.Capacity = 0; } [Obsolete("Use new ILCursor(il).Goto(index)")] public ILCursor At(int index) { return new ILCursor(this).Goto(index); } [Obsolete("Use new ILCursor(il).Goto(index)")] public ILCursor At(ILLabel label) { return new ILCursor(this).GotoLabel(label); } [Obsolete("Use new ILCursor(il).Goto(index)")] public ILCursor At(Instruction instr) { return new ILCursor(this).Goto(instr); } public FieldReference Import(FieldInfo field) { return Module.ImportReference(field); } public MethodReference Import(MethodBase method) { return Module.ImportReference(method); } public TypeReference Import(Type type) { return Module.ImportReference(type); } public ILLabel DefineLabel() { return new ILLabel(this); } public ILLabel DefineLabel(Instruction target) { return new ILLabel(this, target); } public int IndexOf(Instruction? instr) { if (instr == null) { return Instrs.Count; } int num = Instrs.IndexOf(instr); if (num != -1) { return num; } return Instrs.Count; } public IEnumerable GetIncomingLabels(Instruction? instr) { return _Labels.Where((ILLabel l) => l.Target == instr); } public int AddReference(in T? value) { int count = managedObjectRefs.Count; DynamicReferenceCell cellRef; DataScope item = DynamicReferenceManager.AllocReference(in value, out cellRef); managedObjectRefs.Add(item); return count; } public T? GetReference(int id) { if (id < 0 || id >= managedObjectRefs.Count) { throw new ArgumentOutOfRangeException("id"); } return DynamicReferenceManager.GetValue(managedObjectRefs[id].Data); } public void SetReference(int id, in T? value) { if (id < 0 || id >= managedObjectRefs.Count) { throw new ArgumentOutOfRangeException("id"); } DynamicReferenceManager.SetValue(managedObjectRefs[id].Data, in value); } public DynamicReferenceCell GetReferenceCell(int id) { if (id < 0 || id >= managedObjectRefs.Count) { throw new ArgumentOutOfRangeException("id"); } return managedObjectRefs[id].Data; } public VariableDefinition CreateLocal() { return CreateLocal(typeof(T)); } public VariableDefinition CreateLocal(Type type) { return CreateLocal(Import(type)); } public VariableDefinition CreateLocal(TypeReference typeRef) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown VariableDefinition val = new VariableDefinition(typeRef); Method.Body.Variables.Add(val); return val; } public override string ToString() { //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) if (Method == null) { return "// ILContext: READONLY"; } StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder2 = stringBuilder; StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(14, 1, stringBuilder2); handler.AppendLiteral("// ILContext: "); handler.AppendFormatted(Method); stringBuilder2.AppendLine(ref handler); Enumerator enumerator = Instrs.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current = enumerator.Current; ToString(stringBuilder, current); } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } return stringBuilder.ToString(); } internal static StringBuilder ToString(StringBuilder builder, Instruction? instr) { if (instr == null) { return builder; } object operand = instr.Operand; if (operand is ILLabel iLLabel) { instr.Operand = iLLabel.Target; } else if (operand is ILLabel[] source) { instr.Operand = source.Select((ILLabel l) => l.Target).ToArray(); } builder.AppendLine(((object)instr).ToString()); instr.Operand = operand; return builder; } protected virtual void Dispose(bool disposing) { if (disposedValue) { return; } this.OnDispose?.Invoke(); this.OnDispose = null; foreach (DataScope managedObjectRef in managedObjectRefs) { managedObjectRef.Dispose(); } managedObjectRefs.Clear(); managedObjectRefs.Capacity = 0; MakeReadOnly(); disposedValue = true; } ~ILContext() { Dispose(disposing: false); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } public enum MoveType { Before, AfterLabel, After } public enum SearchTarget { None, Next, Prev } [EmitILOverloads("ILOpcodes.txt", "ILCursor")] public sealed class ILCursor { private Instruction? _next; private ILLabel[]? _afterLabels; private bool _afterHandlerStarts; private bool _afterHandlerEnds; private SearchTarget _searchTarget; public ILContext Context { get; } public Instruction? Next { get { return _next; } set { Goto(value); } } public Instruction Prev { get { if (Next != null) { return Next.Previous; } return Instrs[Instrs.Count - 1]; } set { Goto(value, MoveType.After); } } public Instruction Previous { get { return Prev; } set { Prev = value; } } public int Index { get { return Context.IndexOf(Next); } set { Goto(value); } } public SearchTarget SearchTarget { get { return _searchTarget; } set { if ((value == SearchTarget.Next && Next == null) || (value == SearchTarget.Prev && Prev == null)) { value = SearchTarget.None; } _searchTarget = value; } } public IEnumerable IncomingLabels => Context.GetIncomingLabels(Next); public MethodDefinition Method => Context.Method; public ILProcessor IL => Context.IL; public MethodBody Body => Context.Body; public ModuleDefinition Module => Context.Module; public Collection Instrs => Context.Instrs; public ILCursor(ILContext context) { Context = context; Index = 0; } public ILCursor(ILCursor c) { Helpers.ThrowIfArgumentNull(c, "c"); Context = c.Context; _next = c._next; _searchTarget = c._searchTarget; _afterLabels = c._afterLabels; _afterHandlerStarts = c._afterHandlerStarts; _afterHandlerEnds = c._afterHandlerEnds; } public ILCursor Clone() { return new ILCursor(this); } public bool IsBefore(Instruction instr) { return Index <= Context.IndexOf(instr); } public bool IsAfter(Instruction instr) { return Index > Context.IndexOf(instr); } public override string ToString() { StringBuilder stringBuilder2; StringBuilder stringBuilder = (stringBuilder2 = new StringBuilder()); StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(17, 3, stringBuilder2); handler.AppendLiteral("// ILCursor: "); handler.AppendFormatted(Method); handler.AppendLiteral(", "); handler.AppendFormatted(Index); handler.AppendLiteral(", "); handler.AppendFormatted(SearchTarget); stringBuilder2.AppendLine(ref handler); ILContext.ToString(stringBuilder, Prev); ILContext.ToString(stringBuilder, Next); return stringBuilder.ToString(); } public ILCursor Goto(Instruction? insn, MoveType moveType = MoveType.Before, bool setTarget = false) { if (moveType == MoveType.After) { _next = ((insn != null) ? insn.Next : null); } else { _next = insn; } if (setTarget) { _searchTarget = ((moveType != MoveType.After) ? SearchTarget.Next : SearchTarget.Prev); } else { _searchTarget = SearchTarget.None; } if (moveType == MoveType.AfterLabel) { MoveAfterLabels(); } else { MoveBeforeLabels(); } return this; } public ILCursor MoveAfterLabels() { MoveAfterLabels(intoEHRanges: true); return this; } public ILCursor MoveAfterLabels(bool intoEHRanges) { _afterLabels = IncomingLabels.ToArray(); _afterHandlerStarts = intoEHRanges; _afterHandlerEnds = true; return this; } public ILCursor MoveBeforeLabels() { _afterLabels = null; _afterHandlerStarts = false; _afterHandlerEnds = false; return this; } public ILCursor Goto(int index, MoveType moveType = MoveType.Before, bool setTarget = false) { if (index < 0) { index += Instrs.Count; } return Goto((index == Instrs.Count) ? null : Instrs[index], moveType, setTarget); } public ILCursor GotoLabel(ILLabel label, MoveType moveType = MoveType.AfterLabel, bool setTarget = false) { return Goto(Helpers.ThrowIfNull(label, "label").Target, moveType, setTarget); } public ILCursor GotoNext(MoveType moveType = MoveType.Before, params Func[] predicates) { if (!TryGotoNext(moveType, predicates)) { throw new KeyNotFoundException(); } return this; } public bool TryGotoNext(MoveType moveType = MoveType.Before, params Func[] predicates) { Helpers.ThrowIfArgumentNull(predicates, "predicates"); Collection instrs = Instrs; int i = Index; if (SearchTarget == SearchTarget.Next) { i++; } for (; i + predicates.Length <= instrs.Count; i++) { int num = 0; while (true) { if (num < predicates.Length) { Func obj = predicates[num]; if (obj != null && !obj(instrs[i + num])) { break; } num++; continue; } Goto((moveType == MoveType.After) ? (i + predicates.Length - 1) : i, moveType, setTarget: true); return true; } } return false; } public ILCursor GotoPrev(MoveType moveType = MoveType.Before, params Func[] predicates) { if (!TryGotoPrev(moveType, predicates)) { throw new KeyNotFoundException(); } return this; } public bool TryGotoPrev(MoveType moveType = MoveType.Before, params Func[] predicates) { Helpers.ThrowIfArgumentNull(predicates, "predicates"); Collection instrs = Instrs; int num = Index - 1; if (SearchTarget == SearchTarget.Prev) { num--; } for (num = Math.Min(num, instrs.Count - predicates.Length); num >= 0; num--) { int num2 = 0; while (true) { if (num2 < predicates.Length) { Func obj = predicates[num2]; if (obj != null && !obj(instrs[num + num2])) { break; } num2++; continue; } Goto((moveType == MoveType.After) ? (num + predicates.Length - 1) : num, moveType, setTarget: true); return true; } } return false; } public ILCursor GotoNext(params Func[] predicates) { return GotoNext(MoveType.Before, predicates); } public bool TryGotoNext(params Func[] predicates) { return TryGotoNext(MoveType.Before, predicates); } public ILCursor GotoPrev(params Func[] predicates) { return GotoPrev(MoveType.Before, predicates); } public bool TryGotoPrev(params Func[] predicates) { return TryGotoPrev(MoveType.Before, predicates); } public void FindNext(out ILCursor[] cursors, params Func[] predicates) { if (!TryFindNext(out cursors, predicates)) { throw new KeyNotFoundException(); } } public bool TryFindNext(out ILCursor[] cursors, params Func[] predicates) { Helpers.ThrowIfArgumentNull(predicates, "predicates"); cursors = new ILCursor[predicates.Length]; ILCursor iLCursor = this; for (int i = 0; i < predicates.Length; i++) { iLCursor = iLCursor.Clone(); if (!iLCursor.TryGotoNext(predicates[i])) { return false; } cursors[i] = iLCursor; } return true; } public void FindPrev(out ILCursor[] cursors, params Func[] predicates) { if (!TryFindPrev(out cursors, predicates)) { throw new KeyNotFoundException(); } } public bool TryFindPrev(out ILCursor[] cursors, params Func[] predicates) { Helpers.ThrowIfArgumentNull(predicates, "predicates"); cursors = new ILCursor[predicates.Length]; ILCursor iLCursor = this; for (int num = predicates.Length - 1; num >= 0; num--) { iLCursor = iLCursor.Clone(); if (!iLCursor.TryGotoPrev(predicates[num])) { return false; } cursors[num] = iLCursor; } return true; } public void MarkLabel(ILLabel? label) { if (label == null) { label = new ILLabel(Context); } label.Target = Next; if (_afterLabels != null) { Array.Resize(ref _afterLabels, _afterLabels.Length + 1); _afterLabels[_afterLabels.Length - 1] = label; } else { _afterLabels = new ILLabel[1] { label }; } } public ILLabel MarkLabel(Instruction inst) { ILLabel iLLabel = Context.DefineLabel(); if (inst == Next) { MarkLabel(iLLabel); return iLLabel; } iLLabel.Target = inst; return iLLabel; } public ILLabel MarkLabel() { ILLabel iLLabel = DefineLabel(); MarkLabel(iLLabel); return iLLabel; } public ILLabel DefineLabel() { return Context.DefineLabel(); } public VariableDefinition CreateLocal() { return Context.CreateLocal(); } public VariableDefinition CreateLocal(Type type) { return Context.CreateLocal(type); } public VariableDefinition CreateLocal(TypeReference typeRef) { return Context.CreateLocal(typeRef); } private ILCursor _Insert(Instruction instr) { //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_00b4: 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) if (_afterLabels != null) { ILLabel[] afterLabels = _afterLabels; for (int i = 0; i < afterLabels.Length; i++) { afterLabels[i].Target = instr; } } if (_afterHandlerStarts) { Enumerator enumerator = Body.ExceptionHandlers.GetEnumerator(); try { while (enumerator.MoveNext()) { ExceptionHandler current = enumerator.Current; if (current.TryStart == Next) { current.TryStart = instr; } if (current.HandlerStart == Next) { current.HandlerStart = instr; } if (current.FilterStart == Next) { current.FilterStart = instr; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } } if (_afterHandlerEnds) { Enumerator enumerator = Body.ExceptionHandlers.GetEnumerator(); try { while (enumerator.MoveNext()) { ExceptionHandler current2 = enumerator.Current; if (current2.TryEnd == Next) { current2.TryEnd = instr; } if (current2.HandlerEnd == Next) { current2.HandlerEnd = instr; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } } Instrs.Insert(Index, instr); Goto(instr, MoveType.After); return this; } public ILCursor Remove() { return RemoveRange(1); } public ILCursor RemoveRange(int num) { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) int index = Index; Instruction val = ((index + num < Instrs.Count) ? Instrs[index + num] : null); foreach (ILLabel incomingLabel in IncomingLabels) { incomingLabel.Target = val; } Enumerator enumerator2 = Body.ExceptionHandlers.GetEnumerator(); try { while (enumerator2.MoveNext()) { ExceptionHandler current = enumerator2.Current; if (current.TryStart == Next) { current.TryStart = val; } if (current.TryEnd == Next) { current.TryEnd = val; } if (current.HandlerStart == Next) { current.HandlerStart = val; } if (current.FilterStart == Next) { current.FilterStart = val; } if (current.HandlerEnd == Next) { current.HandlerEnd = val; } } } finally { ((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose(); } while (num-- > 0) { Instrs.RemoveAt(index); } _searchTarget = SearchTarget.None; _next = val; return this; } public ILCursor Emit(OpCode opcode, ParameterDefinition parameter) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, parameter)); } public ILCursor Emit(OpCode opcode, VariableDefinition variable) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, variable)); } public ILCursor Emit(OpCode opcode, Instruction[] targets) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, targets)); } public ILCursor Emit(OpCode opcode, Instruction target) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, target)); } public ILCursor Emit(OpCode opcode, double value) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, value)); } public ILCursor Emit(OpCode opcode, float value) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, value)); } public ILCursor Emit(OpCode opcode, long value) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, value)); } public ILCursor Emit(OpCode opcode, sbyte value) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, value)); } public ILCursor Emit(OpCode opcode, byte value) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, value)); } public ILCursor Emit(OpCode opcode, string value) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, value)); } public ILCursor Emit(OpCode opcode, FieldReference field) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, field)); } public ILCursor Emit(OpCode opcode, CallSite site) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, site)); } public ILCursor Emit(OpCode opcode, TypeReference type) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, type)); } public ILCursor Emit(OpCode opcode) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode)); } public ILCursor Emit(OpCode opcode, int value) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, value)); } public ILCursor Emit(OpCode opcode, MethodReference method) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, method)); } public ILCursor Emit(OpCode opcode, FieldInfo field) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, field)); } public ILCursor Emit(OpCode opcode, MethodBase method) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, method)); } public ILCursor Emit(OpCode opcode, Type type) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, type)); } public ILCursor Emit(OpCode opcode, object operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, operand)); } public ILCursor Emit(OpCode opcode, string memberName) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(opcode, typeof(T).GetMember(memberName, (BindingFlags)(-1)).First())); } public int AddReference(in T t) { return Context.AddReference(in t); } public void EmitGetReference(int id) { this.EmitLoadTypedReference(Context.GetReferenceCell(id), typeof(T)); } public int EmitReference(in T? t) { int num = AddReference(in t); this.EmitLoadTypedReferenceUnsafe(Context.GetReferenceCell(num), typeof(T)); return num; } public int EmitDelegate(T cb) where T : Delegate { //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_008c: 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) Helpers.ThrowIfArgumentNull(cb, "cb"); if (cb.GetInvocationList().Length == 1 && cb.Target == null) { Emit(OpCodes.Call, (MethodBase)cb.Method); return -1; } (MethodInfo, Type)? delegateInvoker = FastDelegateInvokers.GetDelegateInvoker(typeof(T)); int result; if (delegateInvoker.HasValue) { (MethodInfo, Type) valueOrDefault = delegateInvoker.GetValueOrDefault(); result = EmitReference(cb.CastDelegate(valueOrDefault.Item2)); AddReference(in valueOrDefault.Item1); Emit(OpCodes.Call, (MethodBase)valueOrDefault.Item1); } else { result = EmitReference(in cb); MethodInfo method = typeof(T).GetMethod("Invoke"); Emit(OpCodes.Callvirt, (MethodBase)method); } return result; } public ILCursor EmitAdd() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Add)); } public ILCursor EmitAddOvf() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Add_Ovf)); } public ILCursor EmitAddOvfUn() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Add_Ovf_Un)); } public ILCursor EmitAnd() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.And)); } public ILCursor EmitArglist() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Arglist)); } public ILCursor EmitBeq(ILLabel operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Beq, operand)); } public ILCursor EmitBeq(Instruction operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Beq, MarkLabel(operand))); } public ILCursor EmitBge(ILLabel operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Bge, operand)); } public ILCursor EmitBge(Instruction operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Bge, MarkLabel(operand))); } public ILCursor EmitBgeUn(ILLabel operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Bge_Un, operand)); } public ILCursor EmitBgeUn(Instruction operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Bge_Un, MarkLabel(operand))); } public ILCursor EmitBgt(ILLabel operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Bgt, operand)); } public ILCursor EmitBgt(Instruction operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Bgt, MarkLabel(operand))); } public ILCursor EmitBgtUn(ILLabel operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Bgt_Un, operand)); } public ILCursor EmitBgtUn(Instruction operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Bgt_Un, MarkLabel(operand))); } public ILCursor EmitBle(ILLabel operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ble, operand)); } public ILCursor EmitBle(Instruction operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ble, MarkLabel(operand))); } public ILCursor EmitBleUn(ILLabel operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ble_Un, operand)); } public ILCursor EmitBleUn(Instruction operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ble_Un, MarkLabel(operand))); } public ILCursor EmitBlt(ILLabel operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Blt, operand)); } public ILCursor EmitBlt(Instruction operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Blt, MarkLabel(operand))); } public ILCursor EmitBltUn(ILLabel operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Blt_Un, operand)); } public ILCursor EmitBltUn(Instruction operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Blt_Un, MarkLabel(operand))); } public ILCursor EmitBneUn(ILLabel operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Bne_Un, operand)); } public ILCursor EmitBneUn(Instruction operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Bne_Un, MarkLabel(operand))); } public ILCursor EmitBox(TypeReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Box, operand)); } public ILCursor EmitBox(Type operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Box, Context.Import(operand))); } public ILCursor EmitBr(ILLabel operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Br, operand)); } public ILCursor EmitBr(Instruction operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Br, MarkLabel(operand))); } public ILCursor EmitBreak() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Break)); } public ILCursor EmitBrfalse(ILLabel operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Brfalse, operand)); } public ILCursor EmitBrfalse(Instruction operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Brfalse, MarkLabel(operand))); } public ILCursor EmitBrtrue(ILLabel operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Brtrue, operand)); } public ILCursor EmitBrtrue(Instruction operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Brtrue, MarkLabel(operand))); } public ILCursor EmitCall(MethodReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Call, operand)); } public ILCursor EmitCall(MethodBase operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Call, Context.Import(operand))); } public ILCursor EmitCalli(IMethodSignature operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Calli, operand)); } public ILCursor EmitCallvirt(MethodReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Callvirt, operand)); } public ILCursor EmitCallvirt(MethodBase operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Callvirt, Context.Import(operand))); } public ILCursor EmitCastclass(TypeReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Castclass, operand)); } public ILCursor EmitCastclass(Type operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Castclass, Context.Import(operand))); } public ILCursor EmitCeq() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ceq)); } public ILCursor EmitCgt() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Cgt)); } public ILCursor EmitCgtUn() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Cgt_Un)); } public ILCursor EmitCkfinite() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ckfinite)); } public ILCursor EmitClt() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Clt)); } public ILCursor EmitCltUn() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Clt_Un)); } public ILCursor EmitConstrained(TypeReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Constrained, operand)); } public ILCursor EmitConstrained(Type operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Constrained, Context.Import(operand))); } public ILCursor EmitConvI() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_I)); } public ILCursor EmitConvI1() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_I1)); } public ILCursor EmitConvI2() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_I2)); } public ILCursor EmitConvI4() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_I4)); } public ILCursor EmitConvI8() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_I8)); } public ILCursor EmitConvOvfI() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_I)); } public ILCursor EmitConvOvfIUn() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_I_Un)); } public ILCursor EmitConvOvfI1() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_I1)); } public ILCursor EmitConvOvfI1Un() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_I1_Un)); } public ILCursor EmitConvOvfI2() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_I2)); } public ILCursor EmitConvOvfI2Un() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_I2_Un)); } public ILCursor EmitConvOvfI4() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_I4)); } public ILCursor EmitConvOvfI4Un() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_I4_Un)); } public ILCursor EmitConvOvfI8() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_I8)); } public ILCursor EmitConvOvfI8Un() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_I8_Un)); } public ILCursor EmitConvOvfU() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_U)); } public ILCursor EmitConvOvfUUn() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_U_Un)); } public ILCursor EmitConvOvfU1() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_U1)); } public ILCursor EmitConvOvfU1Un() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_U1_Un)); } public ILCursor EmitConvOvfU2() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_U2)); } public ILCursor EmitConvOvfU2Un() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_U2_Un)); } public ILCursor EmitConvOvfU4() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_U4)); } public ILCursor EmitConvOvfU4Un() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_U4_Un)); } public ILCursor EmitConvOvfU8() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_U8)); } public ILCursor EmitConvOvfU8Un() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_Ovf_U8_Un)); } public ILCursor EmitConvRUn() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_R_Un)); } public ILCursor EmitConvR4() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_R4)); } public ILCursor EmitConvR8() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_R8)); } public ILCursor EmitConvU() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_U)); } public ILCursor EmitConvU1() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_U1)); } public ILCursor EmitConvU2() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_U2)); } public ILCursor EmitConvU4() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_U4)); } public ILCursor EmitConvU8() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Conv_U8)); } public ILCursor EmitCpblk() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Cpblk)); } public ILCursor EmitCpobj(TypeReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Cpobj, operand)); } public ILCursor EmitCpobj(Type operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Cpobj, Context.Import(operand))); } public ILCursor EmitDiv() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Div)); } public ILCursor EmitDivUn() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Div_Un)); } public ILCursor EmitDup() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Dup)); } public ILCursor EmitEndfilter() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Endfilter)); } public ILCursor EmitEndfinally() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Endfinally)); } public ILCursor EmitInitblk() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Initblk)); } public ILCursor EmitInitobj(TypeReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Initobj, operand)); } public ILCursor EmitInitobj(Type operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Initobj, Context.Import(operand))); } public ILCursor EmitIsinst(TypeReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Isinst, operand)); } public ILCursor EmitIsinst(Type operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Isinst, Context.Import(operand))); } public ILCursor EmitJmp(MethodReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Jmp, operand)); } public ILCursor EmitJmp(MethodBase operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Jmp, Context.Import(operand))); } public ILCursor EmitLdarg0() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldarg_0)); } public ILCursor EmitLdarg1() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldarg_1)); } public ILCursor EmitLdarg2() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldarg_2)); } public ILCursor EmitLdarg3() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldarg_3)); } public ILCursor EmitLdarg(int operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldarg, operand)); } public ILCursor EmitLdarg(uint operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldarg, (int)operand)); } public ILCursor EmitLdarg(ParameterReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldarg, operand)); } public ILCursor EmitLdarga(int operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldarga, operand)); } public ILCursor EmitLdarga(uint operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldarga, (int)operand)); } public ILCursor EmitLdarga(ParameterReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldarga, operand)); } public ILCursor EmitLdcI4(int operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldc_I4, operand)); } public ILCursor EmitLdcI4(uint operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldc_I4, (int)operand)); } public ILCursor EmitLdcI8(long operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldc_I8, operand)); } public ILCursor EmitLdcI8(ulong operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldc_I8, (long)operand)); } public ILCursor EmitLdcR4(float operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldc_R4, operand)); } public ILCursor EmitLdcR8(double operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldc_R8, operand)); } public ILCursor EmitLdelemAny(TypeReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldelem_Any, operand)); } public ILCursor EmitLdelemAny(Type operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldelem_Any, Context.Import(operand))); } public ILCursor EmitLdelemI() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldelem_I)); } public ILCursor EmitLdelemI1() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldelem_I1)); } public ILCursor EmitLdelemI2() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldelem_I2)); } public ILCursor EmitLdelemI4() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldelem_I4)); } public ILCursor EmitLdelemI8() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldelem_I8)); } public ILCursor EmitLdelemR4() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldelem_R4)); } public ILCursor EmitLdelemR8() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldelem_R8)); } public ILCursor EmitLdelemRef() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldelem_Ref)); } public ILCursor EmitLdelemU1() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldelem_U1)); } public ILCursor EmitLdelemU2() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldelem_U2)); } public ILCursor EmitLdelemU4() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldelem_U4)); } public ILCursor EmitLdelema(TypeReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldelema, operand)); } public ILCursor EmitLdelema(Type operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldelema, Context.Import(operand))); } public ILCursor EmitLdfld(FieldReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldfld, operand)); } public ILCursor EmitLdfld(FieldInfo operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldfld, Context.Import(operand))); } public ILCursor EmitLdflda(FieldReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldflda, operand)); } public ILCursor EmitLdflda(FieldInfo operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldflda, Context.Import(operand))); } public ILCursor EmitLdftn(MethodReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldftn, operand)); } public ILCursor EmitLdftn(MethodBase operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldftn, Context.Import(operand))); } public ILCursor EmitLdindI() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldind_I)); } public ILCursor EmitLdindI1() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldind_I1)); } public ILCursor EmitLdindI2() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldind_I2)); } public ILCursor EmitLdindI4() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldind_I4)); } public ILCursor EmitLdindI8() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldind_I8)); } public ILCursor EmitLdindR4() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldind_R4)); } public ILCursor EmitLdindR8() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldind_R8)); } public ILCursor EmitLdindRef() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldind_Ref)); } public ILCursor EmitLdindU1() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldind_U1)); } public ILCursor EmitLdindU2() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldind_U2)); } public ILCursor EmitLdindU4() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldind_U4)); } public ILCursor EmitLdlen() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldlen)); } public ILCursor EmitLdloc0() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldloc_0)); } public ILCursor EmitLdloc1() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldloc_1)); } public ILCursor EmitLdloc2() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldloc_2)); } public ILCursor EmitLdloc3() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldloc_3)); } public ILCursor EmitLdloc(int operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldloc, operand)); } public ILCursor EmitLdloc(uint operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldloc, (int)operand)); } public ILCursor EmitLdloc(VariableReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldloc, operand)); } public ILCursor EmitLdloca(int operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldloca, operand)); } public ILCursor EmitLdloca(uint operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldloca, (int)operand)); } public ILCursor EmitLdloca(VariableReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldloca, operand)); } public ILCursor EmitLdnull() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldnull)); } public ILCursor EmitLdobj(TypeReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldobj, operand)); } public ILCursor EmitLdobj(Type operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldobj, Context.Import(operand))); } public ILCursor EmitLdsfld(FieldReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldsfld, operand)); } public ILCursor EmitLdsfld(FieldInfo operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldsfld, Context.Import(operand))); } public ILCursor EmitLdsflda(FieldReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldsflda, operand)); } public ILCursor EmitLdsflda(FieldInfo operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldsflda, Context.Import(operand))); } public ILCursor EmitLdstr(string operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldstr, operand)); } public ILCursor EmitLdtoken(IMetadataTokenProvider operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldtoken, operand)); } public ILCursor EmitLdtoken(Type operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldtoken, Context.Import(operand))); } public ILCursor EmitLdtoken(FieldInfo operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldtoken, Context.Import(operand))); } public ILCursor EmitLdtoken(MethodBase operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldtoken, Context.Import(operand))); } public ILCursor EmitLdvirtftn(MethodReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldvirtftn, operand)); } public ILCursor EmitLdvirtftn(MethodBase operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ldvirtftn, Context.Import(operand))); } public ILCursor EmitLeave(ILLabel operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Leave, operand)); } public ILCursor EmitLeave(Instruction operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Leave, MarkLabel(operand))); } public ILCursor EmitLocalloc() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Localloc)); } public ILCursor EmitMkrefany(TypeReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Mkrefany, operand)); } public ILCursor EmitMkrefany(Type operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Mkrefany, Context.Import(operand))); } public ILCursor EmitMul() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Mul)); } public ILCursor EmitMulOvf() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Mul_Ovf)); } public ILCursor EmitMulOvfUn() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Mul_Ovf_Un)); } public ILCursor EmitNeg() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Neg)); } public ILCursor EmitNewarr(TypeReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Newarr, operand)); } public ILCursor EmitNewarr(Type operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Newarr, Context.Import(operand))); } public ILCursor EmitNewobj(MethodReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Newobj, operand)); } public ILCursor EmitNewobj(MethodBase operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Newobj, Context.Import(operand))); } public ILCursor EmitNop() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Nop)); } public ILCursor EmitNot() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Not)); } public ILCursor EmitOr() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Or)); } public ILCursor EmitPop() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Pop)); } public ILCursor EmitReadonly() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Readonly)); } public ILCursor EmitRefanytype() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Refanytype)); } public ILCursor EmitRefanyval(TypeReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Refanyval, operand)); } public ILCursor EmitRefanyval(Type operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Refanyval, Context.Import(operand))); } public ILCursor EmitRem() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Rem)); } public ILCursor EmitRemUn() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Rem_Un)); } public ILCursor EmitRet() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Ret)); } public ILCursor EmitRethrow() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Rethrow)); } public ILCursor EmitShl() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Shl)); } public ILCursor EmitShr() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Shr)); } public ILCursor EmitShrUn() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Shr_Un)); } public ILCursor EmitSizeof(TypeReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Sizeof, operand)); } public ILCursor EmitSizeof(Type operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Sizeof, Context.Import(operand))); } public ILCursor EmitStarg(int operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Starg, operand)); } public ILCursor EmitStarg(uint operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Starg, (int)operand)); } public ILCursor EmitStarg(ParameterReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Starg, operand)); } public ILCursor EmitStelemAny(TypeReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stelem_Any, operand)); } public ILCursor EmitStelemAny(Type operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stelem_Any, Context.Import(operand))); } public ILCursor EmitStelemI() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stelem_I)); } public ILCursor EmitStelemI1() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stelem_I1)); } public ILCursor EmitStelemI2() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stelem_I2)); } public ILCursor EmitStelemI4() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stelem_I4)); } public ILCursor EmitStelemI8() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stelem_I8)); } public ILCursor EmitStelemR4() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stelem_R4)); } public ILCursor EmitStelemR8() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stelem_R8)); } public ILCursor EmitStelemRef() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stelem_Ref)); } public ILCursor EmitStfld(FieldReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stfld, operand)); } public ILCursor EmitStfld(FieldInfo operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stfld, Context.Import(operand))); } public ILCursor EmitStindI() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stind_I)); } public ILCursor EmitStindI1() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stind_I1)); } public ILCursor EmitStindI2() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stind_I2)); } public ILCursor EmitStindI4() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stind_I4)); } public ILCursor EmitStindI8() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stind_I8)); } public ILCursor EmitStindR4() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stind_R4)); } public ILCursor EmitStindR8() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stind_R8)); } public ILCursor EmitStindRef() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stind_Ref)); } public ILCursor EmitStloc0() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stloc_0)); } public ILCursor EmitStloc1() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stloc_1)); } public ILCursor EmitStloc2() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stloc_2)); } public ILCursor EmitStloc3() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stloc_3)); } public ILCursor EmitStloc(int operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stloc, operand)); } public ILCursor EmitStloc(uint operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stloc, (int)operand)); } public ILCursor EmitStloc(VariableReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stloc, operand)); } public ILCursor EmitStobj(TypeReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stobj, operand)); } public ILCursor EmitStobj(Type operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stobj, Context.Import(operand))); } public ILCursor EmitStsfld(FieldReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stsfld, operand)); } public ILCursor EmitStsfld(FieldInfo operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Stsfld, Context.Import(operand))); } public ILCursor EmitSub() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Sub)); } public ILCursor EmitSubOvf() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Sub_Ovf)); } public ILCursor EmitSubOvfUn() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Sub_Ovf_Un)); } public ILCursor EmitSwitch(ILLabel[] operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Switch, operand)); } public ILCursor EmitSwitch(Instruction[] operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Switch, operand.Select(MarkLabel).ToArray())); } public ILCursor EmitTail() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Tail)); } public ILCursor EmitThrow() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Throw)); } public ILCursor EmitUnaligned(byte operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Unaligned, operand)); } public ILCursor EmitUnbox(TypeReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Unbox, operand)); } public ILCursor EmitUnbox(Type operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Unbox, Context.Import(operand))); } public ILCursor EmitUnboxAny(TypeReference operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Unbox_Any, operand)); } public ILCursor EmitUnboxAny(Type operand) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Unbox_Any, Context.Import(operand))); } public ILCursor EmitVolatile() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Volatile)); } public ILCursor EmitXor() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _Insert(IL.Create(OpCodes.Xor)); } } public sealed class ILLabel { private readonly ILContext Context; public Instruction? Target { get; set; } public IEnumerable Branches => ((IEnumerable)Context.Instrs).Where((Instruction i) => i.Operand == this); internal ILLabel(ILContext context) { Context = context; Context._Labels.Add(this); } internal ILLabel(ILContext context, Instruction? target) : this(context) { Target = target; } } [EmitILOverloads("ILOpcodes.txt", "ILMatcher")] public static class ILPatternMatchingExt { private sealed class ParameterRefEqualityComparer : IEqualityComparer { public static readonly ParameterRefEqualityComparer Instance = new ParameterRefEqualityComparer(); public bool Equals(ParameterReference? x, ParameterReference? y) { if (x == null) { return y == null; } if (y == null) { return false; } return IsEquivalent(x.ParameterType, y.ParameterType); } public int GetHashCode([DisallowNull] ParameterReference obj) { return ((object)obj.ParameterType).GetHashCode(); } } private static bool IsEquivalent(int l, int r) { return l == r; } private static bool IsEquivalent(int l, uint r) { return l == (int)r; } private static bool IsEquivalent(long l, long r) { return l == r; } private static bool IsEquivalent(long l, ulong r) { return l == (long)r; } private static bool IsEquivalent(float l, float r) { return l == r; } private static bool IsEquivalent(double l, double r) { return l == r; } private static bool IsEquivalent(string l, string r) { return l == r; } private static bool IsEquivalent(ILLabel l, ILLabel r) { return l == r; } private static bool IsEquivalent(ILLabel l, Instruction r) { return IsEquivalent(l.Target, r); } private static bool IsEquivalent(Instruction? l, Instruction? r) { return l == r; } private static bool IsEquivalent(TypeReference l, TypeReference r) { return l == r; } private static bool IsEquivalent(TypeReference l, Type r) { return ((MemberReference?)(object)l).Is(r); } private static bool IsEquivalent(MethodReference l, MethodReference r) { return l == r; } private static bool IsEquivalent(MethodReference l, MethodBase r) { return ((MemberReference?)(object)l).Is(r); } private static bool IsEquivalent(MethodReference l, Type type, string name) { if (((MemberReference?)(object)((MemberReference)l).DeclaringType).Is(type)) { return ((MemberReference)l).Name == name; } return false; } private static bool IsEquivalent(FieldReference l, FieldReference r) { return l == r; } private static bool IsEquivalent(FieldReference l, FieldInfo r) { return ((MemberReference?)(object)l).Is(r); } private static bool IsEquivalent(FieldReference l, Type type, string name) { if (((MemberReference?)(object)((MemberReference)l).DeclaringType).Is(type)) { return ((MemberReference)l).Name == name; } return false; } private static bool IsEquivalent(ILLabel[] l, ILLabel[] r) { if (l != r) { return ((ReadOnlySpan)l).SequenceEqual((ReadOnlySpan)r, (IEqualityComparer?)null); } return true; } private static bool IsEquivalent(ILLabel[] l, Instruction[] r) { if (l.Length != r.Length) { return false; } for (int i = 0; i < l.Length; i++) { if (!IsEquivalent(l[i].Target, r[i])) { return false; } } return true; } private static bool IsEquivalent(IMethodSignature l, IMethodSignature r) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) if (l != r) { if (l.CallingConvention == r.CallingConvention && l.HasThis == r.HasThis && l.ExplicitThis == r.ExplicitThis && IsEquivalent(l.ReturnType, r.ReturnType)) { return CastParamsToRef(l).SequenceEqual(CastParamsToRef(r), ParameterRefEqualityComparer.Instance); } return false; } return true; } private static IEnumerable CastParamsToRef(IMethodSignature sig) { return (IEnumerable)sig.Parameters; } private static bool IsEquivalent(IMetadataTokenProvider l, IMetadataTokenProvider r) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) if (l != r) { return l.MetadataToken == r.MetadataToken; } return true; } private static bool IsEquivalent(IMetadataTokenProvider l, Type r) { TypeReference val = (TypeReference)(object)((l is TypeReference) ? l : null); if (val == null) { return false; } return IsEquivalent(val, r); } private static bool IsEquivalent(IMetadataTokenProvider l, FieldInfo r) { FieldReference val = (FieldReference)(object)((l is FieldReference) ? l : null); if (val == null) { return false; } return IsEquivalent(val, r); } private static bool IsEquivalent(IMetadataTokenProvider l, MethodBase r) { MethodReference val = (MethodReference)(object)((l is MethodReference) ? l : null); if (val == null) { return false; } return IsEquivalent(val, r); } public static bool Match(this Instruction instr, OpCode opcode) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == opcode; } public static bool Match(this Instruction instr, OpCode opcode, T value) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) if (instr.Match(opcode, out var value2)) { ref T reference = ref value2; T val = default(T); if (val == null) { val = reference; reference = ref val; if (val == null) { return value == null; } } object obj = value; return reference.Equals(obj); } return false; } public static bool Match(this Instruction instr, OpCode opcode, [MaybeNullWhen(false)] out T value) { //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) Helpers.ThrowIfArgumentNull(instr, "instr"); if (instr.OpCode == opcode && instr.Operand is T val) { value = val; return true; } value = default(T); return false; } [Obsolete("Leftover from legacy MonoMod, use MatchLeave instead")] public static bool MatchLeaveS(this Instruction instr, ILLabel value) { if (instr.MatchLeaveS(out ILLabel value2)) { return value2 == value; } return false; } [Obsolete("Leftover from legacy MonoMod, use MatchLeave instead")] public static bool MatchLeaveS(this Instruction instr, [MaybeNullWhen(false)] out ILLabel value) { //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) Helpers.ThrowIfArgumentNull(instr, "instr"); if (instr.OpCode == OpCodes.Leave_S) { value = (ILLabel)instr.Operand; return true; } value = null; return false; } public static bool MatchLdarg(this Instruction instr, out int value) { //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_0036: 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_0023: 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_0049: 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_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(instr, "instr"); if (instr.OpCode == OpCodes.Ldarg || instr.OpCode == OpCodes.Ldarg_S) { value = ((ParameterReference)instr.Operand).Index; return true; } if (instr.OpCode == OpCodes.Ldarg_0) { value = 0; return true; } if (instr.OpCode == OpCodes.Ldarg_1) { value = 1; return true; } if (instr.OpCode == OpCodes.Ldarg_2) { value = 2; return true; } if (instr.OpCode == OpCodes.Ldarg_3) { value = 3; return true; } value = 0; return false; } private static int ParameterToIndex(object? obj) { if (obj != null) { if (!(obj is int result)) { if (!(obj is short result2)) { if (!(obj is uint result3)) { if (!(obj is ushort result4)) { if (!(obj is byte result5)) { if (!(obj is sbyte result6)) { ParameterReference val = (ParameterReference)((obj is ParameterReference) ? obj : null); if (val != null) { return val.Index; } throw new InvalidCastException(); } return result6; } return result5; } return result4; } return (int)result3; } return result2; } return result; } return 0; } public static bool MatchStarg(this Instruction instr, out int value) { //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_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(instr, "instr"); if (instr.OpCode == OpCodes.Starg || instr.OpCode == OpCodes.Starg_S) { value = ParameterToIndex(instr.Operand); return true; } value = 0; return false; } public static bool MatchLdarga(this Instruction instr, out int value) { //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_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(instr, "instr"); if (instr.OpCode == OpCodes.Ldarga || instr.OpCode == OpCodes.Ldarga_S) { value = ParameterToIndex(instr.Operand); return true; } value = 0; return false; } private static int VarToIndex(object? obj) { if (obj != null) { if (!(obj is int result)) { if (!(obj is short result2)) { if (!(obj is uint result3)) { if (!(obj is ushort result4)) { if (!(obj is byte result5)) { if (!(obj is sbyte result6)) { VariableReference val = (VariableReference)((obj is VariableReference) ? obj : null); if (val != null) { return val.Index; } throw new InvalidCastException(); } return result6; } return result5; } return result4; } return (int)result3; } return result2; } return result; } return 0; } public static bool MatchLdloc(this Instruction instr, out int value) { //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_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_003f: 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_0056: 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_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0072: 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_0089: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(instr, "instr"); if (instr.OpCode == OpCodes.Ldloc || instr.OpCode == OpCodes.Ldloc_S) { value = VarToIndex(instr.Operand); return true; } if (instr.OpCode == OpCodes.Ldloc_0) { value = 0; return true; } if (instr.OpCode == OpCodes.Ldloc_1) { value = 1; return true; } if (instr.OpCode == OpCodes.Ldloc_2) { value = 2; return true; } if (instr.OpCode == OpCodes.Ldloc_3) { value = 3; return true; } value = 0; return false; } public static bool MatchStloc(this Instruction instr, out int value) { //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_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_003f: 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_0056: 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_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0072: 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_0089: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(instr, "instr"); if (instr.OpCode == OpCodes.Stloc || instr.OpCode == OpCodes.Stloc_S) { value = VarToIndex(instr.Operand); return true; } if (instr.OpCode == OpCodes.Stloc_0) { value = 0; return true; } if (instr.OpCode == OpCodes.Stloc_1) { value = 1; return true; } if (instr.OpCode == OpCodes.Stloc_2) { value = 2; return true; } if (instr.OpCode == OpCodes.Stloc_3) { value = 3; return true; } value = 0; return false; } public static bool MatchLdloca(this Instruction instr, out int value) { //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_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(instr, "instr"); if (instr.OpCode == OpCodes.Ldloca || instr.OpCode == OpCodes.Ldloca_S) { value = VarToIndex(instr.Operand); return true; } value = 0; return false; } public static bool MatchLdcI4(this Instruction instr, out int value) { //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_002d: 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_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_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0093: 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_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: 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_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(instr, "instr"); if (instr.OpCode == OpCodes.Ldc_I4) { value = (int)instr.Operand; return true; } if (instr.OpCode == OpCodes.Ldc_I4_S) { value = (sbyte)instr.Operand; return true; } if (instr.OpCode == OpCodes.Ldc_I4_0) { value = 0; return true; } if (instr.OpCode == OpCodes.Ldc_I4_1) { value = 1; return true; } if (instr.OpCode == OpCodes.Ldc_I4_2) { value = 2; return true; } if (instr.OpCode == OpCodes.Ldc_I4_3) { value = 3; return true; } if (instr.OpCode == OpCodes.Ldc_I4_4) { value = 4; return true; } if (instr.OpCode == OpCodes.Ldc_I4_5) { value = 5; return true; } if (instr.OpCode == OpCodes.Ldc_I4_6) { value = 6; return true; } if (instr.OpCode == OpCodes.Ldc_I4_7) { value = 7; return true; } if (instr.OpCode == OpCodes.Ldc_I4_8) { value = 8; return true; } if (instr.OpCode == OpCodes.Ldc_I4_M1) { value = -1; return true; } value = 0; return false; } public static bool MatchCallOrCallvirt(this Instruction instr, [MaybeNullWhen(false)] out MethodReference value) { //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_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(instr, "instr"); if (instr.OpCode == OpCodes.Call || instr.OpCode == OpCodes.Callvirt) { object operand = instr.Operand; MethodReference val = (MethodReference)((operand is MethodReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchNewobj(this Instruction instr, Type type) { if (instr.MatchNewobj(out MethodReference value)) { return ((MemberReference?)(object)((MemberReference)value).DeclaringType).Is(type); } return false; } public static bool MatchNewobj(this Instruction instr) { return instr.MatchNewobj(typeof(T)); } public static bool MatchNewobj(this Instruction instr, string typeFullName) { if (instr.MatchNewobj(out MethodReference value)) { return ((MemberReference)(object)((MemberReference)value).DeclaringType).Is(typeFullName); } return false; } public static bool MatchAdd(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Add; } public static bool MatchAddOvf(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Add_Ovf; } public static bool MatchAddOvfUn(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Add_Ovf_Un; } public static bool MatchAnd(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.And; } public static bool MatchArglist(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Arglist; } public static bool MatchBeq(this Instruction instr, [MaybeNullWhen(false)] out ILLabel value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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_0022: Unknown result type (might be due to invalid IL or missing references) if ((Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Beq || instr.OpCode == OpCodes.Beq_S) && instr.Operand is ILLabel iLLabel) { value = iLLabel; return true; } value = null; return false; } public static bool MatchBeq(this Instruction instr, ILLabel value) { if (instr.MatchBeq(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBeq(this Instruction instr, Instruction value) { if (instr.MatchBeq(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBge(this Instruction instr, [MaybeNullWhen(false)] out ILLabel value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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_0022: Unknown result type (might be due to invalid IL or missing references) if ((Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Bge || instr.OpCode == OpCodes.Bge_S) && instr.Operand is ILLabel iLLabel) { value = iLLabel; return true; } value = null; return false; } public static bool MatchBge(this Instruction instr, ILLabel value) { if (instr.MatchBge(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBge(this Instruction instr, Instruction value) { if (instr.MatchBge(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBgeUn(this Instruction instr, [MaybeNullWhen(false)] out ILLabel value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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_0022: Unknown result type (might be due to invalid IL or missing references) if ((Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Bge_Un || instr.OpCode == OpCodes.Bge_Un_S) && instr.Operand is ILLabel iLLabel) { value = iLLabel; return true; } value = null; return false; } public static bool MatchBgeUn(this Instruction instr, ILLabel value) { if (instr.MatchBgeUn(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBgeUn(this Instruction instr, Instruction value) { if (instr.MatchBgeUn(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBgt(this Instruction instr, [MaybeNullWhen(false)] out ILLabel value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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_0022: Unknown result type (might be due to invalid IL or missing references) if ((Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Bgt || instr.OpCode == OpCodes.Bgt_S) && instr.Operand is ILLabel iLLabel) { value = iLLabel; return true; } value = null; return false; } public static bool MatchBgt(this Instruction instr, ILLabel value) { if (instr.MatchBgt(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBgt(this Instruction instr, Instruction value) { if (instr.MatchBgt(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBgtUn(this Instruction instr, [MaybeNullWhen(false)] out ILLabel value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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_0022: Unknown result type (might be due to invalid IL or missing references) if ((Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Bgt_Un || instr.OpCode == OpCodes.Bgt_Un_S) && instr.Operand is ILLabel iLLabel) { value = iLLabel; return true; } value = null; return false; } public static bool MatchBgtUn(this Instruction instr, ILLabel value) { if (instr.MatchBgtUn(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBgtUn(this Instruction instr, Instruction value) { if (instr.MatchBgtUn(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBle(this Instruction instr, [MaybeNullWhen(false)] out ILLabel value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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_0022: Unknown result type (might be due to invalid IL or missing references) if ((Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ble || instr.OpCode == OpCodes.Ble_S) && instr.Operand is ILLabel iLLabel) { value = iLLabel; return true; } value = null; return false; } public static bool MatchBle(this Instruction instr, ILLabel value) { if (instr.MatchBle(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBle(this Instruction instr, Instruction value) { if (instr.MatchBle(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBleUn(this Instruction instr, [MaybeNullWhen(false)] out ILLabel value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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_0022: Unknown result type (might be due to invalid IL or missing references) if ((Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ble_Un || instr.OpCode == OpCodes.Ble_Un_S) && instr.Operand is ILLabel iLLabel) { value = iLLabel; return true; } value = null; return false; } public static bool MatchBleUn(this Instruction instr, ILLabel value) { if (instr.MatchBleUn(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBleUn(this Instruction instr, Instruction value) { if (instr.MatchBleUn(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBlt(this Instruction instr, [MaybeNullWhen(false)] out ILLabel value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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_0022: Unknown result type (might be due to invalid IL or missing references) if ((Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Blt || instr.OpCode == OpCodes.Blt_S) && instr.Operand is ILLabel iLLabel) { value = iLLabel; return true; } value = null; return false; } public static bool MatchBlt(this Instruction instr, ILLabel value) { if (instr.MatchBlt(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBlt(this Instruction instr, Instruction value) { if (instr.MatchBlt(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBltUn(this Instruction instr, [MaybeNullWhen(false)] out ILLabel value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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_0022: Unknown result type (might be due to invalid IL or missing references) if ((Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Blt_Un || instr.OpCode == OpCodes.Blt_Un_S) && instr.Operand is ILLabel iLLabel) { value = iLLabel; return true; } value = null; return false; } public static bool MatchBltUn(this Instruction instr, ILLabel value) { if (instr.MatchBltUn(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBltUn(this Instruction instr, Instruction value) { if (instr.MatchBltUn(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBneUn(this Instruction instr, [MaybeNullWhen(false)] out ILLabel value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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_0022: Unknown result type (might be due to invalid IL or missing references) if ((Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Bne_Un || instr.OpCode == OpCodes.Bne_Un_S) && instr.Operand is ILLabel iLLabel) { value = iLLabel; return true; } value = null; return false; } public static bool MatchBneUn(this Instruction instr, ILLabel value) { if (instr.MatchBneUn(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBneUn(this Instruction instr, Instruction value) { if (instr.MatchBneUn(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBox(this Instruction instr, [MaybeNullWhen(false)] out TypeReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Box) { object operand = instr.Operand; TypeReference val = (TypeReference)((operand is TypeReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchBox(this Instruction instr, TypeReference value) { if (instr.MatchBox(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBox(this Instruction instr, Type value) { if (instr.MatchBox(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBox(this Instruction instr) { return instr.MatchBox(typeof(T)); } public static bool MatchBox(this Instruction instr, string typeFullName) { if (instr.MatchBox(out TypeReference value)) { return ((MemberReference)(object)value).Is(typeFullName); } return false; } public static bool MatchBr(this Instruction instr, [MaybeNullWhen(false)] out ILLabel value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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_0022: Unknown result type (might be due to invalid IL or missing references) if ((Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Br || instr.OpCode == OpCodes.Br_S) && instr.Operand is ILLabel iLLabel) { value = iLLabel; return true; } value = null; return false; } public static bool MatchBr(this Instruction instr, ILLabel value) { if (instr.MatchBr(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBr(this Instruction instr, Instruction value) { if (instr.MatchBr(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBreak(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Break; } public static bool MatchBrfalse(this Instruction instr, [MaybeNullWhen(false)] out ILLabel value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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_0022: Unknown result type (might be due to invalid IL or missing references) if ((Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Brfalse || instr.OpCode == OpCodes.Brfalse_S) && instr.Operand is ILLabel iLLabel) { value = iLLabel; return true; } value = null; return false; } public static bool MatchBrfalse(this Instruction instr, ILLabel value) { if (instr.MatchBrfalse(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBrfalse(this Instruction instr, Instruction value) { if (instr.MatchBrfalse(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBrtrue(this Instruction instr, [MaybeNullWhen(false)] out ILLabel value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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_0022: Unknown result type (might be due to invalid IL or missing references) if ((Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Brtrue || instr.OpCode == OpCodes.Brtrue_S) && instr.Operand is ILLabel iLLabel) { value = iLLabel; return true; } value = null; return false; } public static bool MatchBrtrue(this Instruction instr, ILLabel value) { if (instr.MatchBrtrue(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchBrtrue(this Instruction instr, Instruction value) { if (instr.MatchBrtrue(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchCall(this Instruction instr, [MaybeNullWhen(false)] out MethodReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Call) { object operand = instr.Operand; MethodReference val = (MethodReference)((operand is MethodReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchCall(this Instruction instr, MethodReference value) { if (instr.MatchCall(out MethodReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchCall(this Instruction instr, MethodBase value) { if (instr.MatchCall(out MethodReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchCall(this Instruction instr, Type type, string name) { if (instr.MatchCall(out MethodReference value)) { return IsEquivalent(value, type, name); } return false; } public static bool MatchCall(this Instruction instr, string name) { return instr.MatchCall(typeof(T), name); } public static bool MatchCall(this Instruction instr, string typeFullName, string name) { if (instr.MatchCall(out MethodReference value)) { return value.Is(typeFullName, name); } return false; } public static bool MatchCalli(this Instruction instr, [MaybeNullWhen(false)] out IMethodSignature value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Calli) { object operand = instr.Operand; IMethodSignature val = (IMethodSignature)((operand is IMethodSignature) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchCalli(this Instruction instr, IMethodSignature value) { if (instr.MatchCalli(out IMethodSignature value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchCallvirt(this Instruction instr, [MaybeNullWhen(false)] out MethodReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Callvirt) { object operand = instr.Operand; MethodReference val = (MethodReference)((operand is MethodReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchCallvirt(this Instruction instr, MethodReference value) { if (instr.MatchCallvirt(out MethodReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchCallvirt(this Instruction instr, MethodBase value) { if (instr.MatchCallvirt(out MethodReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchCallvirt(this Instruction instr, Type type, string name) { if (instr.MatchCallvirt(out MethodReference value)) { return IsEquivalent(value, type, name); } return false; } public static bool MatchCallvirt(this Instruction instr, string name) { return instr.MatchCallvirt(typeof(T), name); } public static bool MatchCallvirt(this Instruction instr, string typeFullName, string name) { if (instr.MatchCallvirt(out MethodReference value)) { return value.Is(typeFullName, name); } return false; } public static bool MatchCallOrCallvirt(this Instruction instr, MethodReference value) { if (instr.MatchCallOrCallvirt(out MethodReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchCallOrCallvirt(this Instruction instr, MethodBase value) { if (instr.MatchCallOrCallvirt(out MethodReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchCallOrCallvirt(this Instruction instr, Type type, string name) { if (instr.MatchCallOrCallvirt(out MethodReference value)) { return IsEquivalent(value, type, name); } return false; } public static bool MatchCallOrCallvirt(this Instruction instr, string name) { return instr.MatchCallOrCallvirt(typeof(T), name); } public static bool MatchCallOrCallvirt(this Instruction instr, string typeFullName, string name) { if (instr.MatchCallOrCallvirt(out MethodReference value)) { return value.Is(typeFullName, name); } return false; } public static bool MatchCastclass(this Instruction instr, [MaybeNullWhen(false)] out TypeReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Castclass) { object operand = instr.Operand; TypeReference val = (TypeReference)((operand is TypeReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchCastclass(this Instruction instr, TypeReference value) { if (instr.MatchCastclass(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchCastclass(this Instruction instr, Type value) { if (instr.MatchCastclass(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchCastclass(this Instruction instr) { return instr.MatchCastclass(typeof(T)); } public static bool MatchCastclass(this Instruction instr, string typeFullName) { if (instr.MatchCastclass(out TypeReference value)) { return ((MemberReference)(object)value).Is(typeFullName); } return false; } public static bool MatchCeq(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ceq; } public static bool MatchCgt(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Cgt; } public static bool MatchCgtUn(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Cgt_Un; } public static bool MatchCkfinite(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ckfinite; } public static bool MatchClt(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Clt; } public static bool MatchCltUn(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Clt_Un; } public static bool MatchConstrained(this Instruction instr, [MaybeNullWhen(false)] out TypeReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Constrained) { object operand = instr.Operand; TypeReference val = (TypeReference)((operand is TypeReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchConstrained(this Instruction instr, TypeReference value) { if (instr.MatchConstrained(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchConstrained(this Instruction instr, Type value) { if (instr.MatchConstrained(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchConstrained(this Instruction instr) { return instr.MatchConstrained(typeof(T)); } public static bool MatchConstrained(this Instruction instr, string typeFullName) { if (instr.MatchConstrained(out TypeReference value)) { return ((MemberReference)(object)value).Is(typeFullName); } return false; } public static bool MatchConvI(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_I; } public static bool MatchConvI1(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_I1; } public static bool MatchConvI2(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_I2; } public static bool MatchConvI4(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_I4; } public static bool MatchConvI8(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_I8; } public static bool MatchConvOvfI(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_I; } public static bool MatchConvOvfIUn(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_I_Un; } public static bool MatchConvOvfI1(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_I1; } public static bool MatchConvOvfI1Un(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_I1_Un; } public static bool MatchConvOvfI2(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_I2; } public static bool MatchConvOvfI2Un(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_I2_Un; } public static bool MatchConvOvfI4(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_I4; } public static bool MatchConvOvfI4Un(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_I4_Un; } public static bool MatchConvOvfI8(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_I8; } public static bool MatchConvOvfI8Un(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_I8_Un; } public static bool MatchConvOvfU(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_U; } public static bool MatchConvOvfUUn(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_U_Un; } public static bool MatchConvOvfU1(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_U1; } public static bool MatchConvOvfU1Un(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_U1_Un; } public static bool MatchConvOvfU2(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_U2; } public static bool MatchConvOvfU2Un(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_U2_Un; } public static bool MatchConvOvfU4(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_U4; } public static bool MatchConvOvfU4Un(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_U4_Un; } public static bool MatchConvOvfU8(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_U8; } public static bool MatchConvOvfU8Un(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_Ovf_U8_Un; } public static bool MatchConvRUn(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_R_Un; } public static bool MatchConvR4(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_R4; } public static bool MatchConvR8(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_R8; } public static bool MatchConvU(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_U; } public static bool MatchConvU1(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_U1; } public static bool MatchConvU2(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_U2; } public static bool MatchConvU4(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_U4; } public static bool MatchConvU8(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Conv_U8; } public static bool MatchCpblk(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Cpblk; } public static bool MatchCpobj(this Instruction instr, [MaybeNullWhen(false)] out TypeReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Cpobj) { object operand = instr.Operand; TypeReference val = (TypeReference)((operand is TypeReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchCpobj(this Instruction instr, TypeReference value) { if (instr.MatchCpobj(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchCpobj(this Instruction instr, Type value) { if (instr.MatchCpobj(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchCpobj(this Instruction instr) { return instr.MatchCpobj(typeof(T)); } public static bool MatchCpobj(this Instruction instr, string typeFullName) { if (instr.MatchCpobj(out TypeReference value)) { return ((MemberReference)(object)value).Is(typeFullName); } return false; } public static bool MatchDiv(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Div; } public static bool MatchDivUn(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Div_Un; } public static bool MatchDup(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Dup; } public static bool MatchEndfilter(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Endfilter; } public static bool MatchEndfinally(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Endfinally; } public static bool MatchInitblk(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Initblk; } public static bool MatchInitobj(this Instruction instr, [MaybeNullWhen(false)] out TypeReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Initobj) { object operand = instr.Operand; TypeReference val = (TypeReference)((operand is TypeReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchInitobj(this Instruction instr, TypeReference value) { if (instr.MatchInitobj(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchInitobj(this Instruction instr, Type value) { if (instr.MatchInitobj(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchInitobj(this Instruction instr) { return instr.MatchInitobj(typeof(T)); } public static bool MatchInitobj(this Instruction instr, string typeFullName) { if (instr.MatchInitobj(out TypeReference value)) { return ((MemberReference)(object)value).Is(typeFullName); } return false; } public static bool MatchIsinst(this Instruction instr, [MaybeNullWhen(false)] out TypeReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Isinst) { object operand = instr.Operand; TypeReference val = (TypeReference)((operand is TypeReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchIsinst(this Instruction instr, TypeReference value) { if (instr.MatchIsinst(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchIsinst(this Instruction instr, Type value) { if (instr.MatchIsinst(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchIsinst(this Instruction instr) { return instr.MatchIsinst(typeof(T)); } public static bool MatchIsinst(this Instruction instr, string typeFullName) { if (instr.MatchIsinst(out TypeReference value)) { return ((MemberReference)(object)value).Is(typeFullName); } return false; } public static bool MatchJmp(this Instruction instr, [MaybeNullWhen(false)] out MethodReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Jmp) { object operand = instr.Operand; MethodReference val = (MethodReference)((operand is MethodReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchJmp(this Instruction instr, MethodReference value) { if (instr.MatchJmp(out MethodReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchJmp(this Instruction instr, MethodBase value) { if (instr.MatchJmp(out MethodReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchJmp(this Instruction instr, Type type, string name) { if (instr.MatchJmp(out MethodReference value)) { return IsEquivalent(value, type, name); } return false; } public static bool MatchJmp(this Instruction instr, string name) { return instr.MatchJmp(typeof(T), name); } public static bool MatchJmp(this Instruction instr, string typeFullName, string name) { if (instr.MatchJmp(out MethodReference value)) { return value.Is(typeFullName, name); } return false; } public static bool MatchLdarg0(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldarg_0; } public static bool MatchLdarg1(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldarg_1; } public static bool MatchLdarg2(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldarg_2; } public static bool MatchLdarg3(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldarg_3; } public static bool MatchLdarg(this Instruction instr, int value) { if (instr.MatchLdarg(out var value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdarg(this Instruction instr, uint value) { if (instr.MatchLdarg(out var value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdarga(this Instruction instr, int value) { if (instr.MatchLdarga(out var value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdarga(this Instruction instr, uint value) { if (instr.MatchLdarga(out var value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdcI4(this Instruction instr, int value) { if (instr.MatchLdcI4(out var value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdcI4(this Instruction instr, uint value) { if (instr.MatchLdcI4(out var value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdcI8(this Instruction instr, [MaybeNullWhen(false)] out long value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldc_I8 && instr.Operand is long num) { value = num; return true; } value = 0L; return false; } public static bool MatchLdcI8(this Instruction instr, long value) { if (instr.MatchLdcI8(out var value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdcI8(this Instruction instr, ulong value) { if (instr.MatchLdcI8(out var value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdcR4(this Instruction instr, [MaybeNullWhen(false)] out float value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldc_R4 && instr.Operand is float num) { value = num; return true; } value = 0f; return false; } public static bool MatchLdcR4(this Instruction instr, float value) { if (instr.MatchLdcR4(out var value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdcR8(this Instruction instr, [MaybeNullWhen(false)] out double value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldc_R8 && instr.Operand is double num) { value = num; return true; } value = 0.0; return false; } public static bool MatchLdcR8(this Instruction instr, double value) { if (instr.MatchLdcR8(out var value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdelemAny(this Instruction instr, [MaybeNullWhen(false)] out TypeReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldelem_Any) { object operand = instr.Operand; TypeReference val = (TypeReference)((operand is TypeReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchLdelemAny(this Instruction instr, TypeReference value) { if (instr.MatchLdelemAny(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdelemAny(this Instruction instr, Type value) { if (instr.MatchLdelemAny(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdelemAny(this Instruction instr) { return instr.MatchLdelemAny(typeof(T)); } public static bool MatchLdelemAny(this Instruction instr, string typeFullName) { if (instr.MatchLdelemAny(out TypeReference value)) { return ((MemberReference)(object)value).Is(typeFullName); } return false; } public static bool MatchLdelemI(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldelem_I; } public static bool MatchLdelemI1(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldelem_I1; } public static bool MatchLdelemI2(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldelem_I2; } public static bool MatchLdelemI4(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldelem_I4; } public static bool MatchLdelemI8(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldelem_I8; } public static bool MatchLdelemR4(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldelem_R4; } public static bool MatchLdelemR8(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldelem_R8; } public static bool MatchLdelemRef(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldelem_Ref; } public static bool MatchLdelemU1(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldelem_U1; } public static bool MatchLdelemU2(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldelem_U2; } public static bool MatchLdelemU4(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldelem_U4; } public static bool MatchLdelema(this Instruction instr, [MaybeNullWhen(false)] out TypeReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldelema) { object operand = instr.Operand; TypeReference val = (TypeReference)((operand is TypeReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchLdelema(this Instruction instr, TypeReference value) { if (instr.MatchLdelema(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdelema(this Instruction instr, Type value) { if (instr.MatchLdelema(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdelema(this Instruction instr) { return instr.MatchLdelema(typeof(T)); } public static bool MatchLdelema(this Instruction instr, string typeFullName) { if (instr.MatchLdelema(out TypeReference value)) { return ((MemberReference)(object)value).Is(typeFullName); } return false; } public static bool MatchLdfld(this Instruction instr, [MaybeNullWhen(false)] out FieldReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldfld) { object operand = instr.Operand; FieldReference val = (FieldReference)((operand is FieldReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchLdfld(this Instruction instr, FieldReference value) { if (instr.MatchLdfld(out FieldReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdfld(this Instruction instr, FieldInfo value) { if (instr.MatchLdfld(out FieldReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdfld(this Instruction instr, Type type, string name) { if (instr.MatchLdfld(out FieldReference value)) { return IsEquivalent(value, type, name); } return false; } public static bool MatchLdfld(this Instruction instr, string name) { return instr.MatchLdfld(typeof(T), name); } public static bool MatchLdfld(this Instruction instr, string typeFullName, string name) { if (instr.MatchLdfld(out FieldReference value)) { return ((MemberReference)(object)value).Is(typeFullName, name); } return false; } public static bool MatchLdflda(this Instruction instr, [MaybeNullWhen(false)] out FieldReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldflda) { object operand = instr.Operand; FieldReference val = (FieldReference)((operand is FieldReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchLdflda(this Instruction instr, FieldReference value) { if (instr.MatchLdflda(out FieldReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdflda(this Instruction instr, FieldInfo value) { if (instr.MatchLdflda(out FieldReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdflda(this Instruction instr, Type type, string name) { if (instr.MatchLdflda(out FieldReference value)) { return IsEquivalent(value, type, name); } return false; } public static bool MatchLdflda(this Instruction instr, string name) { return instr.MatchLdflda(typeof(T), name); } public static bool MatchLdflda(this Instruction instr, string typeFullName, string name) { if (instr.MatchLdflda(out FieldReference value)) { return ((MemberReference)(object)value).Is(typeFullName, name); } return false; } public static bool MatchLdftn(this Instruction instr, [MaybeNullWhen(false)] out MethodReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldftn) { object operand = instr.Operand; MethodReference val = (MethodReference)((operand is MethodReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchLdftn(this Instruction instr, MethodReference value) { if (instr.MatchLdftn(out MethodReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdftn(this Instruction instr, MethodBase value) { if (instr.MatchLdftn(out MethodReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdftn(this Instruction instr, Type type, string name) { if (instr.MatchLdftn(out MethodReference value)) { return IsEquivalent(value, type, name); } return false; } public static bool MatchLdftn(this Instruction instr, string name) { return instr.MatchLdftn(typeof(T), name); } public static bool MatchLdftn(this Instruction instr, string typeFullName, string name) { if (instr.MatchLdftn(out MethodReference value)) { return value.Is(typeFullName, name); } return false; } public static bool MatchLdindI(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldind_I; } public static bool MatchLdindI1(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldind_I1; } public static bool MatchLdindI2(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldind_I2; } public static bool MatchLdindI4(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldind_I4; } public static bool MatchLdindI8(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldind_I8; } public static bool MatchLdindR4(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldind_R4; } public static bool MatchLdindR8(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldind_R8; } public static bool MatchLdindRef(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldind_Ref; } public static bool MatchLdindU1(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldind_U1; } public static bool MatchLdindU2(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldind_U2; } public static bool MatchLdindU4(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldind_U4; } public static bool MatchLdlen(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldlen; } public static bool MatchLdloc0(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldloc_0; } public static bool MatchLdloc1(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldloc_1; } public static bool MatchLdloc2(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldloc_2; } public static bool MatchLdloc3(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldloc_3; } public static bool MatchLdloc(this Instruction instr, int value) { if (instr.MatchLdloc(out var value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdloc(this Instruction instr, uint value) { if (instr.MatchLdloc(out var value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdloca(this Instruction instr, int value) { if (instr.MatchLdloca(out var value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdloca(this Instruction instr, uint value) { if (instr.MatchLdloca(out var value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdnull(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldnull; } public static bool MatchLdobj(this Instruction instr, [MaybeNullWhen(false)] out TypeReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldobj) { object operand = instr.Operand; TypeReference val = (TypeReference)((operand is TypeReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchLdobj(this Instruction instr, TypeReference value) { if (instr.MatchLdobj(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdobj(this Instruction instr, Type value) { if (instr.MatchLdobj(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdobj(this Instruction instr) { return instr.MatchLdobj(typeof(T)); } public static bool MatchLdobj(this Instruction instr, string typeFullName) { if (instr.MatchLdobj(out TypeReference value)) { return ((MemberReference)(object)value).Is(typeFullName); } return false; } public static bool MatchLdsfld(this Instruction instr, [MaybeNullWhen(false)] out FieldReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldsfld) { object operand = instr.Operand; FieldReference val = (FieldReference)((operand is FieldReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchLdsfld(this Instruction instr, FieldReference value) { if (instr.MatchLdsfld(out FieldReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdsfld(this Instruction instr, FieldInfo value) { if (instr.MatchLdsfld(out FieldReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdsfld(this Instruction instr, Type type, string name) { if (instr.MatchLdsfld(out FieldReference value)) { return IsEquivalent(value, type, name); } return false; } public static bool MatchLdsfld(this Instruction instr, string name) { return instr.MatchLdsfld(typeof(T), name); } public static bool MatchLdsfld(this Instruction instr, string typeFullName, string name) { if (instr.MatchLdsfld(out FieldReference value)) { return ((MemberReference)(object)value).Is(typeFullName, name); } return false; } public static bool MatchLdsflda(this Instruction instr, [MaybeNullWhen(false)] out FieldReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldsflda) { object operand = instr.Operand; FieldReference val = (FieldReference)((operand is FieldReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchLdsflda(this Instruction instr, FieldReference value) { if (instr.MatchLdsflda(out FieldReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdsflda(this Instruction instr, FieldInfo value) { if (instr.MatchLdsflda(out FieldReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdsflda(this Instruction instr, Type type, string name) { if (instr.MatchLdsflda(out FieldReference value)) { return IsEquivalent(value, type, name); } return false; } public static bool MatchLdsflda(this Instruction instr, string name) { return instr.MatchLdsflda(typeof(T), name); } public static bool MatchLdsflda(this Instruction instr, string typeFullName, string name) { if (instr.MatchLdsflda(out FieldReference value)) { return ((MemberReference)(object)value).Is(typeFullName, name); } return false; } public static bool MatchLdstr(this Instruction instr, [MaybeNullWhen(false)] out string value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldstr && instr.Operand is string text) { value = text; return true; } value = null; return false; } public static bool MatchLdstr(this Instruction instr, string value) { if (instr.MatchLdstr(out string value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdtoken(this Instruction instr, [MaybeNullWhen(false)] out IMetadataTokenProvider value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldtoken) { object operand = instr.Operand; IMetadataTokenProvider val = (IMetadataTokenProvider)((operand is IMetadataTokenProvider) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchLdtoken(this Instruction instr, IMetadataTokenProvider value) { if (instr.MatchLdtoken(out IMetadataTokenProvider value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdtoken(this Instruction instr, Type value) { if (instr.MatchLdtoken(out IMetadataTokenProvider value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdtoken(this Instruction instr) { return instr.MatchLdtoken(typeof(T)); } public static bool MatchLdtoken(this Instruction instr, FieldInfo value) { if (instr.MatchLdtoken(out IMetadataTokenProvider value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdtoken(this Instruction instr, MethodBase value) { if (instr.MatchLdtoken(out IMetadataTokenProvider value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdvirtftn(this Instruction instr, [MaybeNullWhen(false)] out MethodReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ldvirtftn) { object operand = instr.Operand; MethodReference val = (MethodReference)((operand is MethodReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchLdvirtftn(this Instruction instr, MethodReference value) { if (instr.MatchLdvirtftn(out MethodReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdvirtftn(this Instruction instr, MethodBase value) { if (instr.MatchLdvirtftn(out MethodReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLdvirtftn(this Instruction instr, Type type, string name) { if (instr.MatchLdvirtftn(out MethodReference value)) { return IsEquivalent(value, type, name); } return false; } public static bool MatchLdvirtftn(this Instruction instr, string name) { return instr.MatchLdvirtftn(typeof(T), name); } public static bool MatchLdvirtftn(this Instruction instr, string typeFullName, string name) { if (instr.MatchLdvirtftn(out MethodReference value)) { return value.Is(typeFullName, name); } return false; } public static bool MatchLeave(this Instruction instr, [MaybeNullWhen(false)] out ILLabel value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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_0022: Unknown result type (might be due to invalid IL or missing references) if ((Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Leave || instr.OpCode == OpCodes.Leave_S) && instr.Operand is ILLabel iLLabel) { value = iLLabel; return true; } value = null; return false; } public static bool MatchLeave(this Instruction instr, ILLabel value) { if (instr.MatchLeave(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLeave(this Instruction instr, Instruction value) { if (instr.MatchLeave(out ILLabel value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchLocalloc(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Localloc; } public static bool MatchMkrefany(this Instruction instr, [MaybeNullWhen(false)] out TypeReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Mkrefany) { object operand = instr.Operand; TypeReference val = (TypeReference)((operand is TypeReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchMkrefany(this Instruction instr, TypeReference value) { if (instr.MatchMkrefany(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchMkrefany(this Instruction instr, Type value) { if (instr.MatchMkrefany(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchMkrefany(this Instruction instr) { return instr.MatchMkrefany(typeof(T)); } public static bool MatchMkrefany(this Instruction instr, string typeFullName) { if (instr.MatchMkrefany(out TypeReference value)) { return ((MemberReference)(object)value).Is(typeFullName); } return false; } public static bool MatchMul(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Mul; } public static bool MatchMulOvf(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Mul_Ovf; } public static bool MatchMulOvfUn(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Mul_Ovf_Un; } public static bool MatchNeg(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Neg; } public static bool MatchNewarr(this Instruction instr, [MaybeNullWhen(false)] out TypeReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Newarr) { object operand = instr.Operand; TypeReference val = (TypeReference)((operand is TypeReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchNewarr(this Instruction instr, TypeReference value) { if (instr.MatchNewarr(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchNewarr(this Instruction instr, Type value) { if (instr.MatchNewarr(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchNewarr(this Instruction instr) { return instr.MatchNewarr(typeof(T)); } public static bool MatchNewarr(this Instruction instr, string typeFullName) { if (instr.MatchNewarr(out TypeReference value)) { return ((MemberReference)(object)value).Is(typeFullName); } return false; } public static bool MatchNewobj(this Instruction instr, [MaybeNullWhen(false)] out MethodReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Newobj) { object operand = instr.Operand; MethodReference val = (MethodReference)((operand is MethodReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchNewobj(this Instruction instr, MethodReference value) { if (instr.MatchNewobj(out MethodReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchNewobj(this Instruction instr, MethodBase value) { if (instr.MatchNewobj(out MethodReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchNewobj(this Instruction instr, Type type, string name) { if (instr.MatchNewobj(out MethodReference value)) { return IsEquivalent(value, type, name); } return false; } public static bool MatchNewobj(this Instruction instr, string name) { return instr.MatchNewobj(typeof(T), name); } public static bool MatchNewobj(this Instruction instr, string typeFullName, string name) { if (instr.MatchNewobj(out MethodReference value)) { return value.Is(typeFullName, name); } return false; } public static bool MatchNop(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Nop; } public static bool MatchNot(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Not; } public static bool MatchOr(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Or; } public static bool MatchPop(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Pop; } public static bool MatchReadonly(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Readonly; } public static bool MatchRefanytype(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Refanytype; } public static bool MatchRefanyval(this Instruction instr, [MaybeNullWhen(false)] out TypeReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Refanyval) { object operand = instr.Operand; TypeReference val = (TypeReference)((operand is TypeReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchRefanyval(this Instruction instr, TypeReference value) { if (instr.MatchRefanyval(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchRefanyval(this Instruction instr, Type value) { if (instr.MatchRefanyval(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchRefanyval(this Instruction instr) { return instr.MatchRefanyval(typeof(T)); } public static bool MatchRefanyval(this Instruction instr, string typeFullName) { if (instr.MatchRefanyval(out TypeReference value)) { return ((MemberReference)(object)value).Is(typeFullName); } return false; } public static bool MatchRem(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Rem; } public static bool MatchRemUn(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Rem_Un; } public static bool MatchRet(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Ret; } public static bool MatchRethrow(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Rethrow; } public static bool MatchShl(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Shl; } public static bool MatchShr(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Shr; } public static bool MatchShrUn(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Shr_Un; } public static bool MatchSizeof(this Instruction instr, [MaybeNullWhen(false)] out TypeReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Sizeof) { object operand = instr.Operand; TypeReference val = (TypeReference)((operand is TypeReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchSizeof(this Instruction instr, TypeReference value) { if (instr.MatchSizeof(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchSizeof(this Instruction instr, Type value) { if (instr.MatchSizeof(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchSizeof(this Instruction instr) { return instr.MatchSizeof(typeof(T)); } public static bool MatchSizeof(this Instruction instr, string typeFullName) { if (instr.MatchSizeof(out TypeReference value)) { return ((MemberReference)(object)value).Is(typeFullName); } return false; } public static bool MatchStarg(this Instruction instr, int value) { if (instr.MatchStarg(out var value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchStarg(this Instruction instr, uint value) { if (instr.MatchStarg(out var value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchStelemAny(this Instruction instr, [MaybeNullWhen(false)] out TypeReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stelem_Any) { object operand = instr.Operand; TypeReference val = (TypeReference)((operand is TypeReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchStelemAny(this Instruction instr, TypeReference value) { if (instr.MatchStelemAny(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchStelemAny(this Instruction instr, Type value) { if (instr.MatchStelemAny(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchStelemAny(this Instruction instr) { return instr.MatchStelemAny(typeof(T)); } public static bool MatchStelemAny(this Instruction instr, string typeFullName) { if (instr.MatchStelemAny(out TypeReference value)) { return ((MemberReference)(object)value).Is(typeFullName); } return false; } public static bool MatchStelemI(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stelem_I; } public static bool MatchStelemI1(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stelem_I1; } public static bool MatchStelemI2(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stelem_I2; } public static bool MatchStelemI4(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stelem_I4; } public static bool MatchStelemI8(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stelem_I8; } public static bool MatchStelemR4(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stelem_R4; } public static bool MatchStelemR8(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stelem_R8; } public static bool MatchStelemRef(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stelem_Ref; } public static bool MatchStfld(this Instruction instr, [MaybeNullWhen(false)] out FieldReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stfld) { object operand = instr.Operand; FieldReference val = (FieldReference)((operand is FieldReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchStfld(this Instruction instr, FieldReference value) { if (instr.MatchStfld(out FieldReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchStfld(this Instruction instr, FieldInfo value) { if (instr.MatchStfld(out FieldReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchStfld(this Instruction instr, Type type, string name) { if (instr.MatchStfld(out FieldReference value)) { return IsEquivalent(value, type, name); } return false; } public static bool MatchStfld(this Instruction instr, string name) { return instr.MatchStfld(typeof(T), name); } public static bool MatchStfld(this Instruction instr, string typeFullName, string name) { if (instr.MatchStfld(out FieldReference value)) { return ((MemberReference)(object)value).Is(typeFullName, name); } return false; } public static bool MatchStindI(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stind_I; } public static bool MatchStindI1(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stind_I1; } public static bool MatchStindI2(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stind_I2; } public static bool MatchStindI4(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stind_I4; } public static bool MatchStindI8(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stind_I8; } public static bool MatchStindR4(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stind_R4; } public static bool MatchStindR8(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stind_R8; } public static bool MatchStindRef(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stind_Ref; } public static bool MatchStloc0(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stloc_0; } public static bool MatchStloc1(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stloc_1; } public static bool MatchStloc2(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stloc_2; } public static bool MatchStloc3(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stloc_3; } public static bool MatchStloc(this Instruction instr, int value) { if (instr.MatchStloc(out var value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchStloc(this Instruction instr, uint value) { if (instr.MatchStloc(out var value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchStobj(this Instruction instr, [MaybeNullWhen(false)] out TypeReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stobj) { object operand = instr.Operand; TypeReference val = (TypeReference)((operand is TypeReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchStobj(this Instruction instr, TypeReference value) { if (instr.MatchStobj(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchStobj(this Instruction instr, Type value) { if (instr.MatchStobj(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchStobj(this Instruction instr) { return instr.MatchStobj(typeof(T)); } public static bool MatchStobj(this Instruction instr, string typeFullName) { if (instr.MatchStobj(out TypeReference value)) { return ((MemberReference)(object)value).Is(typeFullName); } return false; } public static bool MatchStsfld(this Instruction instr, [MaybeNullWhen(false)] out FieldReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Stsfld) { object operand = instr.Operand; FieldReference val = (FieldReference)((operand is FieldReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchStsfld(this Instruction instr, FieldReference value) { if (instr.MatchStsfld(out FieldReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchStsfld(this Instruction instr, FieldInfo value) { if (instr.MatchStsfld(out FieldReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchStsfld(this Instruction instr, Type type, string name) { if (instr.MatchStsfld(out FieldReference value)) { return IsEquivalent(value, type, name); } return false; } public static bool MatchStsfld(this Instruction instr, string name) { return instr.MatchStsfld(typeof(T), name); } public static bool MatchStsfld(this Instruction instr, string typeFullName, string name) { if (instr.MatchStsfld(out FieldReference value)) { return ((MemberReference)(object)value).Is(typeFullName, name); } return false; } public static bool MatchSub(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Sub; } public static bool MatchSubOvf(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Sub_Ovf; } public static bool MatchSubOvfUn(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Sub_Ovf_Un; } public static bool MatchSwitch(this Instruction instr, [MaybeNullWhen(false)] out ILLabel[] value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Switch && instr.Operand is ILLabel[] array) { value = array; return true; } value = null; return false; } public static bool MatchSwitch(this Instruction instr, ILLabel[] value) { if (instr.MatchSwitch(out ILLabel[] value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchSwitch(this Instruction instr, Instruction[] value) { if (instr.MatchSwitch(out ILLabel[] value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchTail(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Tail; } public static bool MatchThrow(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Throw; } public static bool MatchUnaligned(this Instruction instr, [MaybeNullWhen(false)] out byte value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Unaligned && instr.Operand is byte b) { value = b; return true; } value = 0; return false; } public static bool MatchUnaligned(this Instruction instr, byte value) { if (instr.MatchUnaligned(out var value2)) { return IsEquivalent((int)value2, (int)value); } return false; } public static bool MatchUnbox(this Instruction instr, [MaybeNullWhen(false)] out TypeReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Unbox) { object operand = instr.Operand; TypeReference val = (TypeReference)((operand is TypeReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchUnbox(this Instruction instr, TypeReference value) { if (instr.MatchUnbox(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchUnbox(this Instruction instr, Type value) { if (instr.MatchUnbox(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchUnbox(this Instruction instr) { return instr.MatchUnbox(typeof(T)); } public static bool MatchUnbox(this Instruction instr, string typeFullName) { if (instr.MatchUnbox(out TypeReference value)) { return ((MemberReference)(object)value).Is(typeFullName); } return false; } public static bool MatchUnboxAny(this Instruction instr, [MaybeNullWhen(false)] out TypeReference value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Unbox_Any) { object operand = instr.Operand; TypeReference val = (TypeReference)((operand is TypeReference) ? operand : null); if (val != null) { value = val; return true; } } value = null; return false; } public static bool MatchUnboxAny(this Instruction instr, TypeReference value) { if (instr.MatchUnboxAny(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchUnboxAny(this Instruction instr, Type value) { if (instr.MatchUnboxAny(out TypeReference value2)) { return IsEquivalent(value2, value); } return false; } public static bool MatchUnboxAny(this Instruction instr) { return instr.MatchUnboxAny(typeof(T)); } public static bool MatchUnboxAny(this Instruction instr, string typeFullName) { if (instr.MatchUnboxAny(out TypeReference value)) { return ((MemberReference)(object)value).Is(typeFullName); } return false; } public static bool MatchVolatile(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Volatile; } public static bool MatchXor(this Instruction instr) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(instr, "instr").OpCode == OpCodes.Xor; } } } namespace MonoMod.Utils { public enum ArchitectureKind { Unknown = 0, Bits64 = 1, x86 = 2, x86_64 = 3, AMD64 = 3, Arm = 4, Arm64 = 5 } public sealed class AssertionFailedException : Exception { private const string AssertFailed = "Assertion failed! "; public string Expression { get; } = ""; public new string Message { get; } public AssertionFailedException() { Message = ""; } public AssertionFailedException(string? message) : base("Assertion failed! " + message) { Message = message ?? ""; } public AssertionFailedException(string? message, Exception innerException) : base("Assertion failed! " + message, innerException) { Message = message ?? ""; } public AssertionFailedException(string? message, string expression) : base("Assertion failed! " + expression + " " + message) { Message = message ?? ""; Expression = expression; } } public enum CorelibKind { Framework, Core } public abstract class ScopeHandlerBase { public abstract void EndScope(object? data); } public readonly struct DataScope : IDisposable { private readonly ScopeHandlerBase? handler; private readonly object? data; public object? Data => data; public DataScope(ScopeHandlerBase handler, object? data) { this.handler = handler; this.data = data; } public void Dispose() { if (handler != null) { handler.EndScope(data); } } } public abstract class ScopeHandlerBase : ScopeHandlerBase { public sealed override void EndScope(object? data) { EndScope((T)data); } public abstract void EndScope(T data); } public readonly struct DataScope : IDisposable { private readonly ScopeHandlerBase? handler; private readonly T data; public T Data => data; public DataScope(ScopeHandlerBase handler, T data) { this.handler = handler; this.data = data; } public void Dispose() { if (handler != null) { handler.EndScope(data); } } } internal interface IDMDGenerator { MethodInfo Generate(DynamicMethodDefinition dmd, object? context); } public abstract class DMDGenerator : IDMDGenerator where TSelf : DMDGenerator, new() { private static TSelf? Instance; protected abstract MethodInfo GenerateCore(DynamicMethodDefinition dmd, object? context); MethodInfo IDMDGenerator.Generate(DynamicMethodDefinition dmd, object? context) { return Postbuild(GenerateCore(dmd, context)); } public static MethodInfo Generate(DynamicMethodDefinition dmd, object? context = null) { return Postbuild((Instance ?? (Instance = new TSelf())).GenerateCore(dmd, context)); } internal static MethodInfo Postbuild(MethodInfo mi) { if (PlatformDetection.Runtime == RuntimeKind.Mono && !(mi is DynamicMethod) && mi.DeclaringType != null) { Module module = mi.Module; if ((object)module == null) { return mi; } Assembly assembly = module.Assembly; if ((object)assembly.GetType() == null) { return mi; } assembly.SetMonoCorlibInternal(value: true); } return mi; } } public sealed class DMDCecilGenerator : DMDGenerator { protected override MethodInfo GenerateCore(DynamicMethodDefinition dmd, object? context) { //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) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Expected O, but got Unknown //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Expected O, but got Unknown //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_01cc: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Unknown result type (might be due to invalid IL or missing references) //IL_0224: 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_023a: 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_024c: Unknown result type (might be due to invalid IL or missing references) //IL_0253: Unknown result type (might be due to invalid IL or missing references) //IL_025f: Expected O, but got Unknown //IL_026a: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_0178: 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_0194: Expected O, but got Unknown //IL_033b: Unknown result type (might be due to invalid IL or missing references) //IL_0340: Unknown result type (might be due to invalid IL or missing references) //IL_038c: Unknown result type (might be due to invalid IL or missing references) //IL_0391: Unknown result type (might be due to invalid IL or missing references) //IL_0573: Unknown result type (might be due to invalid IL or missing references) //IL_057d: Expected O, but got Unknown //IL_054b: Unknown result type (might be due to invalid IL or missing references) //IL_0552: Expected O, but got Unknown //IL_04a1: Unknown result type (might be due to invalid IL or missing references) //IL_04a8: Expected O, but got Unknown //IL_04cb: Unknown result type (might be due to invalid IL or missing references) MethodDefinition def = dmd.Definition ?? throw new InvalidOperationException(); TypeDefinition val = (TypeDefinition)((context is TypeDefinition) ? context : null); bool flag = false; ModuleDefinition module = ((val != null) ? ((MemberReference)val).Module : null); HashSet hashSet = null; try { if (val == null || module == null) { flag = true; string dumpName = dmd.GetDumpName("Cecil"); module = ModuleDefinition.CreateModule(dumpName, new ModuleParameters { Kind = (ModuleKind)0, ReflectionImporterProvider = MMReflectionImporter.ProviderNoDefault }); hashSet = new HashSet(); module.Assembly.CustomAttributes.Add(new CustomAttribute(module.ImportReference((MethodBase)DynamicMethodDefinition.c_UnverifiableCodeAttribute))); if (dmd.Debug) { CustomAttribute val2 = new CustomAttribute(module.ImportReference((MethodBase)DynamicMethodDefinition.c_DebuggableAttribute)); val2.ConstructorArguments.Add(new CustomAttributeArgument(module.ImportReference(typeof(DebuggableAttribute.DebuggingModes)), (object)(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations))); module.Assembly.CustomAttributes.Add(val2); } val = new TypeDefinition("", $"DMD<{dmd.OriginalMethod?.Name?.Replace('.', '_')}>?{GetHashCode()}", (TypeAttributes)385) { BaseType = module.TypeSystem.Object }; module.Types.Add(val); } MethodDefinition clone = null; new TypeReference("System.Runtime.CompilerServices", "IsVolatile", module, module.TypeSystem.CoreLibrary); Relinker relinker = delegate(IMetadataTokenProvider mtp, IGenericParameterProvider? ctx) { if ((object)mtp == def) { return (IMetadataTokenProvider)(object)clone; } MethodReference val12 = (MethodReference)(object)((mtp is MethodReference) ? mtp : null); return (IMetadataTokenProvider)((val12 != null && ((MemberReference)val12).FullName == ((MemberReference)def).FullName && ((MemberReference)((MemberReference)val12).DeclaringType).FullName == ((MemberReference)def.DeclaringType).FullName && ((MemberReference)val12).DeclaringType.Scope.Name == ((TypeReference)def.DeclaringType).Scope.Name) ? ((object)clone) : ((object)module.ImportReference(mtp))); }; clone = new MethodDefinition(dmd.Name ?? ("_" + ((MemberReference)def).Name.Replace('.', '_')), def.Attributes, module.TypeSystem.Void) { MethodReturnType = ((MethodReference)def).MethodReturnType, Attributes = (MethodAttributes)150, ImplAttributes = (MethodImplAttributes)0, DeclaringType = val, NoInlining = true }; Enumerator enumerator = ((MethodReference)def).Parameters.GetEnumerator(); try { while (enumerator.MoveNext()) { ParameterDefinition current = enumerator.Current; ((MethodReference)clone).Parameters.Add(current.Clone().Relink(relinker, (IGenericParameterProvider)(object)clone)); } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } ((MethodReference)clone).ReturnType = ((MethodReference)def).ReturnType.Relink(relinker, (IGenericParameterProvider?)(object)clone); val.Methods.Add(clone); ((MethodReference)clone).HasThis = ((MethodReference)def).HasThis; MethodBody val3 = (clone.Body = def.Body.Clone(clone)); MethodBody val5 = val3; Enumerator enumerator2 = clone.Body.Variables.GetEnumerator(); try { while (enumerator2.MoveNext()) { VariableDefinition current2 = enumerator2.Current; ((VariableReference)current2).VariableType = ((VariableReference)current2).VariableType.Relink(relinker, (IGenericParameterProvider?)(object)clone); } } finally { ((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose(); } Enumerator enumerator3 = clone.Body.ExceptionHandlers.GetEnumerator(); try { while (enumerator3.MoveNext()) { ExceptionHandler current3 = enumerator3.Current; if (current3.CatchType != null) { current3.CatchType = current3.CatchType.Relink(relinker, (IGenericParameterProvider?)(object)clone); } } } finally { ((IDisposable)enumerator3/*cast due to .constrained prefix*/).Dispose(); } for (int num = 0; num < val5.Instructions.Count; num++) { Instruction obj = val5.Instructions[num]; object obj2 = obj.Operand; ParameterDefinition val6 = (ParameterDefinition)((obj2 is ParameterDefinition) ? obj2 : null); if (val6 != null) { obj2 = ((MethodReference)clone).Parameters[((ParameterReference)val6).Index]; } else { IMetadataTokenProvider val7 = (IMetadataTokenProvider)((obj2 is IMetadataTokenProvider) ? obj2 : null); if (val7 != null) { obj2 = val7.Relink(relinker, (IGenericParameterProvider)(object)clone); } } _ = obj2 is DynamicMethodReference; if (hashSet != null) { MemberReference val8 = (MemberReference)((obj2 is MemberReference) ? obj2 : null); if (val8 != null) { MemberReference obj3 = ((val8 is TypeReference) ? val8 : null); IMetadataScope val9 = ((obj3 != null) ? ((TypeReference)obj3).Scope : null) ?? val8.DeclaringType.Scope; if (!hashSet.Contains(val9.Name)) { CustomAttribute val10 = new CustomAttribute(module.ImportReference((MethodBase)DynamicMethodDefinition.c_IgnoresAccessChecksToAttribute)); val10.ConstructorArguments.Add(new CustomAttributeArgument(module.ImportReference(typeof(DebuggableAttribute.DebuggingModes)), (object)val9.Name)); module.Assembly.CustomAttributes.Add(val10); hashSet.Add(val9.Name); } } } obj.Operand = obj2; } ((MethodReference)clone).HasThis = false; if (((MethodReference)def).HasThis) { TypeReference val11 = (TypeReference)(object)def.DeclaringType; if (val11.IsValueType) { val11 = (TypeReference)new ByReferenceType(val11); } ((MethodReference)clone).Parameters.Insert(0, new ParameterDefinition("<>_this", (ParameterAttributes)0, val11.Relink(relinker, (IGenericParameterProvider?)(object)clone))); } object value; string text = (Switches.TryGetSwitchValue("DMDDumpTo", out value) ? (value as string) : null); if (!string.IsNullOrEmpty(text)) { string fullPath = Path.GetFullPath(text); string path = ((ModuleReference)module).Name + ".dll"; string path2 = Path.Combine(fullPath, path); fullPath = Path.GetDirectoryName(path2); if (!string.IsNullOrEmpty(fullPath) && !Directory.Exists(fullPath)) { Directory.CreateDirectory(fullPath); } if (File.Exists(path2)) { File.Delete(path2); } using Stream stream = File.OpenWrite(path2); module.Write(stream); } return ReflectionHelper.Load(module).GetType(((MemberReference)val).FullName.Replace("+", "\\+", StringComparison.Ordinal), throwOnError: false, ignoreCase: false).GetMethod(((MemberReference)clone).Name, BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ?? throw new InvalidOperationException("Could not find generated method"); } finally { if (flag) { module.Dispose(); } module = null; } } } internal static class _DMDEmit { private abstract class TokenCreator { public abstract int GetTokenForType(Type type); public abstract int GetTokenForSig(byte[] sig); } private sealed class NetTokenCreator : TokenCreator { private readonly List tokens; public NetTokenCreator(ILGenerator il) { Helpers.Assert((object)f_DynScope_m_tokens != null, null, "f_DynScope_m_tokens is not null"); Helpers.Assert((object)f_DynILGen_m_scope != null, null, "f_DynILGen_m_scope is not null"); List list = (List)f_DynScope_m_tokens.GetValue(f_DynILGen_m_scope.GetValue(il)); Helpers.Assert(list != null, "DynamicMethod object list is null!", "list is not null"); tokens = list; } public override int GetTokenForType(Type type) { tokens.Add(type.TypeHandle); return (tokens.Count - 1) | 0x2000000; } public override int GetTokenForSig(byte[] sig) { tokens.Add(sig); return (tokens.Count - 1) | 0x11000000; } } private sealed class MonoTokenCreator : TokenCreator { private readonly DynamicMethod dm; private readonly Func addRef; public MonoTokenCreator(DynamicMethod dm) { Helpers.Assert(DynamicMethod_AddRef != null, null, "DynamicMethod_AddRef is not null"); addRef = DynamicMethod_AddRef; this.dm = dm; } public override int GetTokenForType(Type type) { return addRef(dm, type); } public override int GetTokenForSig(byte[] sig) { return addRef(dm, sig); } } private abstract class CallSiteEmitter { public abstract void EmitCallSite(DynamicMethod dm, ILGenerator il, OpCode opcode, CallSite csite); } private sealed class NetCallSiteEmitter : CallSiteEmitter { public override void EmitCallSite(DynamicMethod dm, ILGenerator il, OpCode opcode, CallSite csite) { //IL_0036: 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_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Expected I4, but got Unknown //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) TokenCreator tokenCreator = ((DynamicMethod_AddRef != null) ? ((TokenCreator)new MonoTokenCreator(dm)) : ((TokenCreator)new NetTokenCreator(il))); byte[] signature = new byte[32]; int currSig = 0; int num = -1; AddData(csite.CallingConvention | (csite.HasThis ? 32 : 0) | (csite.ExplicitThis ? 64 : 0)); num = currSig++; List modReq = new List(); List modOpt = new List(); ResolveWithModifiers(csite.ReturnType, out Type type, out Type[] typeModReq, out Type[] typeModOpt, modReq, modOpt); AddArgument(type, typeModReq, typeModOpt); Enumerator enumerator = csite.Parameters.GetEnumerator(); try { while (enumerator.MoveNext()) { ParameterDefinition current = enumerator.Current; if (((ParameterReference)current).ParameterType.IsSentinel) { AddElementType(65); } if (((ParameterReference)current).ParameterType.IsPinned) { AddElementType(69); } ResolveWithModifiers(((ParameterReference)current).ParameterType, out Type type2, out Type[] typeModReq2, out Type[] typeModOpt2, modReq, modOpt); AddArgument(type2, typeModReq2, typeModOpt2); } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } AddElementType(0); int num2 = currSig; int num3 = ((csite.Parameters.Count < 128) ? 1 : ((csite.Parameters.Count >= 16384) ? 4 : 2)); byte[] array = new byte[currSig + num3 - 1]; array[0] = signature[0]; Buffer.BlockCopy(signature, num + 1, array, num + num3, num2 - (num + 1)); signature = array; currSig = num; AddData(csite.Parameters.Count); currSig = num2 + (num3 - 1); if (signature.Length > currSig) { array = new byte[currSig]; Array.Copy(signature, array, currSig); signature = array; } if (_ILGen_emit_int != null) { _ILGen_make_room.Invoke(il, new object[1] { 6 }); _ILGen_ll_emit.Invoke(il, new object[1] { opcode }); _ILGen_emit_int.Invoke(il, new object[1] { tokenCreator.GetTokenForSig(signature) }); return; } _ILGen_EnsureCapacity.Invoke(il, new object[1] { 7 }); _ILGen_InternalEmit.Invoke(il, new object[1] { opcode }); if (opcode.StackBehaviourPop == StackBehaviour.Varpop) { _ILGen_UpdateStackSize.Invoke(il, new object[2] { opcode, -csite.Parameters.Count - 1 }); } _ILGen_PutInteger4.Invoke(il, new object[1] { tokenCreator.GetTokenForSig(signature) }); void AddArgument(Type clsArgument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) { if (optionalCustomModifiers != null) { Type[] array2 = optionalCustomModifiers; foreach (Type type3 in array2) { InternalAddTypeToken(tokenCreator.GetTokenForType(type3), 32); } } if (requiredCustomModifiers != null) { Type[] array2 = requiredCustomModifiers; foreach (Type type4 in array2) { InternalAddTypeToken(tokenCreator.GetTokenForType(type4), 31); } } AddOneArgTypeHelper(clsArgument); } void AddData(int data) { if (currSig + 4 > signature.Length) { signature = ExpandArray(signature); } if (data <= 127) { signature[currSig++] = (byte)(data & 0xFF); } else if (data <= 16383) { signature[currSig++] = (byte)((data >> 8) | 0x80); signature[currSig++] = (byte)(data & 0xFF); } else { if (data > 536870911) { throw new ArgumentException("Integer or token was too large to be encoded."); } signature[currSig++] = (byte)((data >> 24) | 0xC0); signature[currSig++] = (byte)((data >> 16) & 0xFF); signature[currSig++] = (byte)((data >> 8) & 0xFF); signature[currSig++] = (byte)(data & 0xFF); } } void AddElementType(byte cvt) { if (currSig + 1 > signature.Length) { signature = ExpandArray(signature); } signature[currSig++] = cvt; } void AddOneArgTypeHelper(Type clsArgument) { AddOneArgTypeHelperWorker(clsArgument, lastWasGenericInst: false); } void AddOneArgTypeHelperWorker(Type clsArgument, bool lastWasGenericInst) { if (clsArgument.IsGenericType && (!clsArgument.IsGenericTypeDefinition || !lastWasGenericInst)) { AddElementType(21); AddOneArgTypeHelperWorker(clsArgument.GetGenericTypeDefinition(), lastWasGenericInst: true); Type[] genericArguments = clsArgument.GetGenericArguments(); AddData(genericArguments.Length); Type[] array2 = genericArguments; for (int i = 0; i < array2.Length; i++) { AddOneArgTypeHelper(array2[i]); } } else if (clsArgument.IsByRef) { AddElementType(16); clsArgument = clsArgument.GetElementType() ?? clsArgument; AddOneArgTypeHelper(clsArgument); } else if (clsArgument.IsPointer) { AddElementType(15); AddOneArgTypeHelper(clsArgument.GetElementType() ?? clsArgument); } else if (clsArgument.IsArray) { AddElementType(20); AddOneArgTypeHelper(clsArgument.GetElementType() ?? clsArgument); int arrayRank = clsArgument.GetArrayRank(); AddData(arrayRank); AddData(0); AddData(arrayRank); for (int j = 0; j < arrayRank; j++) { AddData(0); } } else { byte b = 0; for (int k = 0; k < CorElementTypes.Length; k++) { if (clsArgument == CorElementTypes[k]) { b = (byte)k; break; } } if (b == 0) { b = (byte)((clsArgument == typeof(object)) ? 28 : ((!clsArgument.IsValueType) ? 18 : 17)); } if (b <= 14 || b == 22 || b == 24 || b == 25 || b == 28) { AddElementType(b); } else { InternalAddRuntimeType(clsArgument); } } } void AddToken(int token) { int num4 = token & 0xFFFFFF; int num5 = token & -16777216; if (num4 > 67108863) { throw new ArgumentException("Integer or token was too large to be encoded."); } num4 <<= 2; switch (num5) { case 16777216: num4 |= 1; break; case 452984832: num4 |= 2; break; } AddData(num4); } static byte[] ExpandArray(byte[] inArray, int requiredLength = -1) { if (requiredLength < inArray.Length) { requiredLength = inArray.Length * 2; } byte[] array2 = new byte[requiredLength]; Buffer.BlockCopy(inArray, 0, array2, 0, inArray.Length); return array2; } unsafe void InternalAddRuntimeType(Type type3) { AddElementType(33); nint value = type3.TypeHandle.Value; if (currSig + sizeof(void*) > signature.Length) { signature = ExpandArray(signature); } byte* ptr = (byte*)(&value); for (int i = 0; i < sizeof(void*); i++) { signature[currSig++] = ptr[i]; } } void InternalAddTypeToken(int clsToken, byte CorType) { AddElementType(CorType); AddToken(clsToken); } } } private sealed class MonoCallSiteEmitter : CallSiteEmitter { private FieldInfo SigHelper_callConv; private FieldInfo SigHelper_unmanagedCallConv; private FieldInfo SigHelper_arguments; private FieldInfo SigHelper_modreqs; private FieldInfo SigHelper_modopts; public MonoCallSiteEmitter() { FieldInfo field = typeof(SignatureHelper).GetField("callConv", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field2 = typeof(SignatureHelper).GetField("unmanagedCallConv", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field3 = typeof(SignatureHelper).GetField("arguments", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field4 = typeof(SignatureHelper).GetField("modreqs", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field5 = typeof(SignatureHelper).GetField("modopts", BindingFlags.Instance | BindingFlags.NonPublic); Helpers.Assert((object)field != null, null, "callConv is not null"); Helpers.Assert((object)field2 != null, null, "unmanagedCallConv is not null"); Helpers.Assert((object)field3 != null, null, "arguments is not null"); Helpers.Assert((object)field4 != null, null, "modreqs is not null"); Helpers.Assert((object)field5 != null, null, "modopts is not null"); SigHelper_callConv = field; SigHelper_unmanagedCallConv = field2; SigHelper_arguments = field3; SigHelper_modreqs = field4; SigHelper_modopts = field5; } public override void EmitCallSite(DynamicMethod dm, ILGenerator il, OpCode opcode, CallSite csite) { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Invalid comparison between Unknown and I4 //IL_0099: 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_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Expected I4, but got Unknown List modReq = new List(); List modOpt = new List(); ResolveWithModifiers(csite.ReturnType, out Type type, out Type[] _, out Type[] _, modReq, modOpt); SignatureHelper methodSigHelper = SignatureHelper.GetMethodSigHelper(CallingConventions.Standard, type); Type[] array = new Type[csite.Parameters.Count]; Type[][] array2 = new Type[csite.Parameters.Count][]; Type[][] array3 = new Type[csite.Parameters.Count][]; CallingConventions callingConventions = (((int)csite.CallingConvention != 5) ? CallingConventions.Standard : CallingConventions.VarArgs); CallingConventions callingConventions2 = callingConventions; if (csite.HasThis) { callingConventions2 |= CallingConventions.HasThis; } if (csite.ExplicitThis) { callingConventions2 |= CallingConventions.ExplicitThis; } MethodCallingConvention callingConvention = csite.CallingConvention; CallingConvention callingConvention2 = (callingConvention - 1) switch { 0 => CallingConvention.Cdecl, 1 => CallingConvention.StdCall, 2 => CallingConvention.ThisCall, 3 => CallingConvention.FastCall, _ => (CallingConvention)0, }; for (int i = 0; i < csite.Parameters.Count; i++) { ResolveWithModifiers(((ParameterReference)csite.Parameters[i]).ParameterType, out array[i], out array2[i], out array3[i], modReq, modOpt); } SigHelper_callConv.SetValue(methodSigHelper, callingConventions2); SigHelper_unmanagedCallConv.SetValue(methodSigHelper, callingConvention2); SigHelper_arguments.SetValue(methodSigHelper, array); SigHelper_modreqs.SetValue(methodSigHelper, array2); SigHelper_modopts.SetValue(methodSigHelper, array3); _ILGen_make_room.Invoke(il, new object[1] { 6 }); _ILGen_ll_emit.Invoke(il, new object[1] { opcode }); _ILGen_emit_int.Invoke(il, new object[1] { DynamicMethod_AddRef(dm, methodSigHelper) }); } } private static readonly MethodInfo m_MethodBase_InvokeSimple; private static readonly Dictionary _ReflOpCodes; private static readonly Dictionary _CecilOpCodes; private static readonly MethodInfo? _ILGen_make_room; private static readonly MethodInfo? _ILGen_emit_int; private static readonly MethodInfo? _ILGen_ll_emit; private static readonly MethodInfo? mDynamicMethod_AddRef; private static readonly Func? DynamicMethod_AddRef; private static readonly Type? TRuntimeILGenerator; private static readonly MethodInfo? _ILGen_EnsureCapacity; private static readonly MethodInfo? _ILGen_PutInteger4; private static readonly MethodInfo? _ILGen_InternalEmit; private static readonly MethodInfo? _ILGen_UpdateStackSize; private static readonly FieldInfo? f_DynILGen_m_scope; private static readonly FieldInfo? f_DynScope_m_tokens; private static readonly Type?[] CorElementTypes; private static readonly CallSiteEmitter callSiteEmitter; private static MethodBuilder _CreateMethodProxy(MethodBuilder context, MethodInfo target) { TypeBuilder obj = (TypeBuilder)context.DeclaringType; string name = $".dmdproxy<{target.Name.Replace('.', '_')}>?{target.GetHashCode()}"; Type[] array = (from param in target.GetParameters() select param.ParameterType).ToArray(); MethodBuilder methodBuilder = obj.DefineMethod(name, MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.HideBySig, CallingConventions.Standard, target.ReturnType, array); ILGenerator iLGenerator = methodBuilder.GetILGenerator(); iLGenerator.EmitNewTypedReference(target, out var _); iLGenerator.Emit(OpCodes.Ldnull); iLGenerator.Emit(OpCodes.Ldc_I4, array.Length); iLGenerator.Emit(OpCodes.Newarr, typeof(object)); for (int num = 0; num < array.Length; num++) { iLGenerator.Emit(OpCodes.Dup); iLGenerator.Emit(OpCodes.Ldc_I4, num); iLGenerator.Emit(OpCodes.Ldarg, num); Type type = array[num]; if (type.IsByRef) { type = type.GetElementType() ?? type; } if (type.IsValueType) { iLGenerator.Emit(OpCodes.Box, type); } iLGenerator.Emit(OpCodes.Stelem_Ref); } iLGenerator.Emit(OpCodes.Callvirt, m_MethodBase_InvokeSimple); if (target.ReturnType == typeof(void)) { iLGenerator.Emit(OpCodes.Pop); } else if (target.ReturnType.IsValueType) { iLGenerator.Emit(OpCodes.Unbox_Any, target.ReturnType); } iLGenerator.Emit(OpCodes.Ret); return methodBuilder; } static _DMDEmit() { //IL_039f: Unknown result type (might be due to invalid IL or missing references) //IL_03a4: Unknown result type (might be due to invalid IL or missing references) //IL_03b1: Unknown result type (might be due to invalid IL or missing references) m_MethodBase_InvokeSimple = typeof(MethodBase).GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public, null, new Type[2] { typeof(object), typeof(object[]) }, null); _ReflOpCodes = new Dictionary(); _CecilOpCodes = new Dictionary(); _ILGen_make_room = typeof(ILGenerator).GetMethod("make_room", BindingFlags.Instance | BindingFlags.NonPublic); _ILGen_emit_int = typeof(ILGenerator).GetMethod("emit_int", BindingFlags.Instance | BindingFlags.NonPublic); _ILGen_ll_emit = typeof(ILGenerator).GetMethod("ll_emit", BindingFlags.Instance | BindingFlags.NonPublic); mDynamicMethod_AddRef = typeof(DynamicMethod).GetMethod("AddRef", BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[1] { typeof(object) }, null); DynamicMethod_AddRef = mDynamicMethod_AddRef?.CreateDelegate>(); TRuntimeILGenerator = Type.GetType("System.Reflection.Emit.RuntimeILGenerator"); _ILGen_EnsureCapacity = typeof(ILGenerator).GetMethod("EnsureCapacity", BindingFlags.Instance | BindingFlags.NonPublic) ?? TRuntimeILGenerator?.GetMethod("EnsureCapacity", BindingFlags.Instance | BindingFlags.NonPublic); _ILGen_PutInteger4 = typeof(ILGenerator).GetMethod("PutInteger4", BindingFlags.Instance | BindingFlags.NonPublic) ?? TRuntimeILGenerator?.GetMethod("PutInteger4", BindingFlags.Instance | BindingFlags.NonPublic); _ILGen_InternalEmit = typeof(ILGenerator).GetMethod("InternalEmit", BindingFlags.Instance | BindingFlags.NonPublic) ?? TRuntimeILGenerator?.GetMethod("InternalEmit", BindingFlags.Instance | BindingFlags.NonPublic); _ILGen_UpdateStackSize = typeof(ILGenerator).GetMethod("UpdateStackSize", BindingFlags.Instance | BindingFlags.NonPublic) ?? TRuntimeILGenerator?.GetMethod("UpdateStackSize", BindingFlags.Instance | BindingFlags.NonPublic); f_DynILGen_m_scope = typeof(ILGenerator).Assembly.GetType("System.Reflection.Emit.DynamicILGenerator")?.GetField("m_scope", BindingFlags.Instance | BindingFlags.NonPublic); f_DynScope_m_tokens = typeof(ILGenerator).Assembly.GetType("System.Reflection.Emit.DynamicScope")?.GetField("m_tokens", BindingFlags.Instance | BindingFlags.NonPublic); CorElementTypes = new Type[29] { null, typeof(void), typeof(bool), typeof(char), typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(float), typeof(double), typeof(string), null, null, null, null, null, null, null, null, null, typeof(nint), typeof(nuint), null, null, typeof(object) }; callSiteEmitter = ((DynamicMethod_AddRef != null) ? ((CallSiteEmitter)new MonoCallSiteEmitter()) : ((CallSiteEmitter)new NetCallSiteEmitter())); FieldInfo[] fields = typeof(OpCodes).GetFields(BindingFlags.Static | BindingFlags.Public); for (int i = 0; i < fields.Length; i++) { OpCode value = (OpCode)fields[i].GetValue(null); _ReflOpCodes[value.Value] = value; } fields = typeof(OpCodes).GetFields(BindingFlags.Static | BindingFlags.Public); for (int i = 0; i < fields.Length; i++) { OpCode value2 = (OpCode)fields[i].GetValue(null); _CecilOpCodes[((OpCode)(ref value2)).Value] = value2; } } public static void Generate(DynamicMethodDefinition dmd, MethodBase _mb, ILGenerator il) { //IL_00c4: 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_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_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Expected I4, but got Unknown //IL_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: Unknown result type (might be due to invalid IL or missing references) //IL_01e5: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_032b: Unknown result type (might be due to invalid IL or missing references) //IL_0330: Unknown result type (might be due to invalid IL or missing references) //IL_0334: Unknown result type (might be due to invalid IL or missing references) //IL_033a: Invalid comparison between Unknown and I4 //IL_0368: Unknown result type (might be due to invalid IL or missing references) //IL_036d: Unknown result type (might be due to invalid IL or missing references) //IL_0349: Unknown result type (might be due to invalid IL or missing references) //IL_034e: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Unknown result type (might be due to invalid IL or missing references) //IL_025a: Unknown result type (might be due to invalid IL or missing references) //IL_025c: Unknown result type (might be due to invalid IL or missing references) //IL_0277: Expected I4, but got Unknown //IL_02ca: Unknown result type (might be due to invalid IL or missing references) //IL_02cf: 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_02d4: Invalid comparison between Unknown and I4 //IL_03e3: Unknown result type (might be due to invalid IL or missing references) //IL_03e5: Unknown result type (might be due to invalid IL or missing references) //IL_03ea: Unknown result type (might be due to invalid IL or missing references) //IL_03b4: Unknown result type (might be due to invalid IL or missing references) //IL_03b6: Unknown result type (might be due to invalid IL or missing references) //IL_03bb: Unknown result type (might be due to invalid IL or missing references) //IL_0500: Unknown result type (might be due to invalid IL or missing references) //IL_0505: 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_02e4: Unknown result type (might be due to invalid IL or missing references) //IL_02d6: Unknown result type (might be due to invalid IL or missing references) //IL_02d9: Invalid comparison between Unknown and I4 //IL_02f7: Unknown result type (might be due to invalid IL or missing references) //IL_02fc: Unknown result type (might be due to invalid IL or missing references) MethodDefinition val = dmd.Definition ?? throw new InvalidOperationException(); DynamicMethod dynamicMethod = _mb as DynamicMethod; if (dmd.Debug) { _ = val.DebugInformation; } if (dynamicMethod != null) { Enumerator enumerator = ((MethodReference)val).Parameters.GetEnumerator(); try { while (enumerator.MoveNext()) { ParameterDefinition current = enumerator.Current; dynamicMethod.DefineParameter(((ParameterReference)current).Index + 1, (ParameterAttributes)current.Attributes, ((ParameterReference)current).Name); } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } } LocalBuilder[] array = ((IEnumerable)val.Body.Variables).Select((VariableDefinition var) => il.DeclareLocal(((VariableReference)var).VariableType.ResolveReflection(), var.IsPinned)).ToArray(); Dictionary labelMap = new Dictionary(); Enumerator enumerator2 = val.Body.Instructions.GetEnumerator(); try { while (enumerator2.MoveNext()) { Instruction current2 = enumerator2.Current; if (current2.Operand is Instruction[] array2) { Instruction[] array3 = array2; foreach (Instruction key in array3) { if (!labelMap.ContainsKey(key)) { labelMap[key] = il.DefineLabel(); } } } else { object operand = current2.Operand; Instruction val2 = (Instruction)((operand is Instruction) ? operand : null); if (val2 != null && !labelMap.ContainsKey(val2)) { labelMap[val2] = il.DefineLabel(); } } } } finally { ((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose(); } int num2 = (((MethodReference)val).HasThis ? 1 : 0); _ = new object[2]; bool flag = false; enumerator2 = val.Body.Instructions.GetEnumerator(); try { while (enumerator2.MoveNext()) { Instruction current3 = enumerator2.Current; if (labelMap.TryGetValue(current3, out var value)) { il.MarkLabel(value); } Enumerator enumerator3 = val.Body.ExceptionHandlers.GetEnumerator(); try { while (enumerator3.MoveNext()) { ExceptionHandler current4 = enumerator3.Current; if (flag && current4.HandlerEnd == current3) { il.EndExceptionBlock(); } ExceptionHandlerType handlerType; if (current4.TryStart == current3) { il.BeginExceptionBlock(); } else if (current4.FilterStart == current3) { il.BeginExceptFilterBlock(); } else if (current4.HandlerStart == current3) { handlerType = current4.HandlerType; switch ((int)handlerType) { case 1: il.BeginCatchBlock(null); break; case 0: il.BeginCatchBlock(current4.CatchType.ResolveReflection()); break; case 2: il.BeginFinallyBlock(); break; case 4: il.BeginFaultBlock(); break; } } if (current4.HandlerStart != current3.Next) { continue; } handlerType = current4.HandlerType; if ((int)handlerType != 1) { if ((int)handlerType != 2 || !(current3.OpCode == OpCodes.Endfinally)) { continue; } } else if (!(current3.OpCode == OpCodes.Endfilter)) { continue; } goto IL_0547; } } finally { ((IDisposable)enumerator3/*cast due to .constrained prefix*/).Dispose(); } OpCode opCode = current3.OpCode; if ((int)((OpCode)(ref opCode)).OperandType == 5) { ILGenerator iLGenerator = il; Dictionary reflOpCodes = _ReflOpCodes; opCode = current3.OpCode; iLGenerator.Emit(reflOpCodes[((OpCode)(ref opCode)).Value]); } else { OpCode op = current3.OpCode; object obj = current3.Operand; if (obj is Instruction[] source) { obj = source.Select((Instruction target) => labelMap[target]).ToArray(); op = op.ToLongOp(); } else { Instruction val3 = (Instruction)((obj is Instruction) ? obj : null); if (val3 != null) { obj = labelMap[val3]; op = op.ToLongOp(); } else { VariableDefinition val4 = (VariableDefinition)((obj is VariableDefinition) ? obj : null); if (val4 != null) { obj = array[((VariableReference)val4).Index]; } else { ParameterDefinition val5 = (ParameterDefinition)((obj is ParameterDefinition) ? obj : null); if (val5 != null) { obj = ((ParameterReference)val5).Index + num2; } else { MemberReference val6 = (MemberReference)((obj is MemberReference) ? obj : null); if (val6 != null) { obj = (((object)val6 == val) ? _mb : val6.ResolveReflection()); } else { CallSite val7 = (CallSite)((obj is CallSite) ? obj : null); if (val7 != null) { if (dynamicMethod != null) { _EmitCallSite(dynamicMethod, il, _ReflOpCodes[((OpCode)(ref op)).Value], val7); continue; } throw new NotSupportedException(); } } } } } } if (obj == null) { throw new InvalidOperationException($"Unexpected null in {val} @ {current3}"); } il.DynEmit(_ReflOpCodes[((OpCode)(ref op)).Value], obj); } if (!flag) { enumerator3 = val.Body.ExceptionHandlers.GetEnumerator(); try { while (enumerator3.MoveNext()) { if (enumerator3.Current.HandlerEnd == current3.Next) { il.EndExceptionBlock(); } } } finally { ((IDisposable)enumerator3/*cast due to .constrained prefix*/).Dispose(); } } flag = false; continue; IL_0547: flag = true; } } finally { ((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose(); } } public static void ResolveWithModifiers(TypeReference typeRef, out Type type, out Type[] typeModReq, out Type[] typeModOpt, List? modReq = null, List? modOpt = null) { if (modReq == null) { modReq = new List(); } else { modReq.Clear(); } if (modOpt == null) { modOpt = new List(); } else { modOpt.Clear(); } TypeReference val = typeRef; while (true) { TypeSpecification val2 = (TypeSpecification)(object)((val is TypeSpecification) ? val : null); if (val2 == null) { break; } RequiredModifierType val3 = (RequiredModifierType)(object)((val is RequiredModifierType) ? val : null); if (val3 == null) { OptionalModifierType val4 = (OptionalModifierType)(object)((val is OptionalModifierType) ? val : null); if (val4 != null) { modOpt.Add(val4.ModifierType.ResolveReflection()); } } else { modReq.Add(val3.ModifierType.ResolveReflection()); } val = val2.ElementType; } type = typeRef.ResolveReflection(); typeModReq = modReq.ToArray(); typeModOpt = modOpt.ToArray(); } internal static void _EmitCallSite(DynamicMethod dm, ILGenerator il, OpCode opcode, CallSite csite) { callSiteEmitter.EmitCallSite(dm, il, opcode, csite); } } public sealed class DMDEmitDynamicMethodGenerator : DMDGenerator { private static readonly FieldInfo _DynamicMethod_returnType = typeof(DynamicMethod).GetField("returnType", BindingFlags.Instance | BindingFlags.NonPublic) ?? typeof(DynamicMethod).GetField("_returnType", BindingFlags.Instance | BindingFlags.NonPublic) ?? typeof(DynamicMethod).GetField("m_returnType", BindingFlags.Instance | BindingFlags.NonPublic) ?? throw new InvalidOperationException("Cannot find returnType field on DynamicMethod"); protected override MethodInfo GenerateCore(DynamicMethodDefinition dmd, object? context) { MethodBase originalMethod = dmd.OriginalMethod; MethodDefinition val = dmd.Definition ?? throw new InvalidOperationException(); Type[] array; if (originalMethod != null) { ParameterInfo[] parameters = originalMethod.GetParameters(); int num = 0; if (!originalMethod.IsStatic) { num++; array = new Type[parameters.Length + 1]; array[0] = originalMethod.GetThisParamType(); } else { array = new Type[parameters.Length]; } for (int i = 0; i < parameters.Length; i++) { array[i + num] = parameters[i].ParameterType; } } else { int num2 = 0; if (((MethodReference)val).HasThis) { num2++; array = new Type[((MethodReference)val).Parameters.Count + 1]; Type type = ((TypeReference)(object)val.DeclaringType).ResolveReflection(); if (type.IsValueType) { type = type.MakeByRefType(); } array[0] = type; } else { array = new Type[((MethodReference)val).Parameters.Count]; } for (int j = 0; j < ((MethodReference)val).Parameters.Count; j++) { array[j + num2] = ((ParameterReference)((MethodReference)val).Parameters[j]).ParameterType.ResolveReflection(); } } string text = dmd.Name; if (text == null) { FormatInterpolatedStringHandler handler = new FormatInterpolatedStringHandler(5, 1); handler.AppendLiteral("DMD<"); handler.AppendFormatted(((object)originalMethod) ?? ((object)((MethodReference)(object)val).GetID(null, null, withType: true, simple: true))); handler.AppendLiteral(">"); text = DebugFormatter.Format(ref handler); } string text2 = text; Type value = (originalMethod as MethodInfo)?.ReturnType ?? ((MethodReference)val).ReturnType.ResolveReflection(); bool isEnabled; MMDbgLog.DebugLogTraceStringHandler message = new MMDbgLog.DebugLogTraceStringHandler(22, 3, out isEnabled); if (isEnabled) { message.AppendLiteral("new DynamicMethod: "); message.AppendFormatted(value); message.AppendLiteral(" "); message.AppendFormatted(text2); message.AppendLiteral("("); message.AppendFormatted(string.Join(",", array.Select((Type type2) => type2?.ToString()).ToArray())); message.AppendLiteral(")"); } MMDbgLog.Trace(ref message); if (originalMethod != null) { MMDbgLog.DebugLogTraceStringHandler message2 = new MMDbgLog.DebugLogTraceStringHandler(6, 1, out isEnabled); if (isEnabled) { message2.AppendLiteral("orig: "); message2.AppendFormatted(originalMethod); } MMDbgLog.Trace(ref message2); } MMDbgLog.DebugLogTraceStringHandler message3 = new MMDbgLog.DebugLogTraceStringHandler(9, 3, out isEnabled); if (isEnabled) { message3.AppendLiteral("mdef: "); message3.AppendFormatted(((object)((MethodReference)val).ReturnType)?.ToString() ?? "NULL"); message3.AppendLiteral(" "); message3.AppendFormatted(text2); message3.AppendLiteral("("); message3.AppendFormatted(string.Join(",", ((IEnumerable)((MethodReference)val).Parameters).Select((ParameterDefinition arg) => ((arg == null) ? null : ((object)((ParameterReference)arg).ParameterType)?.ToString()) ?? "NULL").ToArray())); message3.AppendLiteral(")"); } MMDbgLog.Trace(ref message3); DynamicMethod dynamicMethod = new DynamicMethod(text2, typeof(void), array, originalMethod?.DeclaringType ?? typeof(DynamicMethodDefinition), skipVisibility: true); _DynamicMethod_returnType.SetValue(dynamicMethod, value); ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); _DMDEmit.Generate(dmd, dynamicMethod, iLGenerator); return dynamicMethod; } } public sealed class DynamicData : DynamicObject, IDisposable, IEnumerable>, IEnumerable { private class _Cache_ { public readonly Dictionary> Getters = new Dictionary>(); public readonly Dictionary> Setters = new Dictionary>(); public readonly Dictionary> Methods = new Dictionary>(); public _Cache_(Type? targetType) { bool flag = true; while (targetType != null && targetType != targetType.BaseType) { FieldInfo[] fields = targetType.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { string name = fieldInfo.Name; if (Getters.ContainsKey(name) || Setters.ContainsKey(name)) { continue; } try { FastReflectionHelper.FastInvoker fastInvoker = fieldInfo.GetFastInvoker(); Getters[name] = (object? target) => fastInvoker(target); Setters[name] = delegate(object? target, object? value) { fastInvoker(target, value); }; } catch { Getters[name] = fieldInfo.GetValue; Setters[name] = fieldInfo.SetValue; } } PropertyInfo[] properties = targetType.GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (PropertyInfo propertyInfo in properties) { string name2 = propertyInfo.Name; MethodInfo get = propertyInfo.GetGetMethod(nonPublic: true); if (get != null && !Getters.ContainsKey(name2)) { try { FastReflectionHelper.FastInvoker fastInvoker2 = get.GetFastInvoker(); Getters[name2] = (object? target) => fastInvoker2(target); } catch { Getters[name2] = (object? obj5) => get.Invoke(obj5, _NoArgs); } } MethodInfo set = propertyInfo.GetSetMethod(nonPublic: true); if (!(set != null) || Setters.ContainsKey(name2)) { continue; } try { FastReflectionHelper.FastInvoker fastInvoker3 = set.GetFastInvoker(); Setters[name2] = delegate(object? target, object? value) { fastInvoker3(target, value); }; } catch { Setters[name2] = delegate(object? obj5, object? value) { set.Invoke(obj5, new object[1] { value }); }; } } Dictionary dictionary = new Dictionary(); MethodInfo[] methods = targetType.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { string name3 = methodInfo.Name; if (flag || !Methods.ContainsKey(name3)) { if (dictionary.ContainsKey(name3)) { dictionary[name3] = null; } else { dictionary[name3] = methodInfo; } } } foreach (KeyValuePair item in dictionary) { if (item.Value == null || item.Value.IsGenericMethod) { continue; } try { FastReflectionHelper.FastInvoker cb = item.Value.GetFastInvoker(); Methods[item.Key] = (object? target, object?[]? args) => cb(target, args); } catch { Methods[item.Key] = item.Value.Invoke; } } flag = false; targetType = targetType.BaseType; } } } private class _Data_ { public readonly Dictionary> Getters = new Dictionary>(); public readonly Dictionary> Setters = new Dictionary>(); public readonly Dictionary> Methods = new Dictionary>(); public readonly Dictionary Data = new Dictionary(); public _Data_(Type type) { _ = type == null; } } private static readonly object?[] _NoArgs = ArrayEx.Empty(); private static readonly Dictionary _CacheMap = new Dictionary(); private static readonly Dictionary _DataStaticMap = new Dictionary(); private static readonly ConditionalWeakTable _DataMap = new ConditionalWeakTable(); private static readonly ConditionalWeakTable _DynamicDataMap = new ConditionalWeakTable(); private readonly WeakReference? Weak; private object? KeepAlive; private readonly _Cache_ _Cache; private readonly _Data_ _Data; public Dictionary> Getters => _Data.Getters; public Dictionary> Setters => _Data.Setters; public Dictionary> Methods => _Data.Methods; public Dictionary Data => _Data.Data; public bool IsAlive { get { if (Weak != null) { return Weak.SafeGetIsAlive(); } return true; } } public object? Target => Weak?.SafeGetTarget(); public Type TargetType { get; private set; } public static event Action? OnInitialize; public DynamicData(Type type) : this(type, null, keepAlive: false) { } public DynamicData(object obj) : this(Helpers.ThrowIfNull(obj, "obj").GetType(), obj, keepAlive: true) { } public DynamicData(Type type, object? obj) : this(type, obj, keepAlive: true) { } public DynamicData(Type type, object? obj, bool keepAlive) { TargetType = type; lock (_CacheMap) { if (!_CacheMap.TryGetValue(type, out _Cache_ value)) { value = new _Cache_(type); _CacheMap.Add(type, value); } _Cache = value; } if (obj != null) { lock (_DataMap) { if (!_DataMap.TryGetValue(obj, out _Data_ value2)) { value2 = new _Data_(type); _DataMap.Add(obj, value2); } _Data = value2; } Weak = new WeakReference(obj); if (keepAlive) { KeepAlive = obj; } } else { lock (_DataStaticMap) { if (!_DataStaticMap.TryGetValue(type, out _Data_ value3)) { value3 = new _Data_(type); _DataStaticMap.Add(type, value3); } _Data = value3; } } DynamicData.OnInitialize?.Invoke(this, type, obj); } public static DynamicData For(object obj) { lock (_DynamicDataMap) { if (!_DynamicDataMap.TryGetValue(obj, out DynamicData value)) { value = new DynamicData(obj); _DynamicDataMap.Add(obj, value); } return value; } } public static Func New(params object[] args) where T : notnull { T target = (T)Activator.CreateInstance(typeof(T), BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, args, null); return (object other) => Set(target, other); } public static Func New(Type type, params object[] args) { object target = Activator.CreateInstance(type, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, args, null); return (object other) => Set(target, other); } public static Func NewWrap(params object[] args) { T target = (T)Activator.CreateInstance(typeof(T), BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, args, null); return (object other) => Wrap(target, other); } public static Func NewWrap(Type type, params object[] args) { object target = Activator.CreateInstance(type, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, args, null); return (object other) => Wrap(target, other); } public static dynamic Wrap(object target, object? other = null) { DynamicData dynamicData = new DynamicData(target); dynamicData.CopyFrom(other); return dynamicData; } public static T? Set(T target, object? other = null) where T : notnull { return (T)Set((object)target, other); } public static object? Set(object target, object? other = null) { using DynamicData dynamicData = new DynamicData(target); dynamicData.CopyFrom(other); return dynamicData.Target; } public void RegisterProperty(string name, Func getter, Action setter) { Getters[name] = getter; Setters[name] = setter; } public void UnregisterProperty(string name) { Getters.Remove(name); Setters.Remove(name); } public void RegisterMethod(string name, Func cb) { Methods[name] = cb; } public void UnregisterMethod(string name) { Methods.Remove(name); } public void CopyFrom(object? other) { if (other != null) { PropertyInfo[] properties = other.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (PropertyInfo propertyInfo in properties) { Set(propertyInfo.Name, propertyInfo.GetValue(other, null)); } } } public object? Get(string name) { TryGet(name, out object value); return value; } public bool TryGet(string name, out object? value) { object target = Target; if (_Data.Getters.TryGetValue(name, out Func value2)) { value = value2(target); return true; } if (_Cache.Getters.TryGetValue(name, out value2)) { value = value2(target); return true; } if (_Data.Data.TryGetValue(name, out value)) { return true; } return false; } public T? Get(string name) { return (T)Get(name); } public bool TryGet(string name, [MaybeNullWhen(false)] out T value) { object value2; bool result = TryGet(name, out value2); value = (T)value2; return result; } public void Set(string name, object? value) { object target = Target; if (_Data.Setters.TryGetValue(name, out Action value2)) { value2(target, value); } else if (_Cache.Setters.TryGetValue(name, out value2)) { value2(target, value); } else { Data[name] = value; } } public void Add(KeyValuePair kvp) { Set(kvp.Key, kvp.Value); } public void Add(string key, object value) { Set(key, value); } public object? Invoke(string name, params object[] args) { TryInvoke(name, args, out object result); return result; } public bool TryInvoke(string name, object?[]? args, out object? result) { if (_Data.Methods.TryGetValue(name, out Func value)) { result = value(Target, args); return true; } if (_Cache.Methods.TryGetValue(name, out value)) { result = value(Target, args); return true; } result = null; return false; } public T? Invoke(string name, params object[] args) { return (T)Invoke(name, args); } public bool TryInvoke(string name, object[] args, [MaybeNullWhen(false)] out T result) { object result3; bool result2 = TryInvoke(name, args, out result3); result = (T)result3; return result2; } private void Dispose(bool disposing) { KeepAlive = null; } ~DynamicData() { Dispose(disposing: false); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } public override IEnumerable GetDynamicMemberNames() { return _Data.Data.Keys.Union(_Data.Getters.Keys).Union(_Data.Setters.Keys).Union(_Data.Methods.Keys) .Union(_Cache.Getters.Keys) .Union(_Cache.Setters.Keys) .Union(_Cache.Methods.Keys); } public override bool TryConvert(ConvertBinder binder, out object? result) { Helpers.ThrowIfArgumentNull(binder, "binder"); if (TargetType.IsCompatible(binder.Type) || TargetType.IsCompatible(binder.ReturnType) || binder.Type == typeof(object) || binder.ReturnType == typeof(object)) { result = Target; return true; } if (typeof(DynamicData).IsCompatible(binder.Type) || typeof(DynamicData).IsCompatible(binder.ReturnType)) { result = this; return true; } result = null; return false; } public override bool TryGetMember(GetMemberBinder binder, out object? result) { Helpers.ThrowIfArgumentNull(binder, "binder"); if (Methods.ContainsKey(binder.Name)) { result = null; return false; } result = Get(binder.Name); return true; } public override bool TrySetMember(SetMemberBinder binder, object? value) { Helpers.ThrowIfArgumentNull(binder, "binder"); Set(binder.Name, value); return true; } public override bool TryInvokeMember(InvokeMemberBinder binder, object?[]? args, out object? result) { Helpers.ThrowIfArgumentNull(binder, "binder"); return TryInvoke(binder.Name, args, out result); } public IEnumerator> GetEnumerator() { foreach (string item in _Data.Data.Keys.Union(_Data.Getters.Keys).Union(_Data.Setters.Keys).Union(_Cache.Getters.Keys) .Union(_Cache.Setters.Keys)) { yield return new KeyValuePair(item, Get(item)); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public sealed class DynamicMethodDefinition : IDisposable { private enum TokenResolutionMode { Any, Type, Method, Field } private static OpCode[] _CecilOpCodes1X; private static OpCode[] _CecilOpCodes2X; internal static readonly bool _IsNewMonoSRE; internal static readonly bool _IsOldMonoSRE; private static bool _PreferCecil; internal static readonly ConstructorInfo c_DebuggableAttribute; internal static readonly ConstructorInfo c_UnverifiableCodeAttribute; internal static readonly ConstructorInfo c_IgnoresAccessChecksToAttribute; internal static readonly Type t__IDMDGenerator; internal static readonly ConcurrentDictionary _DMDGeneratorCache; private Guid GUID = Guid.NewGuid(); private bool isDisposed; public static bool IsDynamicILAvailable => !_PreferCecil; public MethodBase? OriginalMethod { get; } public MethodDefinition Definition { get; } public ModuleDefinition Module { get; } public string? Name { get; } public bool Debug { get; init; } private static void _InitCopier() { //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_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Invalid comparison between Unknown and I4 //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) _CecilOpCodes1X = (OpCode[])(object)new OpCode[225]; _CecilOpCodes2X = (OpCode[])(object)new OpCode[31]; FieldInfo[] fields = typeof(OpCodes).GetFields(BindingFlags.Static | BindingFlags.Public); for (int i = 0; i < fields.Length; i++) { OpCode val = (OpCode)fields[i].GetValue(null); if ((int)((OpCode)(ref val)).OpCodeType != 2) { if (((OpCode)(ref val)).Size == 1) { _CecilOpCodes1X[((OpCode)(ref val)).Value] = val; } else { _CecilOpCodes2X[((OpCode)(ref val)).Value & 0xFF] = val; } } } } private static void _CopyMethodToDefinition(MethodBase from, MethodDefinition into) { //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Expected O, but got Unknown //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Expected O, but got Unknown //IL_0143: 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_016f: Unknown result type (might be due to invalid IL or missing references) //IL_01fc: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Unknown result type (might be due to invalid IL or missing references) //IL_0218: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Unknown result type (might be due to invalid IL or missing references) //IL_0221: Unknown result type (might be due to invalid IL or missing references) //IL_0223: 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_022b: Invalid comparison between Unknown and I4 //IL_022d: Unknown result type (might be due to invalid IL or missing references) //IL_0231: Invalid comparison between Unknown and I4 //IL_02d1: Unknown result type (might be due to invalid IL or missing references) //IL_02d8: Expected O, but got Unknown //IL_031e: Unknown result type (might be due to invalid IL or missing references) //IL_0324: Invalid comparison between Unknown and I4 //IL_036f: Unknown result type (might be due to invalid IL or missing references) Module moduleFrom = from.Module; MethodBody methodBody = from.GetMethodBody() ?? throw new NotSupportedException("Body-less method"); byte[] buffer = methodBody.GetILAsByteArray() ?? throw new InvalidOperationException(); ModuleDefinition moduleTo = ((MemberReference)into).Module; MethodBody bodyTo = into.Body; bodyTo.GetILProcessor(); Type[] typeArguments = null; Type? declaringType = from.DeclaringType; if ((object)declaringType != null && declaringType.IsGenericType) { typeArguments = from.DeclaringType.GetGenericArguments(); } Type[] methodArguments = null; if (from.IsGenericMethod) { methodArguments = from.GetGenericArguments(); } foreach (LocalVariableInfo localVariable in methodBody.LocalVariables) { TypeReference val = moduleTo.ImportReference(localVariable.LocalType); if (localVariable.IsPinned) { val = (TypeReference)new PinnedType(val); } bodyTo.Variables.Add(new VariableDefinition(val)); } using (BinaryReader binaryReader = new BinaryReader(new MemoryStream(buffer))) { Instruction val2 = null; Instruction val3 = null; while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length) { int offset = (int)binaryReader.BaseStream.Position; val2 = Instruction.Create(OpCodes.Nop); byte b = binaryReader.ReadByte(); val2.OpCode = ((b != 254) ? _CecilOpCodes1X[b] : _CecilOpCodes2X[binaryReader.ReadByte()]); val2.Offset = offset; if (val3 != null) { val3.Next = val2; } val2.Previous = val3; ReadOperand(binaryReader, val2); bodyTo.Instructions.Add(val2); val3 = val2; } } Enumerator enumerator2 = bodyTo.Instructions.GetEnumerator(); try { while (enumerator2.MoveNext()) { Instruction current2 = enumerator2.Current; OpCode opCode = current2.OpCode; OperandType operandType = ((OpCode)(ref opCode)).OperandType; if ((int)operandType != 0) { if ((int)operandType == 10) { int[] array = (int[])current2.Operand; Instruction[] array2 = (Instruction[])(object)new Instruction[array.Length]; for (int i = 0; i < array.Length; i++) { array2[i] = GetInstruction(array[i]); } current2.Operand = array2; continue; } if ((int)operandType != 15) { continue; } } current2.Operand = GetInstruction((int)current2.Operand); } } finally { ((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose(); } foreach (ExceptionHandlingClause exceptionHandlingClause in methodBody.ExceptionHandlingClauses) { ExceptionHandler val4 = new ExceptionHandler((ExceptionHandlerType)exceptionHandlingClause.Flags); bodyTo.ExceptionHandlers.Add(val4); val4.TryStart = GetInstruction(exceptionHandlingClause.TryOffset); val4.TryEnd = GetInstruction(exceptionHandlingClause.TryOffset + exceptionHandlingClause.TryLength); val4.FilterStart = (((int)val4.HandlerType != 1) ? null : GetInstruction(exceptionHandlingClause.FilterOffset)); val4.HandlerStart = GetInstruction(exceptionHandlingClause.HandlerOffset); val4.HandlerEnd = GetInstruction(exceptionHandlingClause.HandlerOffset + exceptionHandlingClause.HandlerLength); val4.CatchType = (((int)val4.HandlerType != 0) ? null : ((exceptionHandlingClause.CatchType == null) ? null : moduleTo.ImportReference(exceptionHandlingClause.CatchType))); } Instruction? GetInstruction(int num2) { int num = bodyTo.Instructions.Count - 1; if (num2 < 0 || num2 > bodyTo.Instructions[num].Offset) { return null; } int num3 = 0; int num4 = num; while (num3 <= num4) { int num5 = num3 + (num4 - num3) / 2; Instruction val5 = bodyTo.Instructions[num5]; if (num2 == val5.Offset) { return val5; } if (num2 < val5.Offset) { num4 = num5 - 1; } else { num3 = num5 + 1; } } return null; } void ReadOperand(BinaryReader reader, Instruction instr) { //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_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Expected I4, but got Unknown //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_0283: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_020e: Unknown result type (might be due to invalid IL or missing references) //IL_0215: Invalid comparison between Unknown and I4 //IL_023f: 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_0248: Unknown result type (might be due to invalid IL or missing references) //IL_024f: Invalid comparison between Unknown and I4 //IL_00fc: 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) OpCode opCode2 = instr.OpCode; OperandType operandType2 = ((OpCode)(ref opCode2)).OperandType; switch ((int)operandType2) { case 5: instr.Operand = null; break; case 10: { int num2 = reader.ReadInt32(); int num3 = (int)reader.BaseStream.Position + 4 * num2; int[] array3 = new int[num2]; for (int j = 0; j < num2; j++) { array3[j] = reader.ReadInt32() + num3; } instr.Operand = array3; break; } case 15: { int num3 = reader.ReadSByte(); instr.Operand = (int)reader.BaseStream.Position + num3; break; } case 0: { int num3 = reader.ReadInt32(); instr.Operand = (int)reader.BaseStream.Position + num3; break; } case 16: instr.Operand = ((instr.OpCode == OpCodes.Ldc_I4_S) ? ((object)reader.ReadSByte()) : ((object)reader.ReadByte())); break; case 2: instr.Operand = reader.ReadInt32(); break; case 17: instr.Operand = reader.ReadSingle(); break; case 7: instr.Operand = reader.ReadDouble(); break; case 3: instr.Operand = reader.ReadInt64(); break; case 8: instr.Operand = moduleTo.ImportCallSite(moduleFrom, moduleFrom.ResolveSignature(reader.ReadInt32())); break; case 9: instr.Operand = moduleFrom.ResolveString(reader.ReadInt32()); break; case 11: instr.Operand = ResolveTokenAs(reader.ReadInt32(), TokenResolutionMode.Any); break; case 12: instr.Operand = ResolveTokenAs(reader.ReadInt32(), TokenResolutionMode.Type); break; case 4: instr.Operand = ResolveTokenAs(reader.ReadInt32(), TokenResolutionMode.Method); break; case 1: instr.Operand = ResolveTokenAs(reader.ReadInt32(), TokenResolutionMode.Field); break; case 13: case 18: { opCode2 = instr.OpCode; int num = (((int)((OpCode)(ref opCode2)).OperandType == 18) ? reader.ReadByte() : reader.ReadInt16()); instr.Operand = bodyTo.Variables[num]; break; } case 14: case 19: { opCode2 = instr.OpCode; int num = (((int)((OpCode)(ref opCode2)).OperandType == 19) ? reader.ReadByte() : reader.ReadInt16()); instr.Operand = ((MethodReference)into).Parameters[num]; break; } default: opCode2 = instr.OpCode; throw new NotSupportedException("Unsupported opcode $" + ((OpCode)(ref opCode2)).Name); } } MemberReference ResolveTokenAs(int token, TokenResolutionMode resolveMode) { //IL_01ef: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: Unknown result type (might be due to invalid IL or missing references) //IL_0200: Expected O, but got Unknown //IL_0220: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Expected O, but got Unknown //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_0247: Expected O, but got Unknown //IL_024b: Unknown result type (might be due to invalid IL or missing references) //IL_0251: Expected O, but got Unknown //IL_0255: Unknown result type (might be due to invalid IL or missing references) //IL_025b: Expected O, but got Unknown try { switch (resolveMode) { case TokenResolutionMode.Type: { Type type2 = moduleFrom.ResolveType(token, typeArguments, methodArguments); type2.FixReflectionCacheAuto(); return (MemberReference)(object)moduleTo.ImportReference(type2); } case TokenResolutionMode.Method: { MethodBase methodBase2 = moduleFrom.ResolveMethod(token, typeArguments, methodArguments); methodBase2?.GetRealDeclaringType()?.FixReflectionCacheAuto(); return (MemberReference)(object)moduleTo.ImportReference(methodBase2); } case TokenResolutionMode.Field: { FieldInfo fieldInfo2 = moduleFrom.ResolveField(token, typeArguments, methodArguments); fieldInfo2?.GetRealDeclaringType()?.FixReflectionCacheAuto(); return (MemberReference)(object)moduleTo.ImportReference(fieldInfo2); } case TokenResolutionMode.Any: { MemberInfo memberInfo = moduleFrom.ResolveMember(token, typeArguments, methodArguments); if (memberInfo is Type type) { type.FixReflectionCacheAuto(); return (MemberReference)(object)moduleTo.ImportReference(type); } if (memberInfo is MethodBase methodBase) { methodBase.GetRealDeclaringType()?.FixReflectionCacheAuto(); return (MemberReference)(object)moduleTo.ImportReference(methodBase); } if (!(memberInfo is FieldInfo fieldInfo)) { throw new NotSupportedException($"Invalid resolved member type {memberInfo?.GetType()}"); } fieldInfo.GetRealDeclaringType()?.FixReflectionCacheAuto(); return (MemberReference)(object)moduleTo.ImportReference(fieldInfo); } default: throw new NotSupportedException($"Invalid TokenResolutionMode {resolveMode}"); } } catch (MissingMemberException) { string location = moduleFrom.Assembly.Location; if (!File.Exists(location)) { throw; } AssemblyDefinition val5 = AssemblyDefinition.ReadAssembly(location, new ReaderParameters { ReadingMode = (ReadingMode)2 }); try { MemberReference val6 = (MemberReference)((IEnumerable)val5.Modules).First((ModuleDefinition m) => ((ModuleReference)m).Name == moduleFrom.Name).LookupToken(token); return (MemberReference)(resolveMode switch { TokenResolutionMode.Type => (object)(TypeReference)val6, TokenResolutionMode.Method => (object)(MethodReference)val6, TokenResolutionMode.Field => (object)(FieldReference)val6, TokenResolutionMode.Any => val6, _ => throw new NotSupportedException($"Invalid TokenResolutionMode {resolveMode}"), }); } finally { ((IDisposable)val5)?.Dispose(); } } } } static DynamicMethodDefinition() { _CecilOpCodes1X = null; _CecilOpCodes2X = null; _IsNewMonoSRE = PlatformDetection.Runtime == RuntimeKind.Mono && typeof(DynamicMethod).GetField("il_info", BindingFlags.Instance | BindingFlags.NonPublic) != null; _IsOldMonoSRE = PlatformDetection.Runtime == RuntimeKind.Mono && !_IsNewMonoSRE && typeof(DynamicMethod).GetField("ilgen", BindingFlags.Instance | BindingFlags.NonPublic) != null; _PreferCecil = (PlatformDetection.Runtime == RuntimeKind.Mono && !_IsNewMonoSRE && !_IsOldMonoSRE) || (PlatformDetection.Runtime != RuntimeKind.Mono && typeof(ILGenerator).Assembly.GetType("System.Reflection.Emit.DynamicILGenerator")?.GetField("m_scope", BindingFlags.Instance | BindingFlags.NonPublic) == null); c_DebuggableAttribute = typeof(DebuggableAttribute).GetConstructor(new Type[1] { typeof(DebuggableAttribute.DebuggingModes) }); c_UnverifiableCodeAttribute = typeof(UnverifiableCodeAttribute).GetConstructor(ArrayEx.Empty()); c_IgnoresAccessChecksToAttribute = typeof(IgnoresAccessChecksToAttribute).GetConstructor(new Type[1] { typeof(string) }); t__IDMDGenerator = typeof(IDMDGenerator); _DMDGeneratorCache = new ConcurrentDictionary(); _InitCopier(); } private static bool GetDefaultDebugValue() { bool isEnabled; return Switches.TryGetSwitchEnabled("DMDDebug", out isEnabled) && isEnabled; } public DynamicMethodDefinition(MethodBase method) { Helpers.ThrowIfArgumentNull(method, "method"); OriginalMethod = method; Debug = GetDefaultDebugValue(); LoadFromMethod(method, out ModuleDefinition Module, out MethodDefinition def); this.Module = Module; Definition = def; } public DynamicMethodDefinition(DynamicMethodDefinition method) { Helpers.ThrowIfArgumentNull(method, "method"); OriginalMethod = null; Debug = GetDefaultDebugValue(); Name = method.Name; CreateFromDmd(method, out ModuleDefinition Module, out MethodDefinition Definition); this.Module = Module; this.Definition = Definition; } public DynamicMethodDefinition(string name, Type? returnType, Type[] parameterTypes) { Helpers.ThrowIfArgumentNull(name, "name"); Helpers.ThrowIfArgumentNull(parameterTypes, "parameterTypes"); Name = name; OriginalMethod = null; Debug = GetDefaultDebugValue(); _CreateDynModule(name, returnType, parameterTypes, out ModuleDefinition Module, out MethodDefinition Definition); this.Module = Module; this.Definition = Definition; } [MemberNotNull("Definition")] public ILProcessor GetILProcessor() { if (Definition == null) { throw new InvalidOperationException(); } return Definition.Body.GetILProcessor(); } [MemberNotNull("Definition")] public ILGenerator GetILGenerator() { if (Definition == null) { throw new InvalidOperationException(); } return new CecilILGenerator(Definition.Body.GetILProcessor()).GetProxy(); } private void _CreateDynModule(string name, Type? returnType, Type[] parameterTypes, out ModuleDefinition Module, out MethodDefinition Definition) { //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_004c: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Expected O, but got Unknown //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Expected O, but got Unknown //IL_00e6: Expected O, but got Unknown //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Expected O, but got Unknown ModuleDefinition val = (Module = ModuleDefinition.CreateModule($"DMD:DynModule<{name}>?{GetHashCode()}", new ModuleParameters { Kind = (ModuleKind)0, ReflectionImporterProvider = MMReflectionImporter.ProviderNoDefault })); TypeDefinition val2 = new TypeDefinition("", $"DMD<{name}>?{GetHashCode()}", (TypeAttributes)1); val.Types.Add(val2); MethodDefinition val3 = new MethodDefinition(name, (MethodAttributes)150, (returnType != null) ? val.ImportReference(returnType) : val.TypeSystem.Void); MethodDefinition val4 = val3; Definition = val3; MethodDefinition val5 = val4; foreach (Type type in parameterTypes) { ((MethodReference)val5).Parameters.Add(new ParameterDefinition(val.ImportReference(type))); } val2.Methods.Add(val5); } private void CreateFromDmd(DynamicMethodDefinition src, out ModuleDefinition Module, out MethodDefinition Definition) { //IL_0044: 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_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Expected O, but got Unknown //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Expected O, but got Unknown //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Expected O, but got Unknown ModuleDefinition val = (Module = ModuleDefinition.CreateModule($"DMD:DynModule<{src.Name}>?{GetHashCode()}", new ModuleParameters { Kind = (ModuleKind)0, ReflectionImporterProvider = MMReflectionImporter.ProviderNoDefault })); TypeDefinition val2 = new TypeDefinition("", $"DMD<{src.Name}>?{GetHashCode()}", (TypeAttributes)1); val.Types.Add(val2); MethodDefinition val3 = new MethodDefinition(src.Name, (MethodAttributes)150, val.ImportReference(((MethodReference)src.Definition).ReturnType)); val2.Methods.Add(val3); (Definition = src.Definition.Clone(val3)).DeclaringType = val2; } private void LoadFromMethod(MethodBase orig, out ModuleDefinition Module, out MethodDefinition def) { ParameterInfo[] parameters = orig.GetParameters(); int num = 0; Type[] array; if (!orig.IsStatic) { num++; array = new Type[parameters.Length + 1]; array[0] = orig.GetThisParamType(); } else { array = new Type[parameters.Length]; } for (int i = 0; i < parameters.Length; i++) { array[i + num] = parameters[i].ParameterType; } _CreateDynModule(orig.GetID(null, null, withType: true, proxyMethod: false, simple: true), (orig as MethodInfo)?.ReturnType, array, out Module, out def); _CopyMethodToDefinition(orig, def); if (!orig.IsStatic) { ((ParameterReference)((MethodReference)def).Parameters[0]).Name = "this"; } for (int j = 0; j < parameters.Length; j++) { ((ParameterReference)((MethodReference)def).Parameters[j + num]).Name = parameters[j].Name; } } public MethodInfo Generate() { return Generate(null); } public MethodInfo Generate(object? context) { object value; string text = (Switches.TryGetSwitchValue("DMDType", out value) ? (value as string) : null); if (text != null) { if (text.Equals("dynamicmethod", StringComparison.OrdinalIgnoreCase) || text.Equals("dm", StringComparison.OrdinalIgnoreCase)) { return DMDGenerator.Generate(this, context); } if (text.Equals("cecil", StringComparison.OrdinalIgnoreCase) || text.Equals("md", StringComparison.OrdinalIgnoreCase)) { return DMDGenerator.Generate(this, context); } } if (text != null) { Type type = ReflectionHelper.GetType(text); if (type != null) { if (!t__IDMDGenerator.IsCompatible(type)) { throw new ArgumentException("Invalid DMDGenerator type: " + text); } return _DMDGeneratorCache.GetOrAdd(text, (string _) => (IDMDGenerator)Activator.CreateInstance(type)).Generate(this, context); } } if (_PreferCecil) { return DMDGenerator.Generate(this, context); } if (Debug) { return DMDGenerator.Generate(this, context); } return DMDGenerator.Generate(this, context); } public void Dispose() { if (!isDisposed) { isDisposed = true; ModuleDefinition module = Module; if (module != null) { module.Dispose(); } } } public string GetDumpName(string type) { return $"DMDASM.{GUID.GetHashCode():X8}{(string.IsNullOrEmpty(type) ? "" : ("." + type))}"; } } public class DynamicMethodReference : MethodReference { public MethodInfo DynamicMethod { get; } public DynamicMethodReference(ModuleDefinition module, MethodInfo dm) : base("", Helpers.ThrowIfNull(module, "module").TypeSystem.Void) { DynamicMethod = dm; } } public record struct DynamicReferenceCell { public int Index { get; internal set; } public int Hash { get; internal set; } public DynamicReferenceCell(int idx, int hash) { Index = idx; Hash = hash; } } public static class DynamicReferenceManager { private abstract class Cell { public readonly nuint Type; protected Cell(nuint type) { Type = type; } } private class RefCell : Cell { public object? Value; public RefCell() : base(0u) { } } private abstract class ValueCellBase : Cell { public ValueCellBase() : base(1u) { } public abstract object? BoxValue(); } private class ValueCell : ValueCellBase { public T? Value; public override object? BoxValue() { return Value; } } private sealed class ScopeHandler : ScopeHandlerBase { public static readonly ScopeHandler Instance = new ScopeHandler(); public override void EndScope(DynamicReferenceCell data) { bool lockTaken = false; try { writeLock.Enter(ref lockTaken); Cell[] cells = DynamicReferenceManager.cells; Cell cell = Volatile.Read(in cells[data.Index]); if (cell != null && cell.GetHashCode() == data.Hash) { Volatile.Write(ref cells[data.Index], null); firstEmptyCell = Math.Min(firstEmptyCell, data.Index); } } finally { if (lockTaken) { writeLock.Exit(); } } } } private const nuint RefValueCell = 0u; private const nuint ValueTypeCell = 1u; private static SpinLock writeLock = new SpinLock(enableThreadOwnerTracking: false); private static volatile Cell?[] cells = new Cell[16]; private static volatile int firstEmptyCell; private static readonly MethodInfo Self_GetValue_ii = typeof(DynamicReferenceManager).GetMethod("GetValue", BindingFlags.Static | BindingFlags.NonPublic, null, new Type[2] { typeof(int), typeof(int) }, null) ?? throw new InvalidOperationException("GetValue doesn't exist?!?!?!?"); private static readonly MethodInfo Self_GetValueT_ii = typeof(DynamicReferenceManager).GetMethod("GetValueT", BindingFlags.Static | BindingFlags.NonPublic, null, new Type[2] { typeof(int), typeof(int) }, null) ?? throw new InvalidOperationException("GetValueT doesn't exist?!?!?!?"); private static readonly MethodInfo Self_GetValueTUnsafe_ii = typeof(DynamicReferenceManager).GetMethod("GetValueTUnsafe", BindingFlags.Static | BindingFlags.NonPublic, null, new Type[2] { typeof(int), typeof(int) }, null) ?? throw new InvalidOperationException("GetValueTUnsafe doesn't exist?!?!?!?"); private static DataScope AllocReferenceCore(Cell cell, out DynamicReferenceCell cellRef) { cellRef = default(DynamicReferenceCell); bool lockTaken = false; try { writeLock.Enter(ref lockTaken); Cell[] array = cells; int i = firstEmptyCell; if (i >= array.Length) { Cell[] destinationArray = new Cell[array.Length * 2]; Array.Copy(array, destinationArray, array.Length); array = (cells = destinationArray); } int num = i++; for (; i < array.Length && array[i] != null; i++) { } firstEmptyCell = i; Volatile.Write(ref array[num], cell); cellRef = new DynamicReferenceCell(num, cell.GetHashCode()); } finally { if (lockTaken) { writeLock.Exit(); } } return new DataScope(ScopeHandler.Instance, cellRef); } private static DataScope AllocReferenceClass(object? value, out DynamicReferenceCell cellRef) { return AllocReferenceCore(new RefCell { Value = value }, out cellRef); } private static DataScope AllocReferenceStruct(in T value, out DynamicReferenceCell cellRef) { return AllocReferenceCore(new ValueCell { Value = value }, out cellRef); } [MethodImpl(MethodImplOptions.AggressiveOptimization)] public static DataScope AllocReference(in T? value, out DynamicReferenceCell cellRef) { if (!typeof(T).IsValueType) { return AllocReferenceClass(Unsafe.As(ref Unsafe.AsRef(in value)), out cellRef); } return AllocReferenceStruct(in value, out cellRef); } private static Cell GetCell(DynamicReferenceCell cellRef) { Cell cell = Volatile.Read(in cells[cellRef.Index]); if (cell == null || cell.GetHashCode() != cellRef.Hash) { throw new ArgumentException("Referenced cell no longer exists", "cellRef"); } return cell; } public static object? GetValue(DynamicReferenceCell cellRef) { Cell cell = GetCell(cellRef); return (ulong)cell.Type switch { 0uL => Unsafe.As(cell).Value, 1uL => Unsafe.As(cell).BoxValue(), _ => throw new InvalidOperationException("Cell is not of valid type"), }; } [MethodImpl(MethodImplOptions.AggressiveOptimization)] private static ref T? GetValueRef(DynamicReferenceCell cellRef) { Cell cell = GetCell(cellRef); switch (cell.Type) { case 0uL: { Helpers.Assert(!typeof(T).IsValueType, null, "!typeof(T).IsValueType"); RefCell refCell = Unsafe.As(cell); object value = refCell.Value; bool value2 = ((value == null || value is T) ? true : false); Helpers.Assert(value2, null, "c.Value is null or T"); return ref Unsafe.As(ref refCell.Value); } case 1uL: Helpers.Assert(typeof(T).IsValueType, null, "typeof(T).IsValueType"); return ref ((ValueCell)cell).Value; default: throw new InvalidOperationException("Cell is not of valid type"); } } [MethodImpl(MethodImplOptions.AggressiveOptimization)] private static ref T? GetValueRefUnsafe(DynamicReferenceCell cellRef) { Cell cell = GetCell(cellRef); if (default(T) == null) { return ref Unsafe.As(ref Unsafe.As(cell).Value); } return ref Unsafe.As>(cell).Value; } public static T? GetValue(DynamicReferenceCell cellRef) { return GetValueRef(cellRef); } internal static object? GetValue(int index, int hash) { return GetValue(new DynamicReferenceCell(index, hash)); } internal static T? GetValueT(int index, int hash) { return GetValue(new DynamicReferenceCell(index, hash)); } internal static T? GetValueTUnsafe(int index, int hash) { return GetValueRefUnsafe(new DynamicReferenceCell(index, hash)); } public static void SetValue(DynamicReferenceCell cellRef, in T? value) { GetValueRef(cellRef) = value; } public static void EmitLoadReference(this ILProcessor il, DynamicReferenceCell cellRef) { //IL_000c: 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_0030: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(il, "il"); il.Emit(OpCodes.Ldc_I4, cellRef.Index); il.Emit(OpCodes.Ldc_I4, cellRef.Hash); il.Emit(OpCodes.Call, ((MemberReference)il.Body.Method).Module.ImportReference((MethodBase)Self_GetValue_ii)); } public static void EmitLoadReference(this ILCursor il, DynamicReferenceCell cellRef) { //IL_000c: 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_0032: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(il, "il"); il.Emit(OpCodes.Ldc_I4, cellRef.Index); il.Emit(OpCodes.Ldc_I4, cellRef.Hash); il.Emit(OpCodes.Call, ((MemberReference)il.Body.Method).Module.ImportReference((MethodBase)Self_GetValue_ii)); } public static void EmitLoadReference(this ILGenerator il, DynamicReferenceCell cellRef) { Helpers.ThrowIfArgumentNull(il, "il"); il.Emit(OpCodes.Ldc_I4, cellRef.Index); il.Emit(OpCodes.Ldc_I4, cellRef.Hash); il.Emit(OpCodes.Call, Self_GetValue_ii); } public static void EmitLoadTypedReference(this ILProcessor il, DynamicReferenceCell cellRef, Type type) { //IL_000c: 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_0030: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(il, "il"); il.Emit(OpCodes.Ldc_I4, cellRef.Index); il.Emit(OpCodes.Ldc_I4, cellRef.Hash); il.Emit(OpCodes.Call, ((MemberReference)il.Body.Method).Module.ImportReference((MethodBase)Self_GetValueT_ii.MakeGenericMethod(type))); } public static void EmitLoadTypedReference(this ILCursor il, DynamicReferenceCell cellRef, Type type) { //IL_000c: 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_0032: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(il, "il"); il.Emit(OpCodes.Ldc_I4, cellRef.Index); il.Emit(OpCodes.Ldc_I4, cellRef.Hash); il.Emit(OpCodes.Call, ((MemberReference)il.Body.Method).Module.ImportReference((MethodBase)Self_GetValueT_ii.MakeGenericMethod(type))); } public static void EmitLoadTypedReference(this ILGenerator il, DynamicReferenceCell cellRef, Type type) { Helpers.ThrowIfArgumentNull(il, "il"); il.Emit(OpCodes.Ldc_I4, cellRef.Index); il.Emit(OpCodes.Ldc_I4, cellRef.Hash); il.Emit(OpCodes.Call, Self_GetValueT_ii.MakeGenericMethod(type)); } internal static void EmitLoadTypedReferenceUnsafe(this ILProcessor il, DynamicReferenceCell cellRef, Type type) { //IL_000c: 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_0030: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(il, "il"); il.Emit(OpCodes.Ldc_I4, cellRef.Index); il.Emit(OpCodes.Ldc_I4, cellRef.Hash); il.Emit(OpCodes.Call, ((MemberReference)il.Body.Method).Module.ImportReference((MethodBase)Self_GetValueTUnsafe_ii.MakeGenericMethod(type))); } internal static void EmitLoadTypedReferenceUnsafe(this ILCursor il, DynamicReferenceCell cellRef, Type type) { //IL_000c: 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_0032: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(il, "il"); il.Emit(OpCodes.Ldc_I4, cellRef.Index); il.Emit(OpCodes.Ldc_I4, cellRef.Hash); il.Emit(OpCodes.Call, ((MemberReference)il.Body.Method).Module.ImportReference((MethodBase)Self_GetValueTUnsafe_ii.MakeGenericMethod(type))); } internal static void EmitLoadTypedReferenceUnsafe(this ILGenerator il, DynamicReferenceCell cellRef, Type type) { Helpers.ThrowIfArgumentNull(il, "il"); il.Emit(OpCodes.Ldc_I4, cellRef.Index); il.Emit(OpCodes.Ldc_I4, cellRef.Hash); il.Emit(OpCodes.Call, Self_GetValueTUnsafe_ii.MakeGenericMethod(type)); } public static DataScope EmitNewReference(this ILProcessor il, object? value, out DynamicReferenceCell cellRef) { DataScope result = AllocReference(in value, out cellRef); il.EmitLoadReference(cellRef); return result; } public static DataScope EmitNewReference(this ILCursor il, object? value, out DynamicReferenceCell cellRef) { DataScope result = AllocReference(in value, out cellRef); il.EmitLoadReference(cellRef); return result; } public static DataScope EmitNewReference(this ILGenerator il, object? value, out DynamicReferenceCell cellRef) { DataScope result = AllocReference(in value, out cellRef); il.EmitLoadReference(cellRef); return result; } public static DataScope EmitNewTypedReference(this ILProcessor il, T? value, out DynamicReferenceCell cellRef) { DataScope result = AllocReference(in value, out cellRef); il.EmitLoadTypedReferenceUnsafe(cellRef, typeof(T)); return result; } public static DataScope EmitNewTypedReference(this ILCursor il, T? value, out DynamicReferenceCell cellRef) { DataScope result = AllocReference(in value, out cellRef); il.EmitLoadTypedReferenceUnsafe(cellRef, typeof(T)); return result; } public static DataScope EmitNewTypedReference(this ILGenerator il, T? value, out DynamicReferenceCell cellRef) { DataScope result = AllocReference(in value, out cellRef); il.EmitLoadTypedReferenceUnsafe(cellRef, typeof(T)); return result; } } public sealed class DynData : IDisposable where TTarget : class { private class _Data_ : IDisposable { public readonly Dictionary> Getters = new Dictionary>(); public readonly Dictionary> Setters = new Dictionary>(); public readonly Dictionary Data = new Dictionary(); public readonly HashSet Disposable = new HashSet(); ~_Data_() { Dispose(); } public void Dispose() { lock (Data) { if (Data.Count == 0) { return; } foreach (string item in Disposable) { if (Data.TryGetValue(item, out object value) && value is IDisposable disposable) { disposable.Dispose(); } } Disposable.Clear(); Data.Clear(); } GC.SuppressFinalize(this); } } private static readonly _Data_ _DataStatic; private static readonly ConditionalWeakTable _DataMap; private static readonly Dictionary> _SpecialGetters; private static readonly Dictionary> _SpecialSetters; private readonly WeakReference? Weak; private TTarget? KeepAlive; private readonly _Data_ _Data; public Dictionary> Getters => _Data.Getters; public Dictionary> Setters => _Data.Setters; public Dictionary Data => _Data.Data; public bool IsAlive { get { if (Weak != null) { return Weak.SafeGetIsAlive(); } return true; } } public TTarget Target => (TTarget)(Weak?.SafeGetTarget()); public object? this[string name] { get { if (_SpecialGetters.TryGetValue(name, out Func value) || Getters.TryGetValue(name, out value)) { return value(Target); } if (Data.TryGetValue(name, out object value2)) { return value2; } return null; } set { if (_SpecialSetters.TryGetValue(name, out Action value2) || Setters.TryGetValue(name, out value2)) { value2(Target, value); return; } object obj; if (_Data.Disposable.Contains(name) && (obj = this[name]) != null && obj is IDisposable disposable) { disposable.Dispose(); } Data[name] = value; } } public static event Action, TTarget?>? OnInitialize; static DynData() { _DataStatic = new _Data_(); _DataMap = new ConditionalWeakTable(); _SpecialGetters = new Dictionary>(); _SpecialSetters = new Dictionary>(); FieldInfo[] fields = typeof(TTarget).GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo field in fields) { string name = field.Name; _SpecialGetters[name] = (TTarget obj) => field.GetValue(obj); _SpecialSetters[name] = delegate(TTarget obj, object? value) { field.SetValue(obj, value); }; } PropertyInfo[] properties = typeof(TTarget).GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (PropertyInfo propertyInfo in properties) { string name2 = propertyInfo.Name; MethodInfo get = propertyInfo.GetGetMethod(nonPublic: true); if (get != null) { _SpecialGetters[name2] = (TTarget obj) => get.Invoke(obj, ArrayEx.Empty()); } MethodInfo set = propertyInfo.GetSetMethod(nonPublic: true); if (set != null) { _SpecialSetters[name2] = delegate(TTarget obj, object? value) { set.Invoke(obj, new object[1] { value }); }; } } } public DynData() : this((TTarget?)null, keepAlive: false) { } public DynData(TTarget? obj) : this(obj, keepAlive: true) { } public DynData(TTarget? obj, bool keepAlive) { if (obj != null) { WeakReference weak = new WeakReference(obj); if (!_DataMap.TryGetValue(obj, out _Data_ value)) { value = new _Data_(); _DataMap.Add(obj, value); } _Data = value; Weak = weak; if (keepAlive) { KeepAlive = obj; } } else { _Data = _DataStatic; } DynData.OnInitialize?.Invoke(this, obj); } public T? Get(string name) { return (T)this[name]; } public void Set(string name, T value) { this[name] = value; } public void RegisterProperty(string name, Func getter, Action setter) { Getters[name] = getter; Setters[name] = setter; } public void UnregisterProperty(string name) { Getters.Remove(name); Setters.Remove(name); } private void Dispose(bool disposing) { KeepAlive = null; if (disposing) { _Data.Dispose(); } } ~DynData() { Dispose(disposing: false); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } public static class DynDll { private abstract class BackendImpl { protected abstract bool TryOpenLibraryCore(string? name, Assembly assembly, out nint handle); public abstract bool TryCloseLibrary(nint handle); public abstract bool TryGetExport(nint handle, string name, out nint ptr); protected abstract void CheckAndThrowError(); public virtual bool TryOpenLibrary(string? name, Assembly assembly, out nint handle) { if (name != null) { foreach (string item in GetLibrarySearchOrder(name)) { if (TryOpenLibraryCore(item, assembly, out handle)) { return true; } } handle = IntPtr.Zero; return false; } return TryOpenLibraryCore(null, assembly, out handle); } protected virtual IEnumerable GetLibrarySearchOrder(string name) { yield return name; } public virtual nint OpenLibrary(string? name, Assembly assembly) { if (!TryOpenLibrary(name, assembly, out var handle)) { CheckAndThrowError(); } return handle; } public virtual void CloseLibrary(nint handle) { if (!TryCloseLibrary(handle)) { CheckAndThrowError(); } } public virtual nint GetExport(nint handle, string name) { if (!TryGetExport(handle, name, out var ptr)) { CheckAndThrowError(); } return ptr; } } private sealed class NativeLibraryBackend : BackendImpl { protected override void CheckAndThrowError() { throw new NotSupportedException(); } private nint GetMainProgramHandle(Assembly assembly) { return NativeLibrary.GetMainProgramHandle(); } protected override bool TryOpenLibraryCore(string? name, Assembly assembly, out nint handle) { if (name == null) { handle = GetMainProgramHandle(assembly); return true; } return NativeLibrary.TryLoad(name, assembly, null, out handle); } public override nint OpenLibrary(string? name, Assembly assembly) { if (name == null) { return GetMainProgramHandle(assembly); } return NativeLibrary.Load(name, assembly, null); } public override bool TryOpenLibrary(string? name, Assembly assembly, out nint handle) { return TryOpenLibraryCore(name, assembly, out handle); } public override bool TryCloseLibrary(nint handle) { NativeLibrary.Free(handle); return true; } public override bool TryGetExport(nint handle, string name, out nint ptr) { return NativeLibrary.TryGetExport(handle, name, out ptr); } public override void CloseLibrary(nint handle) { TryCloseLibrary(handle); } public override nint GetExport(nint handle, string name) { return NativeLibrary.GetExport(handle, name); } } private sealed class WindowsBackend : BackendImpl { protected override void CheckAndThrowError() { uint lastError = Windows.GetLastError(); if (lastError != 0) { throw new Win32Exception((int)lastError); } } protected unsafe override bool TryOpenLibraryCore(string? name, Assembly assembly, out nint handle) { nint num; if (name == null) { num = (handle = (nint)Windows.GetModuleHandleW(null)); } else { fixed (char* lpLibFileName = name.AsSpan()) { num = (handle = (nint)Windows.LoadLibraryW((ushort*)lpLibFileName)); } } return num != IntPtr.Zero; } public unsafe override bool TryCloseLibrary(nint handle) { return Windows.FreeLibrary(new Windows.HMODULE((void*)handle)); } public unsafe override bool TryGetExport(nint handle, string name, out nint ptr) { byte[]? array = Unix.MarshalToUtf8(name); nint num; fixed (byte* lpProcName = array) { num = (ptr = Windows.GetProcAddress(new Windows.HMODULE((void*)handle), (sbyte*)lpProcName)); } Unix.FreeMarshalledArray(array); return num != IntPtr.Zero; } protected override IEnumerable GetLibrarySearchOrder(string name) { yield return name; if (!name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) && !name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) { yield return name + ".dll"; } } } private abstract class LibdlBackend : BackendImpl { [ThreadStatic] private static nint lastDlErrorReturn; protected LibdlBackend() { Unix.DlError(); } [DoesNotReturn] private static void ThrowError(nint dlerr) { throw new Win32Exception(Marshal.PtrToStringAnsi(dlerr)); } protected override void CheckAndThrowError() { nint num = lastDlErrorReturn; nint num2; if (num == IntPtr.Zero) { num2 = Unix.DlError(); } else { num2 = num; lastDlErrorReturn = IntPtr.Zero; } if (num2 != IntPtr.Zero) { ThrowError(num2); } } protected override bool TryOpenLibraryCore(string? name, Assembly assembly, out nint handle) { Unix.DlopenFlags flags = (Unix.DlopenFlags)258; return (handle = Unix.DlOpen(name, flags)) != IntPtr.Zero; } public override bool TryCloseLibrary(nint handle) { return Unix.DlClose(handle); } public override bool TryGetExport(nint handle, string name, out nint ptr) { Unix.DlError(); ptr = Unix.DlSym(handle, name); return (lastDlErrorReturn = Unix.DlError()) == IntPtr.Zero; } public override nint GetExport(nint handle, string name) { Unix.DlError(); nint result = Unix.DlSym(handle, name); nint num = Unix.DlError(); if (num != IntPtr.Zero) { ThrowError(num); } return result; } } private sealed class LinuxOSXBackend : LibdlBackend { private readonly bool isLinux; public LinuxOSXBackend(bool isLinux) { this.isLinux = isLinux; } protected override IEnumerable GetLibrarySearchOrder(string name) { bool hasSlash = name.Contains('/', StringComparison.Ordinal); string suffix = ".dylib"; if (isLinux) { if (name.EndsWith(".so", StringComparison.Ordinal) || name.Contains(".so.", StringComparison.Ordinal)) { yield return name; if (!hasSlash) { yield return "lib" + name; } yield return name + ".so"; if (!hasSlash) { yield return "lib" + name + ".so"; } yield break; } suffix = ".so"; } yield return name + suffix; if (!hasSlash) { yield return "lib" + name + suffix; } yield return name; if (!hasSlash) { yield return "lib" + name; } bool flag = isLinux; if (flag) { bool flag2 = ((name == "c" || name == "libc") ? true : false); flag = flag2; } if (!flag) { yield break; } foreach (string item in GetLibrarySearchOrder("c.so.6")) { yield return item; } foreach (string item2 in GetLibrarySearchOrder("glibc")) { yield return item2; } foreach (string item3 in GetLibrarySearchOrder("glibc.so.6")) { yield return item3; } } } private sealed class UnknownPosixBackend : LibdlBackend { } private static readonly NativeLibraryBackend Backend = new NativeLibraryBackend(); [CompilerGenerated] private static string k__BackingField; [CompilerGenerated] private static string k__BackingField; [CompilerGenerated] private static string k__BackingField; [CompilerGenerated] private static string k__BackingField; [CompilerGenerated] private static string k__BackingField; public static string DllPrefix { get { if (k__BackingField == null) { OSKind oS = PlatformDetection.OS; if (oS.Is(OSKind.Windows)) { k__BackingField = ""; } else { if (!oS.Is(OSKind.Posix)) { throw new PlatformNotSupportedException($"OS kind {oS} not supported"); } k__BackingField = "lib"; } } return k__BackingField; } } public static string DllExtension { get { if (k__BackingField == null) { OSKind oS = PlatformDetection.OS; if (oS.Is(OSKind.Windows)) { k__BackingField = "dll"; } else if (oS.Is(OSKind.OSX)) { k__BackingField = "dylib"; } else { if (!oS.Is(OSKind.Posix)) { throw new PlatformNotSupportedException($"OS kind {oS} not supported"); } k__BackingField = "so"; } } return k__BackingField; } } public static string DllSuffix => k__BackingField ?? (k__BackingField = "." + DllExtension); public static string ExeExtension { get { if (k__BackingField == null) { OSKind oS = PlatformDetection.OS; if (oS.Is(OSKind.Windows)) { k__BackingField = "exe"; } else { if (!oS.Is(OSKind.Posix)) { throw new PlatformNotSupportedException($"OS kind {oS} not supported"); } k__BackingField = ""; } } return k__BackingField; } } public static string ExeSuffix => k__BackingField ?? (k__BackingField = (string.IsNullOrEmpty(ExeExtension) ? "" : ("." + ExeExtension))); private static BackendImpl CreateCrossplatBackend(OSKind os) { if (os.Is(OSKind.Windows)) { return new WindowsBackend(); } if (os.Is(OSKind.Linux) || os.Is(OSKind.OSX)) { return new LinuxOSXBackend(os.Is(OSKind.Linux)); } bool isEnabled; MMDbgLog.DebugLogWarningStringHandler message = new MMDbgLog.DebugLogWarningStringHandler(55, 1, out isEnabled); if (isEnabled) { message.AppendLiteral("Unknown OS "); message.AppendFormatted(os); message.AppendLiteral(" when setting up DynDll; assuming posix-like"); } MMDbgLog.Warning(ref message); return new UnknownPosixBackend(); } internal static void InitializeBackend(OSKind os) { } private static BackendImpl CreateCrossplatBackend() { return CreateCrossplatBackend(PlatformDetection.OS); } public static string MakeDllName(string name) { return DllPrefix + name + DllSuffix; } public static nint OpenLibrary(string? name) { return Backend.OpenLibrary(name, Assembly.GetCallingAssembly()); } public static bool TryOpenLibrary(string? name, out nint libraryPtr) { return Backend.TryOpenLibrary(name, Assembly.GetCallingAssembly(), out libraryPtr); } public static void CloseLibrary(nint lib) { Backend.CloseLibrary(lib); } public static bool TryCloseLibrary(nint lib) { return Backend.TryCloseLibrary(lib); } public static nint GetExport(this nint libraryPtr, string name) { return Backend.GetExport(libraryPtr, name); } public static bool TryGetExport(this nint libraryPtr, string name, out nint functionPtr) { return Backend.TryGetExport(libraryPtr, name, out functionPtr); } } public static class Extensions { private static readonly Type t_Code = typeof(Code); private static readonly Type t_OpCodes = typeof(OpCodes); private static readonly Dictionary _ToLongOp = new Dictionary(); private static readonly Dictionary _ToShortOp = new Dictionary(); private static readonly Dictionary fmap_mono_assembly = new Dictionary(); private static readonly bool _MonoAssemblyNameHasArch = new AssemblyName("Dummy, ProcessorArchitecture=MSIL").ProcessorArchitecture == ProcessorArchitecture.MSIL; private static readonly Type? _RTDynamicMethod = typeof(DynamicMethod).GetNestedType("RTDynamicMethod", BindingFlags.Public | BindingFlags.NonPublic); private static readonly Type t_ParamArrayAttribute = typeof(ParamArrayAttribute); private static readonly FieldInfo f_GenericParameter_position = typeof(GenericParameter).GetField("position", BindingFlags.Instance | BindingFlags.NonPublic) ?? throw new InvalidOperationException("No field 'position' on GenericParameter"); private static readonly FieldInfo f_GenericParameter_type = typeof(GenericParameter).GetField("type", BindingFlags.Instance | BindingFlags.NonPublic) ?? throw new InvalidOperationException("No field 'type' on GenericParameter"); private static readonly ConcurrentDictionary _GetManagedSizeCache = new ConcurrentDictionary(new KeyValuePair[1] { new KeyValuePair(typeof(void), 0) }); private static MethodInfo? _GetManagedSizeHelper; private static readonly Dictionary> _GetLdftnPointerCache = new Dictionary>(); private static readonly Type? RTDynamicMethod = typeof(DynamicMethod).GetNestedType("RTDynamicMethod", BindingFlags.NonPublic); private static readonly FieldInfo? RTDynamicMethod_m_owner = RTDynamicMethod?.GetField("m_owner", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); private static readonly Type? t_StateMachineAttribute = typeof(object).Assembly.GetType("System.Runtime.CompilerServices.StateMachineAttribute"); private static readonly PropertyInfo? p_StateMachineType = t_StateMachineAttribute?.GetProperty("StateMachineType"); public static TypeDefinition? SafeResolve(this TypeReference? r) { try { return (r != null) ? r.Resolve() : null; } catch { return null; } } public static FieldDefinition? SafeResolve(this FieldReference? r) { try { return (r != null) ? r.Resolve() : null; } catch { return null; } } public static MethodDefinition? SafeResolve(this MethodReference? r) { try { return (r != null) ? r.Resolve() : null; } catch { return null; } } public static PropertyDefinition? SafeResolve(this PropertyReference? r) { try { return (r != null) ? r.Resolve() : null; } catch { return null; } } public static CustomAttribute? GetCustomAttribute(this ICustomAttributeProvider cap, string attribute) { //IL_0013: 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) if (cap == null || !cap.HasCustomAttributes) { return null; } Enumerator enumerator = cap.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; if (((MemberReference)current.AttributeType).FullName == attribute) { return current; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } return null; } public static bool HasCustomAttribute(this ICustomAttributeProvider cap, string attribute) { return cap.GetCustomAttribute(attribute) != null; } public static int GetInt(this Instruction instr) { //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_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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_0022: 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_0031: 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_0040: 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_004f: 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_005e: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_007c: 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_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(instr, "instr"); OpCode opCode = instr.OpCode; if (opCode == OpCodes.Ldc_I4_M1) { return -1; } if (opCode == OpCodes.Ldc_I4_0) { return 0; } if (opCode == OpCodes.Ldc_I4_1) { return 1; } if (opCode == OpCodes.Ldc_I4_2) { return 2; } if (opCode == OpCodes.Ldc_I4_3) { return 3; } if (opCode == OpCodes.Ldc_I4_4) { return 4; } if (opCode == OpCodes.Ldc_I4_5) { return 5; } if (opCode == OpCodes.Ldc_I4_6) { return 6; } if (opCode == OpCodes.Ldc_I4_7) { return 7; } if (opCode == OpCodes.Ldc_I4_8) { return 8; } if (opCode == OpCodes.Ldc_I4_S) { return (sbyte)instr.Operand; } return (int)instr.Operand; } public static int? GetIntOrNull(this Instruction instr) { //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_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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_0027: 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_003b: 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_004f: 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_0063: 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_0077: 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_008b: 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_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00da: 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_00f8: 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) Helpers.ThrowIfArgumentNull(instr, "instr"); OpCode opCode = instr.OpCode; if (opCode == OpCodes.Ldc_I4_M1) { return -1; } if (opCode == OpCodes.Ldc_I4_0) { return 0; } if (opCode == OpCodes.Ldc_I4_1) { return 1; } if (opCode == OpCodes.Ldc_I4_2) { return 2; } if (opCode == OpCodes.Ldc_I4_3) { return 3; } if (opCode == OpCodes.Ldc_I4_4) { return 4; } if (opCode == OpCodes.Ldc_I4_5) { return 5; } if (opCode == OpCodes.Ldc_I4_6) { return 6; } if (opCode == OpCodes.Ldc_I4_7) { return 7; } if (opCode == OpCodes.Ldc_I4_8) { return 8; } if (opCode == OpCodes.Ldc_I4_S) { return (sbyte)instr.Operand; } if (opCode == OpCodes.Ldc_I4) { return (int)instr.Operand; } return null; } public static bool IsBaseMethodCall(this MethodBody body, MethodReference? called) { Helpers.ThrowIfArgumentNull(body, "body"); MethodDefinition method = body.Method; if (called == null) { return false; } TypeReference val = ((MemberReference)called).DeclaringType; while (true) { TypeSpecification val2 = (TypeSpecification)(object)((val is TypeSpecification) ? val : null); if (val2 == null) { break; } val = val2.ElementType; } string patchFullName = ((MemberReference)(object)val).GetPatchFullName(); bool flag = false; try { TypeDefinition val3 = method.DeclaringType; while ((val3 = val3.BaseType?.SafeResolve()) != null) { if (((MemberReference)(object)val3).GetPatchFullName() == patchFullName) { flag = true; break; } } } catch { flag = ((MemberReference)(object)method.DeclaringType).GetPatchFullName() == patchFullName; } if (!flag) { return false; } return true; } public static bool IsCallvirt(this MethodReference method) { Helpers.ThrowIfArgumentNull(method, "method"); if (!method.HasThis) { return false; } if (((MemberReference)method).DeclaringType.IsValueType) { return false; } return true; } public static bool IsStruct(this TypeReference type) { Helpers.ThrowIfArgumentNull(type, "type"); if (!type.IsValueType) { return false; } if (type.IsPrimitive) { return false; } return true; } public static OpCode ToLongOp(this OpCode op) { //IL_0007: 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_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected I4, but got Unknown //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_004f: 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_00ad: 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_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Expected I4, but got Unknown //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) string name = Enum.GetName(t_Code, ((OpCode)(ref op)).Code); if (name == null || !name.EndsWith("_S", StringComparison.Ordinal)) { return op; } lock (_ToLongOp) { if (_ToLongOp.TryGetValue((int)((OpCode)(ref op)).Code, out var value)) { return value; } return _ToLongOp[(int)((OpCode)(ref op)).Code] = ((OpCode?)t_OpCodes.GetField(name.Substring(0, name.Length - 2))?.GetValue(null)) ?? op; } } public static OpCode ToShortOp(this OpCode op) { //IL_0007: 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_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected I4, but got Unknown //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_004f: 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_00a9: 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_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Expected I4, but got Unknown //IL_0099: 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) string name = Enum.GetName(t_Code, ((OpCode)(ref op)).Code); if (name == null || name.EndsWith("_S", StringComparison.Ordinal)) { return op; } lock (_ToShortOp) { if (_ToShortOp.TryGetValue((int)((OpCode)(ref op)).Code, out var value)) { return value; } return _ToShortOp[(int)((OpCode)(ref op)).Code] = ((OpCode?)t_OpCodes.GetField(name + "_S")?.GetValue(null)) ?? op; } } public static void RecalculateILOffsets(this MethodDefinition method) { Helpers.ThrowIfArgumentNull(method, "method"); if (method.HasBody) { int num = 0; for (int i = 0; i < method.Body.Instructions.Count; i++) { Instruction val = method.Body.Instructions[i]; val.Offset = num; num += val.GetSize(); } } } public static void FixShortLongOps(this MethodDefinition method) { //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_00ad: 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_00c7: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(method, "method"); if (!method.HasBody) { return; } for (int i = 0; i < method.Body.Instructions.Count; i++) { Instruction val = method.Body.Instructions[i]; if (val.Operand is Instruction) { val.OpCode = val.OpCode.ToLongOp(); } } method.RecalculateILOffsets(); bool flag; do { flag = false; for (int j = 0; j < method.Body.Instructions.Count; j++) { Instruction val2 = method.Body.Instructions[j]; object operand = val2.Operand; Instruction val3 = (Instruction)((operand is Instruction) ? operand : null); if (val3 != null) { int num = val3.Offset - (val2.Offset + val2.GetSize()); if (num == (sbyte)num) { OpCode opCode = val2.OpCode; val2.OpCode = val2.OpCode.ToShortOp(); flag = opCode != val2.OpCode; } } } } while (flag); } public static bool Is(this MemberInfo? minfo, MemberReference? mref) { return mref.Is(minfo); } public static bool Is(this MemberReference? mref, MemberInfo? minfo) { if (mref == null) { return false; } if ((object)minfo == null) { return false; } TypeReference val = mref.DeclaringType; if (((val != null) ? ((MemberReference)val).FullName : null) == "") { val = null; } GenericParameter val2 = (GenericParameter)(object)((mref is GenericParameter) ? mref : null); if (val2 != null) { if (!(minfo is Type type)) { return false; } if (!type.IsGenericParameter) { IGenericParameterProvider owner = val2.Owner; IGenericInstance val3 = (IGenericInstance)(object)((owner is IGenericInstance) ? owner : null); if (val3 != null) { return ((MemberReference?)(object)val3.GenericArguments[val2.Position]).Is(type); } return false; } return val2.Position == type.GenericParameterPosition; } if (minfo.DeclaringType != null) { if (val == null) { return false; } Type type2 = minfo.DeclaringType; if (minfo is Type && type2.IsGenericType && !type2.IsGenericTypeDefinition) { type2 = type2.GetGenericTypeDefinition(); } if (!((MemberReference?)(object)val).Is(type2)) { return false; } } else if (val != null) { return false; } if (!(mref is TypeSpecification) && mref.Name != minfo.Name) { return false; } TypeReference val4 = (TypeReference)(object)((mref is TypeReference) ? mref : null); if (val4 != null) { if (!(minfo is Type type3)) { return false; } if (type3.IsGenericParameter) { return false; } GenericInstanceType val5 = (GenericInstanceType)(object)((mref is GenericInstanceType) ? mref : null); if (val5 != null) { if (!type3.IsGenericType) { return false; } Collection genericArguments = val5.GenericArguments; Type[] genericArguments2 = type3.GetGenericArguments(); if (genericArguments.Count != genericArguments2.Length) { return false; } for (int i = 0; i < genericArguments.Count; i++) { if (!((MemberReference?)(object)genericArguments[i]).Is(genericArguments2[i])) { return false; } } return ((MemberReference?)(object)((TypeSpecification)val5).ElementType).Is(type3.GetGenericTypeDefinition()); } if (val4.HasGenericParameters) { if (!type3.IsGenericType) { return false; } Collection genericParameters = val4.GenericParameters; Type[] genericArguments3 = type3.GetGenericArguments(); if (genericParameters.Count != genericArguments3.Length) { return false; } for (int j = 0; j < genericParameters.Count; j++) { if (!((MemberReference?)(object)genericParameters[j]).Is(genericArguments3[j])) { return false; } } } else if (type3.IsGenericType) { return false; } ArrayType val6 = (ArrayType)(object)((mref is ArrayType) ? mref : null); if (val6 != null) { if (!type3.IsArray) { return false; } if (val6.Dimensions.Count == type3.GetArrayRank()) { return ((MemberReference?)(object)((TypeSpecification)val6).ElementType).Is(type3.GetElementType()); } return false; } ByReferenceType val7 = (ByReferenceType)(object)((mref is ByReferenceType) ? mref : null); if (val7 != null) { if (!type3.IsByRef) { return false; } return ((MemberReference?)(object)((TypeSpecification)val7).ElementType).Is(type3.GetElementType()); } PointerType val8 = (PointerType)(object)((mref is PointerType) ? mref : null); if (val8 != null) { if (!type3.IsPointer) { return false; } return ((MemberReference?)(object)((TypeSpecification)val8).ElementType).Is(type3.GetElementType()); } TypeSpecification val9 = (TypeSpecification)(object)((mref is TypeSpecification) ? mref : null); if (val9 != null) { return ((MemberReference?)(object)val9.ElementType).Is(type3.HasElementType ? type3.GetElementType() : type3); } if (val != null) { return mref.Name == type3.Name; } return mref.FullName == type3.FullName?.Replace("+", "/", StringComparison.Ordinal); } if (minfo is Type) { return false; } MethodReference methodRef = (MethodReference)(object)((mref is MethodReference) ? mref : null); if (methodRef != null) { if (!(minfo is MethodBase methodBase)) { return false; } Collection parameters = methodRef.Parameters; ParameterInfo[] parameters2 = methodBase.GetParameters(); if (parameters.Count != parameters2.Length) { return false; } GenericInstanceMethod val10 = (GenericInstanceMethod)(object)((mref is GenericInstanceMethod) ? mref : null); if (val10 != null) { if (!methodBase.IsGenericMethod) { return false; } Collection genericArguments4 = val10.GenericArguments; Type[] genericArguments5 = methodBase.GetGenericArguments(); if (genericArguments4.Count != genericArguments5.Length) { return false; } for (int k = 0; k < genericArguments4.Count; k++) { if (!((MemberReference?)(object)genericArguments4[k]).Is(genericArguments5[k])) { return false; } } return ((MemberReference?)(object)((MethodSpecification)val10).ElementMethod).Is((methodBase as MethodInfo)?.GetGenericMethodDefinition() ?? methodBase); } if (methodRef.HasGenericParameters) { if (!methodBase.IsGenericMethod) { return false; } Collection genericParameters2 = methodRef.GenericParameters; Type[] genericArguments6 = methodBase.GetGenericArguments(); if (genericParameters2.Count != genericArguments6.Length) { return false; } for (int l = 0; l < genericParameters2.Count; l++) { if (!((MemberReference?)(object)genericParameters2[l]).Is(genericArguments6[l])) { return false; } } } else if (methodBase.IsGenericMethod) { return false; } Relinker relinker = null; relinker = delegate(IMetadataTokenProvider paramMemberRef, IGenericParameterProvider? ctx) { TypeReference val11 = (TypeReference)(object)((paramMemberRef is TypeReference) ? paramMemberRef : null); return (IMetadataTokenProvider)((val11 == null) ? ((object)paramMemberRef) : ((object)ResolveParameter(val11))); }; if (!((MemberReference?)(object)methodRef.ReturnType.Relink(relinker, null)).Is((methodBase as MethodInfo)?.ReturnType ?? typeof(void)) && !((MemberReference?)(object)methodRef.ReturnType).Is((methodBase as MethodInfo)?.ReturnType ?? typeof(void))) { return false; } for (int num = 0; num < parameters.Count; num++) { if (!((MemberReference?)(object)((ParameterReference)parameters[num]).ParameterType.Relink(relinker, null)).Is(parameters2[num].ParameterType) && !((MemberReference?)(object)((ParameterReference)parameters[num]).ParameterType).Is(parameters2[num].ParameterType)) { return false; } } return true; } if (minfo is MethodInfo) { return false; } if (mref is FieldReference != minfo is FieldInfo) { return false; } if (mref is PropertyReference != minfo is PropertyInfo) { return false; } if (mref is EventReference != minfo is EventInfo) { return false; } return true; TypeReference ResolveParameter(TypeReference paramTypeRef) { GenericParameter val11 = (GenericParameter)(object)((paramTypeRef is GenericParameter) ? paramTypeRef : null); if (val11 != null) { if (val11.Owner is MethodReference) { MethodReference obj = methodRef; GenericInstanceMethod val12 = (GenericInstanceMethod)(object)((obj is GenericInstanceMethod) ? obj : null); if (val12 != null) { return val12.GenericArguments[val11.Position]; } } IGenericParameterProvider owner2 = val11.Owner; TypeReference val13 = (TypeReference)(object)((owner2 is TypeReference) ? owner2 : null); if (val13 != null) { TypeReference declaringType = ((MemberReference)methodRef).DeclaringType; GenericInstanceType val14 = (GenericInstanceType)(object)((declaringType is GenericInstanceType) ? declaringType : null); if (val14 != null && ((MemberReference)val13).FullName == ((MemberReference)((TypeSpecification)val14).ElementType).FullName) { return val14.GenericArguments[val11.Position]; } } return paramTypeRef; } if (paramTypeRef == ((MemberReference)methodRef).DeclaringType.GetElementType()) { return ((MemberReference)methodRef).DeclaringType; } return paramTypeRef; } } public static IMetadataTokenProvider ImportReference(this ModuleDefinition mod, IMetadataTokenProvider mtp) { Helpers.ThrowIfArgumentNull(mod, "mod"); TypeReference val = (TypeReference)(object)((mtp is TypeReference) ? mtp : null); if (val != null) { return (IMetadataTokenProvider)(object)mod.ImportReference(val); } FieldReference val2 = (FieldReference)(object)((mtp is FieldReference) ? mtp : null); if (val2 != null) { return (IMetadataTokenProvider)(object)mod.ImportReference(val2); } MethodReference val3 = (MethodReference)(object)((mtp is MethodReference) ? mtp : null); if (val3 != null) { return (IMetadataTokenProvider)(object)mod.ImportReference(val3); } CallSite val4 = (CallSite)(object)((mtp is CallSite) ? mtp : null); if (val4 != null) { return (IMetadataTokenProvider)(object)mod.ImportReference(val4); } return mtp; } public static CallSite ImportReference(this ModuleDefinition mod, CallSite callsite) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown //IL_002a: 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) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Expected O, but got Unknown Helpers.ThrowIfArgumentNull(mod, "mod"); Helpers.ThrowIfArgumentNull(callsite, "callsite"); CallSite val = new CallSite(mod.ImportReference(callsite.ReturnType)); val.CallingConvention = callsite.CallingConvention; val.ExplicitThis = callsite.ExplicitThis; val.HasThis = callsite.HasThis; Enumerator enumerator = callsite.Parameters.GetEnumerator(); try { while (enumerator.MoveNext()) { ParameterDefinition current = enumerator.Current; ParameterDefinition val2 = new ParameterDefinition(mod.ImportReference(((ParameterReference)current).ParameterType)) { Name = ((ParameterReference)current).Name, Attributes = current.Attributes, Constant = current.Constant, MarshalInfo = current.MarshalInfo }; val.Parameters.Add(val2); } return val; } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } } public static void AddRange(this Collection list, IEnumerable other) { Helpers.ThrowIfArgumentNull>(list, "list"); foreach (T item in Helpers.ThrowIfNull(other, "other")) { list.Add(item); } } public static void AddRange(this IDictionary dict, IDictionary other) { Helpers.ThrowIfArgumentNull(dict, "dict"); foreach (DictionaryEntry item in Helpers.ThrowIfNull(other, "other")) { dict.Add(item.Key, item.Value); } } public static void AddRange(this IDictionary dict, IDictionary other) { Helpers.ThrowIfArgumentNull(dict, "dict"); foreach (KeyValuePair item in Helpers.ThrowIfNull(other, "other")) { dict.Add(item.Key, item.Value); } } public static void AddRange(this Dictionary dict, Dictionary other) where TKey : notnull { Helpers.ThrowIfArgumentNull(dict, "dict"); foreach (KeyValuePair item in Helpers.ThrowIfNull(other, "other")) { dict.Add(item.Key, item.Value); } } public static void InsertRange(this Collection list, int index, IEnumerable other) { Helpers.ThrowIfArgumentNull>(list, "list"); foreach (T item in Helpers.ThrowIfNull(other, "other")) { list.Insert(index++, item); } } public static bool IsCompatible(this Type type, Type other) { if (!Helpers.ThrowIfNull(type, "type")._IsCompatible(Helpers.ThrowIfNull(other, "other"))) { return other._IsCompatible(type); } return true; } private static bool _IsCompatible(this Type type, Type other) { if (type == other) { return true; } if (other.IsEnum && type == typeof(Enum)) { return false; } if (other.IsValueType && type == typeof(ValueType)) { return false; } if (type.IsAssignableFrom(other)) { return true; } if (other.IsEnum && type.IsCompatible(Enum.GetUnderlyingType(other))) { return true; } if ((other.IsPointer || other.IsByRef) && type == typeof(nint)) { return true; } if (type.IsPointer && other.IsPointer) { return true; } if (type.IsByRef && other.IsPointer) { return true; } return false; } public static T GetDeclaredMember(this T member) where T : MemberInfo { Helpers.ThrowIfArgumentNull(member, "member"); if (member.DeclaringType == member.ReflectedType) { return member; } if ((object)member.DeclaringType != null) { int metadataToken = member.MetadataToken; MemberInfo[] members = member.DeclaringType.GetMembers((BindingFlags)(-1)); foreach (MemberInfo memberInfo in members) { if (memberInfo.MetadataToken == metadataToken) { return (T)memberInfo; } } } return member; } public unsafe static void SetMonoCorlibInternal(this Assembly asm, bool value) { if (PlatformDetection.Runtime != RuntimeKind.Mono) { return; } Helpers.ThrowIfArgumentNull(asm, "asm"); Type type = asm.GetType(); if (type == null) { return; } FieldInfo value2; lock (fmap_mono_assembly) { if (!fmap_mono_assembly.TryGetValue(type, out value2)) { value2 = type.GetField("_mono_assembly", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? type.GetField("dynamic_assembly", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? throw new InvalidOperationException("Could not find assembly field for Mono"); fmap_mono_assembly[type] = value2; } } if (value2 == null) { return; } AssemblyName name = asm.GetName(); lock (ReflectionHelper.AssemblyCache) { WeakReference value3 = new WeakReference(asm); ReflectionHelper.AssemblyCache[asm.GetRuntimeHashedFullName()] = value3; ReflectionHelper.AssemblyCache[name.FullName] = value3; if (name.Name != null) { ReflectionHelper.AssemblyCache[name.Name] = value3; } } long num = 0L; object value4 = value2.GetValue(asm); if (!(value4 is nint num2)) { if (value4 is nuint num3) { num = (long)num3; } } else { num = num2; } int num4 = IntPtr.Size + IntPtr.Size + IntPtr.Size + IntPtr.Size + IntPtr.Size + IntPtr.Size + 20 + 4 + 4 + 4 + (_MonoAssemblyNameHasArch ? ((!ReflectionHelper.IsCoreBCL) ? ((IntPtr.Size == 4) ? 12 : 16) : ((IntPtr.Size == 4) ? 20 : 24)) : (ReflectionHelper.IsCoreBCL ? 16 : 8)) + IntPtr.Size + IntPtr.Size + 1 + 1 + 1; byte* ptr = (byte*)(num + num4); *ptr = (value ? ((byte)1) : ((byte)0)); } public static bool IsDynamicMethod(this MethodBase method) { Helpers.ThrowIfArgumentNull(method, "method"); if (_RTDynamicMethod != null) { if (!(method is DynamicMethod)) { return method.GetType() == _RTDynamicMethod; } return true; } if (method is DynamicMethod) { return true; } if (method.MetadataToken != 0 || !method.IsStatic || !method.IsPublic || (method.Attributes & MethodAttributes.PrivateScope) != MethodAttributes.PrivateScope) { return false; } if ((object)method.DeclaringType != null) { MethodInfo[] methods = method.DeclaringType.GetMethods(BindingFlags.Static | BindingFlags.Public); foreach (MethodInfo methodInfo in methods) { if (method == methodInfo) { return false; } } } return true; } public static object? SafeGetTarget(this WeakReference weak) { Helpers.ThrowIfArgumentNull(weak, "weak"); try { return weak.Target; } catch (InvalidOperationException) { return null; } } public static bool SafeGetIsAlive(this WeakReference weak) { Helpers.ThrowIfArgumentNull(weak, "weak"); try { return weak.IsAlive; } catch (InvalidOperationException) { return false; } } public static T CreateDelegate(this MethodBase method) where T : Delegate { return (T)method.CreateDelegate(typeof(T), null); } public static T CreateDelegate(this MethodBase method, object? target) where T : Delegate { return (T)method.CreateDelegate(typeof(T), target); } public static Delegate CreateDelegate(this MethodBase method, Type delegateType) { return method.CreateDelegate(delegateType, null); } public static Delegate CreateDelegate(this MethodBase method, Type delegateType, object? target) { Helpers.ThrowIfArgumentNull(method, "method"); Helpers.ThrowIfArgumentNull(delegateType, "delegateType"); if (!typeof(Delegate).IsAssignableFrom(delegateType)) { throw new ArgumentException("Type argument must be a delegate type!"); } if (method is DynamicMethod dynamicMethod) { return dynamicMethod.CreateDelegate(delegateType, target); } if (method is MethodInfo method2) { return Delegate.CreateDelegate(delegateType, target, method2); } RuntimeMethodHandle methodHandle = method.MethodHandle; RuntimeHelpers.PrepareMethod(methodHandle); nint functionPointer = methodHandle.GetFunctionPointer(); return (Delegate)Activator.CreateInstance(delegateType, target, functionPointer); } public static T? TryCreateDelegate(this MethodInfo? mi) where T : Delegate { try { return ((object)mi != null) ? mi.CreateDelegate() : null; } catch { return null; } } public static MethodDefinition? FindMethod(this TypeDefinition type, string id, bool simple = true) { //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: 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_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(type, "type"); Helpers.ThrowIfArgumentNull(id, "id"); Enumerator enumerator; if (simple && !id.Contains(' ', StringComparison.Ordinal)) { enumerator = type.Methods.GetEnumerator(); try { while (enumerator.MoveNext()) { MethodDefinition current = enumerator.Current; if (((MethodReference)(object)current).GetID(null, null, withType: true, simple: true) == id) { return current; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } enumerator = type.Methods.GetEnumerator(); try { while (enumerator.MoveNext()) { MethodDefinition current2 = enumerator.Current; if (((MethodReference)(object)current2).GetID(null, null, withType: false, simple: true) == id) { return current2; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } } enumerator = type.Methods.GetEnumerator(); try { while (enumerator.MoveNext()) { MethodDefinition current3 = enumerator.Current; if (((MethodReference)(object)current3).GetID() == id) { return current3; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } enumerator = type.Methods.GetEnumerator(); try { while (enumerator.MoveNext()) { MethodDefinition current4 = enumerator.Current; if (((MethodReference)(object)current4).GetID(null, null, withType: false) == id) { return current4; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } return null; } public static MethodDefinition? FindMethodDeep(this TypeDefinition type, string id, bool simple = true) { MethodDefinition? obj = Helpers.ThrowIfNull(type, "type").FindMethod(id, simple); if (obj == null) { TypeReference baseType = type.BaseType; if (baseType == null) { return null; } TypeDefinition obj2 = baseType.Resolve(); if (obj2 == null) { return null; } obj = obj2.FindMethodDeep(id, simple); } return obj; } public static MethodInfo? FindMethod(this Type type, string id, bool simple = true) { Helpers.ThrowIfArgumentNull(type, "type"); Helpers.ThrowIfArgumentNull(id, "id"); MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); MethodInfo[] array; if (simple && !id.Contains(' ', StringComparison.Ordinal)) { array = methods; foreach (MethodInfo methodInfo in array) { if (methodInfo.GetID(null, null, withType: true, proxyMethod: false, simple: true) == id) { return methodInfo; } } array = methods; foreach (MethodInfo methodInfo2 in array) { if (methodInfo2.GetID(null, null, withType: false, proxyMethod: false, simple: true) == id) { return methodInfo2; } } } array = methods; foreach (MethodInfo methodInfo3 in array) { if (methodInfo3.GetID(null, null, withType: true, proxyMethod: false, simple: false) == id) { return methodInfo3; } } array = methods; foreach (MethodInfo methodInfo4 in array) { if (methodInfo4.GetID(null, null, withType: false, proxyMethod: false, simple: false) == id) { return methodInfo4; } } return null; } public static MethodInfo? FindMethodDeep(this Type type, string id, bool simple = true) { MethodInfo? methodInfo = type.FindMethod(id, simple); if ((object)methodInfo == null) { Type? baseType = type.BaseType; if ((object)baseType == null) { return null; } methodInfo = baseType.FindMethodDeep(id, simple); } return methodInfo; } public static PropertyDefinition? FindProperty(this TypeDefinition type, string name) { //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) Helpers.ThrowIfArgumentNull(type, "type"); Enumerator enumerator = type.Properties.GetEnumerator(); try { while (enumerator.MoveNext()) { PropertyDefinition current = enumerator.Current; if (((MemberReference)current).Name == name) { return current; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } return null; } public static PropertyDefinition? FindPropertyDeep(this TypeDefinition type, string name) { Helpers.ThrowIfArgumentNull(type, "type"); PropertyDefinition? obj = type.FindProperty(name); if (obj == null) { TypeReference baseType = type.BaseType; if (baseType == null) { return null; } TypeDefinition obj2 = baseType.Resolve(); if (obj2 == null) { return null; } obj = obj2.FindPropertyDeep(name); } return obj; } public static FieldDefinition? FindField(this TypeDefinition type, string name) { //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) Helpers.ThrowIfArgumentNull(type, "type"); Enumerator enumerator = type.Fields.GetEnumerator(); try { while (enumerator.MoveNext()) { FieldDefinition current = enumerator.Current; if (((MemberReference)current).Name == name) { return current; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } return null; } public static FieldDefinition? FindFieldDeep(this TypeDefinition type, string name) { Helpers.ThrowIfArgumentNull(type, "type"); FieldDefinition? obj = type.FindField(name); if (obj == null) { TypeReference baseType = type.BaseType; if (baseType == null) { return null; } TypeDefinition obj2 = baseType.Resolve(); if (obj2 == null) { return null; } obj = obj2.FindFieldDeep(name); } return obj; } public static EventDefinition? FindEvent(this TypeDefinition type, string name) { //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) Helpers.ThrowIfArgumentNull(type, "type"); Enumerator enumerator = type.Events.GetEnumerator(); try { while (enumerator.MoveNext()) { EventDefinition current = enumerator.Current; if (((MemberReference)current).Name == name) { return current; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } return null; } public static EventDefinition? FindEventDeep(this TypeDefinition type, string name) { Helpers.ThrowIfArgumentNull(type, "type"); EventDefinition? obj = type.FindEvent(name); if (obj == null) { TypeReference baseType = type.BaseType; if (baseType == null) { return null; } TypeDefinition obj2 = baseType.Resolve(); if (obj2 == null) { return null; } obj = obj2.FindEventDeep(name); } return obj; } public static string GetID(this MethodReference method, string? name = null, string? type = null, bool withType = true, bool simple = false) { Helpers.ThrowIfArgumentNull(method, "method"); StringBuilder stringBuilder = new StringBuilder(); if (simple) { if (withType && (type != null || ((MemberReference)method).DeclaringType != null)) { stringBuilder.Append(type ?? ((MemberReference)(object)((MemberReference)method).DeclaringType).GetPatchFullName()).Append("::"); } stringBuilder.Append(name ?? ((MemberReference)method).Name); return stringBuilder.ToString(); } stringBuilder.Append(((MemberReference)(object)method.ReturnType).GetPatchFullName()).Append(' '); if (withType && (type != null || ((MemberReference)method).DeclaringType != null)) { stringBuilder.Append(type ?? ((MemberReference)(object)((MemberReference)method).DeclaringType).GetPatchFullName()).Append("::"); } stringBuilder.Append(name ?? ((MemberReference)method).Name); GenericInstanceMethod val = (GenericInstanceMethod)(object)((method is GenericInstanceMethod) ? method : null); if (val != null && val.GenericArguments.Count != 0) { stringBuilder.Append('<'); Collection genericArguments = val.GenericArguments; for (int i = 0; i < genericArguments.Count; i++) { if (i > 0) { stringBuilder.Append(','); } stringBuilder.Append(((MemberReference)(object)genericArguments[i]).GetPatchFullName()); } stringBuilder.Append('>'); } else if (method.GenericParameters.Count != 0) { stringBuilder.Append('<'); Collection genericParameters = method.GenericParameters; for (int j = 0; j < genericParameters.Count; j++) { if (j > 0) { stringBuilder.Append(','); } stringBuilder.Append(((MemberReference)genericParameters[j]).Name); } stringBuilder.Append('>'); } stringBuilder.Append('('); if (method.HasParameters) { Collection parameters = method.Parameters; for (int k = 0; k < parameters.Count; k++) { ParameterDefinition val2 = parameters[k]; if (k > 0) { stringBuilder.Append(','); } if (((ParameterReference)val2).ParameterType.IsSentinel) { stringBuilder.Append("...,"); } stringBuilder.Append(((MemberReference)(object)((ParameterReference)val2).ParameterType).GetPatchFullName()); } } stringBuilder.Append(')'); return stringBuilder.ToString(); } public static string GetID(this CallSite method) { Helpers.ThrowIfArgumentNull(method, "method"); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(((MemberReference)(object)method.ReturnType).GetPatchFullName()).Append(' '); stringBuilder.Append('('); if (method.HasParameters) { Collection parameters = method.Parameters; for (int i = 0; i < parameters.Count; i++) { ParameterDefinition val = parameters[i]; if (i > 0) { stringBuilder.Append(','); } if (((ParameterReference)val).ParameterType.IsSentinel) { stringBuilder.Append("...,"); } stringBuilder.Append(((MemberReference)(object)((ParameterReference)val).ParameterType).GetPatchFullName()); } } stringBuilder.Append(')'); return stringBuilder.ToString(); } public static string GetID(this MethodBase method, string? name = null, string? type = null, bool withType = true, bool proxyMethod = false, bool simple = false) { Helpers.ThrowIfArgumentNull(method, "method"); while (method is MethodInfo methodInfo && method.IsGenericMethod && !method.IsGenericMethodDefinition) { method = methodInfo.GetGenericMethodDefinition(); } StringBuilder stringBuilder = new StringBuilder(); if (simple) { if (withType && (type != null || method.DeclaringType != null)) { stringBuilder.Append(type ?? method.DeclaringType.FullName).Append("::"); } stringBuilder.Append(name ?? method.Name); return stringBuilder.ToString(); } stringBuilder.Append((method as MethodInfo)?.ReturnType?.FullName ?? "System.Void").Append(' '); if (withType && (type != null || method.DeclaringType != null)) { stringBuilder.Append(type ?? method.DeclaringType.FullName?.Replace("+", "/", StringComparison.Ordinal)).Append("::"); } stringBuilder.Append(name ?? method.Name); if (method.ContainsGenericParameters) { stringBuilder.Append('<'); Type[] genericArguments = method.GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { if (i > 0) { stringBuilder.Append(','); } stringBuilder.Append(genericArguments[i].Name); } stringBuilder.Append('>'); } stringBuilder.Append('('); ParameterInfo[] parameters = method.GetParameters(); for (int j = (proxyMethod ? 1 : 0); j < parameters.Length; j++) { ParameterInfo parameterInfo = parameters[j]; if (j > (proxyMethod ? 1 : 0)) { stringBuilder.Append(','); } bool flag; try { flag = parameterInfo.GetCustomAttributes(t_ParamArrayAttribute, inherit: false).Length != 0; } catch (NotSupportedException) { flag = false; } if (flag) { stringBuilder.Append("...,"); } stringBuilder.Append(parameterInfo.ParameterType.FullName); } stringBuilder.Append(')'); return stringBuilder.ToString(); } public static string GetPatchName(this MemberReference mr) { Helpers.ThrowIfArgumentNull(mr, "mr"); MemberReference obj = ((mr is ICustomAttributeProvider) ? mr : null); return ((obj != null) ? ((ICustomAttributeProvider)(object)obj).GetPatchName() : null) ?? mr.Name; } public static string GetPatchFullName(this MemberReference mr) { Helpers.ThrowIfArgumentNull(mr, "mr"); MemberReference obj = ((mr is ICustomAttributeProvider) ? mr : null); return ((obj != null) ? ((ICustomAttributeProvider)(object)obj).GetPatchFullName(mr) : null) ?? mr.FullName; } private static string GetPatchName(this ICustomAttributeProvider cap) { //IL_0059: 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) Helpers.ThrowIfArgumentNull(cap, "cap"); CustomAttribute customAttribute = cap.GetCustomAttribute("MonoMod.MonoModPatch"); string text; if (customAttribute != null) { CustomAttributeArgument val = customAttribute.ConstructorArguments[0]; text = (string)((CustomAttributeArgument)(ref val)).Value; int num = text.LastIndexOf('.'); if (num != -1 && num != text.Length - 1) { text = text.Substring(num + 1); } return text; } text = ((MemberReference)cap).Name; if (!text.StartsWith("patch_", StringComparison.Ordinal)) { return text; } return text.Substring(6); } private static string GetPatchFullName(this ICustomAttributeProvider cap, MemberReference mr) { //IL_0050: 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_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Expected O, but got Unknown //IL_0248: Unknown result type (might be due to invalid IL or missing references) //IL_027b: Unknown result type (might be due to invalid IL or missing references) //IL_02a2: Unknown result type (might be due to invalid IL or missing references) //IL_02a9: Expected O, but got Unknown //IL_0315: Unknown result type (might be due to invalid IL or missing references) //IL_031c: Expected O, but got Unknown //IL_01f2: 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) Helpers.ThrowIfArgumentNull(cap, "cap"); Helpers.ThrowIfArgumentNull(mr, "mr"); TypeReference val = (TypeReference)(object)((cap is TypeReference) ? cap : null); if (val != null) { CustomAttribute customAttribute = cap.GetCustomAttribute("MonoMod.MonoModPatch"); string text; if (customAttribute != null) { CustomAttributeArgument val2 = customAttribute.ConstructorArguments[0]; text = (string)((CustomAttributeArgument)(ref val2)).Value; } else { text = ((MemberReference)cap).Name; text = (text.StartsWith("patch_", StringComparison.Ordinal) ? text.Substring(6) : text); } if (text.StartsWith("global::", StringComparison.Ordinal)) { text = text.Substring(8); } else if (!text.Contains('.', StringComparison.Ordinal) && !text.Contains('/', StringComparison.Ordinal)) { if (!string.IsNullOrEmpty(val.Namespace)) { text = val.Namespace + "." + text; } else if (val.IsNested) { text = ((MemberReference)(object)((MemberReference)val).DeclaringType).GetPatchFullName() + "/" + text; } } TypeSpecification val3 = (TypeSpecification)(object)((mr is TypeSpecification) ? mr : null); if (val3 != null) { List list = new List(); TypeSpecification val4 = val3; TypeReference elementType; do { list.Add(val4); elementType = val4.ElementType; } while ((val4 = (TypeSpecification)(object)((elementType is TypeSpecification) ? elementType : null)) != null); StringBuilder stringBuilder = new StringBuilder(text.Length + list.Count * 4); stringBuilder.Append(text); for (int num = list.Count - 1; num > -1; num--) { val4 = list[num]; if (((TypeReference)val4).IsByReference) { stringBuilder.Append('&'); } else if (((TypeReference)val4).IsPointer) { stringBuilder.Append('*'); } else if (!((TypeReference)val4).IsPinned && !((TypeReference)val4).IsSentinel) { if (((TypeReference)val4).IsArray) { ArrayType val5 = (ArrayType)val4; if (val5.IsVector) { stringBuilder.Append("[]"); } else { stringBuilder.Append('['); for (int i = 0; i < val5.Dimensions.Count; i++) { if (i > 0) { stringBuilder.Append(','); } stringBuilder.Append(((object)val5.Dimensions[i]/*cast due to .constrained prefix*/).ToString()); } stringBuilder.Append(']'); } } else if (((TypeReference)val4).IsRequiredModifier) { stringBuilder.Append("modreq(").Append(((RequiredModifierType)val4).ModifierType).Append(')'); } else if (((TypeReference)val4).IsOptionalModifier) { stringBuilder.Append("modopt(").Append(((OptionalModifierType)val4).ModifierType).Append(')'); } else if (((TypeReference)val4).IsGenericInstance) { GenericInstanceType val6 = (GenericInstanceType)val4; stringBuilder.Append('<'); for (int j = 0; j < val6.GenericArguments.Count; j++) { if (j > 0) { stringBuilder.Append(','); } stringBuilder.Append(((MemberReference)(object)val6.GenericArguments[j]).GetPatchFullName()); } stringBuilder.Append('>'); } else { if (!((TypeReference)val4).IsFunctionPointer) { throw new NotSupportedException($"MonoMod can't handle TypeSpecification: {((MemberReference)val).FullName} ({((object)val).GetType()})"); } FunctionPointerType val7 = (FunctionPointerType)val4; stringBuilder.Append(' ').Append(((MemberReference)(object)val7.ReturnType).GetPatchFullName()).Append(" *("); if (val7.HasParameters) { for (int k = 0; k < val7.Parameters.Count; k++) { ParameterDefinition val8 = val7.Parameters[k]; if (k > 0) { stringBuilder.Append(','); } if (((ParameterReference)val8).ParameterType.IsSentinel) { stringBuilder.Append("...,"); } stringBuilder.Append(((MemberReference)((ParameterReference)val8).ParameterType).FullName); } } stringBuilder.Append(')'); } } } text = stringBuilder.ToString(); } return text; } FieldReference val9 = (FieldReference)(object)((cap is FieldReference) ? cap : null); if (val9 != null) { return $"{((MemberReference)(object)val9.FieldType).GetPatchFullName()} {((MemberReference)(object)((MemberReference)val9).DeclaringType).GetPatchFullName()}::{cap.GetPatchName()}"; } if (cap is MethodReference) { throw new InvalidOperationException("GetPatchFullName not supported on MethodReferences - use GetID instead"); } throw new InvalidOperationException($"GetPatchFullName not supported on type {((object)cap).GetType()}"); } [return: NotNullIfNotNull("o")] public static MethodDefinition? Clone(this MethodDefinition? o, MethodDefinition? c = null) { //IL_002f: 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_000f: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown //IL_0078: 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_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: 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_0138: 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_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) //IL_01ce: Unknown result type (might be due to invalid IL or missing references) if (o == null) { return null; } if (c == null) { c = new MethodDefinition(((MemberReference)o).Name, o.Attributes, ((MethodReference)o).ReturnType); } ((MemberReference)c).Name = ((MemberReference)o).Name; c.Attributes = o.Attributes; ((MethodReference)c).ReturnType = ((MethodReference)o).ReturnType; c.DeclaringType = o.DeclaringType; ((MemberReference)c).MetadataToken = ((MemberReference)c).MetadataToken; c.Body = o.Body?.Clone(c); c.Attributes = o.Attributes; c.ImplAttributes = o.ImplAttributes; c.PInvokeInfo = o.PInvokeInfo; c.IsPreserveSig = o.IsPreserveSig; c.IsPInvokeImpl = o.IsPInvokeImpl; Enumerator enumerator = ((MethodReference)o).GenericParameters.GetEnumerator(); try { while (enumerator.MoveNext()) { GenericParameter current = enumerator.Current; ((MethodReference)c).GenericParameters.Add(current.Clone()); } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } Enumerator enumerator2 = ((MethodReference)o).Parameters.GetEnumerator(); try { while (enumerator2.MoveNext()) { ParameterDefinition current2 = enumerator2.Current; ((MethodReference)c).Parameters.Add(current2.Clone()); } } finally { ((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose(); } Enumerator enumerator3 = o.CustomAttributes.GetEnumerator(); try { while (enumerator3.MoveNext()) { CustomAttribute current3 = enumerator3.Current; c.CustomAttributes.Add(current3.Clone()); } } finally { ((IDisposable)enumerator3/*cast due to .constrained prefix*/).Dispose(); } Enumerator enumerator4 = o.Overrides.GetEnumerator(); try { while (enumerator4.MoveNext()) { MethodReference current4 = enumerator4.Current; c.Overrides.Add(current4); } } finally { ((IDisposable)enumerator4/*cast due to .constrained prefix*/).Dispose(); } if (c.Body != null) { Enumerator enumerator5 = c.Body.Instructions.GetEnumerator(); try { while (enumerator5.MoveNext()) { Instruction current5 = enumerator5.Current; object operand = current5.Operand; GenericParameter val = (GenericParameter)((operand is GenericParameter) ? operand : null); int num; if (val != null && (num = ((MethodReference)o).GenericParameters.IndexOf(val)) != -1) { current5.Operand = ((MethodReference)c).GenericParameters[num]; continue; } object operand2 = current5.Operand; ParameterDefinition val2 = (ParameterDefinition)((operand2 is ParameterDefinition) ? operand2 : null); if (val2 != null && (num = ((MethodReference)o).Parameters.IndexOf(val2)) != -1) { current5.Operand = ((MethodReference)c).Parameters[num]; } } } finally { ((IDisposable)enumerator5/*cast due to .constrained prefix*/).Dispose(); } } return c; } [return: NotNullIfNotNull("bo")] public static MethodBody? Clone(this MethodBody? bo, MethodDefinition m) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown //IL_0066: 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_018c: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(m, "m"); if (bo == null) { return null; } MethodBody bc = new MethodBody(m); bc.MaxStackSize = bo.MaxStackSize; bc.InitLocals = bo.InitLocals; bc.LocalVarToken = bo.LocalVarToken; bc.Instructions.AddRange(((IEnumerable)bo.Instructions).Select(delegate(Instruction o) { //IL_0000: 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) Instruction obj = Instruction.Create(OpCodes.Nop); obj.OpCode = o.OpCode; obj.Operand = o.Operand; obj.Offset = o.Offset; return obj; })); bc.ExceptionHandlers.AddRange(((IEnumerable)bo.ExceptionHandlers).Select((Func)((ExceptionHandler o) => new ExceptionHandler(o.HandlerType) { TryStart = ((o.TryStart == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.TryStart)]), TryEnd = ((o.TryEnd == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.TryEnd)]), FilterStart = ((o.FilterStart == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.FilterStart)]), HandlerStart = ((o.HandlerStart == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.HandlerStart)]), HandlerEnd = ((o.HandlerEnd == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.HandlerEnd)]), CatchType = o.CatchType }))); bc.Variables.AddRange(((IEnumerable)bo.Variables).Select((Func)((VariableDefinition o) => new VariableDefinition(((VariableReference)o).VariableType)))); m.CustomDebugInformations.AddRange(((IEnumerable)bo.Method.CustomDebugInformations).Select((Func)delegate(CustomDebugInformation o) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Expected O, but got Unknown //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_00e7: 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_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_0125: Expected O, but got Unknown //IL_0052: 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_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_0049: Unknown result type (might be due to invalid IL or missing references) AsyncMethodBodyDebugInformation val3 = (AsyncMethodBodyDebugInformation)(object)((o is AsyncMethodBodyDebugInformation) ? o : null); if (val3 != null) { AsyncMethodBodyDebugInformation val4 = new AsyncMethodBodyDebugInformation(); InstructionOffset val5 = val3.CatchHandler; if (((InstructionOffset)(ref val5)).Offset >= 0) { val5 = val3.CatchHandler; ? catchHandler; if (!((InstructionOffset)(ref val5)).IsEndOfMethod) { val5 = val3.CatchHandler; catchHandler = new InstructionOffset(ResolveInstrOff(((InstructionOffset)(ref val5)).Offset)); } else { val5 = default(InstructionOffset); catchHandler = val5; } val4.CatchHandler = (InstructionOffset)catchHandler; } val4.Yields.AddRange(((IEnumerable)val3.Yields).Select((Func)((InstructionOffset off) => (!((InstructionOffset)(ref off)).IsEndOfMethod) ? new InstructionOffset(ResolveInstrOff(((InstructionOffset)(ref off)).Offset)) : default(InstructionOffset)))); val4.Resumes.AddRange(((IEnumerable)val3.Resumes).Select((Func)((InstructionOffset off) => (!((InstructionOffset)(ref off)).IsEndOfMethod) ? new InstructionOffset(ResolveInstrOff(((InstructionOffset)(ref off)).Offset)) : default(InstructionOffset)))); val4.ResumeMethods.AddRange((IEnumerable)val3.ResumeMethods); return (CustomDebugInformation)(object)val4; } StateMachineScopeDebugInformation val6 = (StateMachineScopeDebugInformation)(object)((o is StateMachineScopeDebugInformation) ? o : null); if (val6 != null) { StateMachineScopeDebugInformation val7 = new StateMachineScopeDebugInformation(); val7.Scopes.AddRange(((IEnumerable)val6.Scopes).Select((Func)delegate(StateMachineScope s) { //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_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: 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_002b: 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 InstructionOffset val8 = s.Start; Instruction obj = ResolveInstrOff(((InstructionOffset)(ref val8)).Offset); val8 = s.End; object obj2; if (!((InstructionOffset)(ref val8)).IsEndOfMethod) { val8 = s.End; obj2 = ResolveInstrOff(((InstructionOffset)(ref val8)).Offset); } else { obj2 = null; } return new StateMachineScope(obj, (Instruction)obj2); })); return (CustomDebugInformation)val7; } return o; })); m.DebugInformation.SequencePoints.AddRange(((IEnumerable)bo.Method.DebugInformation.SequencePoints).Select((Func)((SequencePoint o) => new SequencePoint(ResolveInstrOff(o.Offset), o.Document) { StartLine = o.StartLine, StartColumn = o.StartColumn, EndLine = o.EndLine, EndColumn = o.EndColumn }))); Enumerator enumerator = bc.Instructions.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current = enumerator.Current; object operand = current.Operand; Instruction val = (Instruction)((operand is Instruction) ? operand : null); if (val != null) { current.Operand = bc.Instructions[bo.Instructions.IndexOf(val)]; continue; } if (current.Operand is Instruction[] source) { current.Operand = source.Select((Instruction i) => bc.Instructions[bo.Instructions.IndexOf(i)]).ToArray(); continue; } object operand2 = current.Operand; VariableDefinition val2 = (VariableDefinition)((operand2 is VariableDefinition) ? operand2 : null); if (val2 != null) { current.Operand = bc.Variables[((VariableReference)val2).Index]; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } return bc; Instruction ResolveInstrOff(int off) { for (int i = 0; i < bo.Instructions.Count; i++) { if (bo.Instructions[i].Offset == off) { return bc.Instructions[i]; } } throw new ArgumentException($"Invalid instruction offset {off}"); } } public static GenericParameter Update(this GenericParameter param, int position, GenericParameterType type) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) f_GenericParameter_position.SetValue(param, position); f_GenericParameter_type.SetValue(param, type); return param; } public static GenericParameter? ResolveGenericParameter(this IGenericParameterProvider provider, GenericParameter orig) { //IL_003b: 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) Helpers.ThrowIfArgumentNull(provider, "provider"); Helpers.ThrowIfArgumentNull(orig, "orig"); GenericParameter val = (GenericParameter)(object)((provider is GenericParameter) ? provider : null); if (val != null && ((MemberReference)val).Name == ((MemberReference)orig).Name) { return val; } Enumerator enumerator = provider.GenericParameters.GetEnumerator(); try { while (enumerator.MoveNext()) { GenericParameter current = enumerator.Current; if (((MemberReference)current).Name == ((MemberReference)orig).Name) { return current; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } int position = orig.Position; if (provider is MethodReference && orig.DeclaringMethod != null) { if (position < provider.GenericParameters.Count) { return provider.GenericParameters[position]; } return orig.Clone().Update(position, (GenericParameterType)1); } if (provider is TypeReference && ((MemberReference)orig).DeclaringType != null) { if (position < provider.GenericParameters.Count) { return provider.GenericParameters[position]; } return orig.Clone().Update(position, (GenericParameterType)0); } IGenericParameterProvider obj = ((provider is TypeSpecification) ? provider : null); object obj2 = ((obj != null) ? ((IGenericParameterProvider)(object)((TypeSpecification)obj).ElementType).ResolveGenericParameter(orig) : null); if (obj2 == null) { IGenericParameterProvider obj3 = ((provider is MemberReference) ? provider : null); if (obj3 == null) { return null; } TypeReference declaringType = ((MemberReference)obj3).DeclaringType; if (declaringType == null) { return null; } obj2 = ((IGenericParameterProvider)(object)declaringType).ResolveGenericParameter(orig); } return (GenericParameter?)obj2; } [return: NotNullIfNotNull("mtp")] public static IMetadataTokenProvider? Relink(this IMetadataTokenProvider? mtp, Relinker relinker, IGenericParameterProvider context) { TypeReference val = (TypeReference)(object)((mtp is TypeReference) ? mtp : null); if (val == null) { GenericParameterConstraint val2 = (GenericParameterConstraint)(object)((mtp is GenericParameterConstraint) ? mtp : null); if (val2 == null) { MethodReference val3 = (MethodReference)(object)((mtp is MethodReference) ? mtp : null); if (val3 == null) { FieldReference val4 = (FieldReference)(object)((mtp is FieldReference) ? mtp : null); if (val4 == null) { ParameterDefinition val5 = (ParameterDefinition)(object)((mtp is ParameterDefinition) ? mtp : null); if (val5 == null) { CallSite val6 = (CallSite)(object)((mtp is CallSite) ? mtp : null); if (val6 == null) { if (mtp == null) { return null; } throw new InvalidOperationException($"MonoMod can't handle metadata token providers of the type {((object)mtp).GetType()}"); } return (IMetadataTokenProvider?)(object)val6.Relink(relinker, context); } return (IMetadataTokenProvider?)(object)val5.Relink(relinker, context); } return val4.Relink(relinker, context); } return val3.Relink(relinker, context); } return (IMetadataTokenProvider?)(object)val2.Relink(relinker, context); } return (IMetadataTokenProvider?)(object)val.Relink(relinker, context); } [return: NotNullIfNotNull("type")] public static TypeReference? Relink(this TypeReference? type, Relinker relinker, IGenericParameterProvider? context) { //IL_0301: Unknown result type (might be due to invalid IL or missing references) //IL_0307: Expected O, but got Unknown //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown //IL_0230: Unknown result type (might be due to invalid IL or missing references) //IL_023a: 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_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected O, but got Unknown //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Expected O, but got Unknown //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Expected O, but got Unknown //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Expected O, but got Unknown //IL_008d: 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_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Expected O, but got Unknown //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0161: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Expected O, but got Unknown if (type == null) { return null; } Helpers.ThrowIfArgumentNull(relinker, "relinker"); TypeSpecification val = (TypeSpecification)(object)((type is TypeSpecification) ? type : null); if (val != null) { TypeReference val2 = val.ElementType.Relink(relinker, context); if (type.IsSentinel) { return (TypeReference?)new SentinelType(val2); } if (type.IsByReference) { return (TypeReference?)new ByReferenceType(val2); } if (type.IsPointer) { return (TypeReference?)new PointerType(val2); } if (type.IsPinned) { return (TypeReference?)new PinnedType(val2); } if (type.IsArray) { ArrayType val3 = new ArrayType(val2, ((ArrayType)type).Rank); for (int i = 0; i < val3.Rank; i++) { val3.Dimensions[i] = ((ArrayType)type).Dimensions[i]; } return (TypeReference?)(object)val3; } if (type.IsRequiredModifier) { return (TypeReference?)new RequiredModifierType(((RequiredModifierType)type).ModifierType.Relink(relinker, context), val2); } if (type.IsOptionalModifier) { return (TypeReference?)new OptionalModifierType(((OptionalModifierType)type).ModifierType.Relink(relinker, context), val2); } if (type.IsGenericInstance) { GenericInstanceType val4 = new GenericInstanceType(val2); Enumerator enumerator = ((GenericInstanceType)type).GenericArguments.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeReference current = enumerator.Current; val4.GenericArguments.Add(current?.Relink(relinker, context)); } return (TypeReference?)(object)val4; } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } } if (type.IsFunctionPointer) { FunctionPointerType val5 = (FunctionPointerType)type; val5.ReturnType = val5.ReturnType.Relink(relinker, context); for (int j = 0; j < val5.Parameters.Count; j++) { ((ParameterReference)val5.Parameters[j]).ParameterType = ((ParameterReference)val5.Parameters[j]).ParameterType.Relink(relinker, context); } return (TypeReference?)(object)val5; } throw new NotSupportedException($"MonoMod can't handle TypeSpecification: {((MemberReference)type).FullName} ({((object)type).GetType()})"); } if (!type.IsGenericParameter || context == null) { return (TypeReference)relinker((IMetadataTokenProvider)(object)type, context); } GenericParameter val6 = context.ResolveGenericParameter((GenericParameter)type) ?? throw new RelinkTargetNotFoundException($"{"MonoMod relinker failed finding"} {((MemberReference)type).FullName} (context: {context})", (IMetadataTokenProvider)(object)type, (IMetadataTokenProvider?)(object)context); for (int k = 0; k < val6.Constraints.Count; k++) { if (!val6.Constraints[k].GetConstraintType().IsGenericInstance) { val6.Constraints[k] = val6.Constraints[k].Relink(relinker, context); } } return (TypeReference?)(object)val6; } [return: NotNullIfNotNull("constraint")] public static GenericParameterConstraint? Relink(this GenericParameterConstraint? constraint, Relinker relinker, IGenericParameterProvider context) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) if (constraint == null) { return null; } GenericParameterConstraint val = new GenericParameterConstraint(constraint.ConstraintType.Relink(relinker, context)); Enumerator enumerator = constraint.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; val.CustomAttributes.Add(current.Relink(relinker, context)); } return val; } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } } public static IMetadataTokenProvider Relink(this MethodReference method, Relinker relinker, IGenericParameterProvider context) { //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Expected O, but got Unknown //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: 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_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_003b: Expected O, but got Unknown //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Expected O, but got Unknown //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Unknown result type (might be due to invalid IL or missing references) //IL_018e: Expected O, but got Unknown Helpers.ThrowIfArgumentNull(method, "method"); Helpers.ThrowIfArgumentNull(relinker, "relinker"); if (method.IsGenericInstance) { GenericInstanceMethod val = (GenericInstanceMethod)method; GenericInstanceMethod val2 = new GenericInstanceMethod((MethodReference)((MethodSpecification)val).ElementMethod.Relink(relinker, context)); Enumerator enumerator = val.GenericArguments.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeReference current = enumerator.Current; val2.GenericArguments.Add(current.Relink(relinker, context)); } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } return (IMetadataTokenProvider)(MethodReference)relinker((IMetadataTokenProvider)(object)val2, context); } MethodReference val3 = new MethodReference(((MemberReference)method).Name, method.ReturnType, ((MemberReference)method).DeclaringType.Relink(relinker, context)); val3.CallingConvention = method.CallingConvention; val3.ExplicitThis = method.ExplicitThis; val3.HasThis = method.HasThis; Enumerator enumerator2 = method.GenericParameters.GetEnumerator(); try { while (enumerator2.MoveNext()) { GenericParameter current2 = enumerator2.Current; val3.GenericParameters.Add(current2.Relink(relinker, context)); } } finally { ((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose(); } val3.ReturnType = val3.ReturnType?.Relink(relinker, (IGenericParameterProvider?)(object)val3); Enumerator enumerator3 = method.Parameters.GetEnumerator(); try { while (enumerator3.MoveNext()) { ParameterDefinition current3 = enumerator3.Current; ((ParameterReference)current3).ParameterType = ((ParameterReference)current3).ParameterType.Relink(relinker, (IGenericParameterProvider?)(object)method); val3.Parameters.Add(current3); } } finally { ((IDisposable)enumerator3/*cast due to .constrained prefix*/).Dispose(); } return (IMetadataTokenProvider)(MethodReference)relinker((IMetadataTokenProvider)(object)val3, context); } public static CallSite Relink(this CallSite method, Relinker relinker, IGenericParameterProvider context) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown //IL_0024: 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_006b: 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_00bc: Expected O, but got Unknown Helpers.ThrowIfArgumentNull(method, "method"); Helpers.ThrowIfArgumentNull(relinker, "relinker"); CallSite val = new CallSite(method.ReturnType); val.CallingConvention = method.CallingConvention; val.ExplicitThis = method.ExplicitThis; val.HasThis = method.HasThis; val.ReturnType = val.ReturnType?.Relink(relinker, context); Enumerator enumerator = method.Parameters.GetEnumerator(); try { while (enumerator.MoveNext()) { ParameterDefinition current = enumerator.Current; ((ParameterReference)current).ParameterType = ((ParameterReference)current).ParameterType.Relink(relinker, context); val.Parameters.Add(current); } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } return (CallSite)relinker((IMetadataTokenProvider)(object)val, context); } public static IMetadataTokenProvider Relink(this FieldReference field, Relinker relinker, IGenericParameterProvider context) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected O, but got Unknown Helpers.ThrowIfArgumentNull(field, "field"); Helpers.ThrowIfArgumentNull(relinker, "relinker"); TypeReference val = ((MemberReference)field).DeclaringType.Relink(relinker, context); return relinker((IMetadataTokenProvider)new FieldReference(((MemberReference)field).Name, field.FieldType.Relink(relinker, (IGenericParameterProvider?)(object)val), val), context); } public static ParameterDefinition Relink(this ParameterDefinition param, Relinker relinker, IGenericParameterProvider context) { //IL_0046: 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_005d: 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_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Expected O, but got Unknown Helpers.ThrowIfArgumentNull(param, "param"); Helpers.ThrowIfArgumentNull(relinker, "relinker"); IMethodSignature method = param.Method; IMethodSignature obj = ((method is MethodReference) ? method : null); param = ((obj != null) ? ((MethodReference)obj).Parameters[((ParameterReference)param).Index] : null) ?? param; ParameterDefinition val = new ParameterDefinition(((ParameterReference)param).Name, param.Attributes, ((ParameterReference)param).ParameterType.Relink(relinker, context)) { IsIn = param.IsIn, IsLcid = param.IsLcid, IsOptional = param.IsOptional, IsOut = param.IsOut, IsReturnValue = param.IsReturnValue, MarshalInfo = param.MarshalInfo }; if (param.HasConstant) { val.Constant = param.Constant; } return val; } public static ParameterDefinition Clone(this ParameterDefinition param) { //IL_0012: 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_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002e: 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_0046: 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_005e: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected O, but got Unknown //IL_0085: 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) Helpers.ThrowIfArgumentNull(param, "param"); ParameterDefinition val = new ParameterDefinition(((ParameterReference)param).Name, param.Attributes, ((ParameterReference)param).ParameterType) { IsIn = param.IsIn, IsLcid = param.IsLcid, IsOptional = param.IsOptional, IsOut = param.IsOut, IsReturnValue = param.IsReturnValue, MarshalInfo = param.MarshalInfo }; if (param.HasConstant) { val.Constant = param.Constant; } Enumerator enumerator = param.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; val.CustomAttributes.Add(current.Clone()); } return val; } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } } public static CustomAttribute Relink(this CustomAttribute attrib, Relinker relinker, IGenericParameterProvider context) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown //IL_0034: 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_0043: 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_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: 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_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0120: 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_0137: 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_0145: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(attrib, "attrib"); Helpers.ThrowIfArgumentNull(relinker, "relinker"); CustomAttribute val = new CustomAttribute((MethodReference)attrib.Constructor.Relink(relinker, context)); Enumerator enumerator = attrib.ConstructorArguments.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttributeArgument current = enumerator.Current; val.ConstructorArguments.Add(new CustomAttributeArgument(((CustomAttributeArgument)(ref current)).Type.Relink(relinker, context), ((CustomAttributeArgument)(ref current)).Value)); } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } Enumerator enumerator2 = attrib.Fields.GetEnumerator(); CustomAttributeArgument argument; try { while (enumerator2.MoveNext()) { CustomAttributeNamedArgument current2 = enumerator2.Current; Collection fields = val.Fields; string name = ((CustomAttributeNamedArgument)(ref current2)).Name; argument = ((CustomAttributeNamedArgument)(ref current2)).Argument; TypeReference? obj = ((CustomAttributeArgument)(ref argument)).Type.Relink(relinker, context); argument = ((CustomAttributeNamedArgument)(ref current2)).Argument; fields.Add(new CustomAttributeNamedArgument(name, new CustomAttributeArgument(obj, ((CustomAttributeArgument)(ref argument)).Value))); } } finally { ((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose(); } enumerator2 = attrib.Properties.GetEnumerator(); try { while (enumerator2.MoveNext()) { CustomAttributeNamedArgument current3 = enumerator2.Current; Collection properties = val.Properties; string name2 = ((CustomAttributeNamedArgument)(ref current3)).Name; argument = ((CustomAttributeNamedArgument)(ref current3)).Argument; TypeReference? obj2 = ((CustomAttributeArgument)(ref argument)).Type.Relink(relinker, context); argument = ((CustomAttributeNamedArgument)(ref current3)).Argument; properties.Add(new CustomAttributeNamedArgument(name2, new CustomAttributeArgument(obj2, ((CustomAttributeArgument)(ref argument)).Value))); } return val; } finally { ((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose(); } } public static CustomAttribute Clone(this CustomAttribute attrib) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown //IL_001d: 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) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //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) //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_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_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: 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_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010b: 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_0119: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(attrib, "attrib"); CustomAttribute val = new CustomAttribute(attrib.Constructor); Enumerator enumerator = attrib.ConstructorArguments.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttributeArgument current = enumerator.Current; val.ConstructorArguments.Add(new CustomAttributeArgument(((CustomAttributeArgument)(ref current)).Type, ((CustomAttributeArgument)(ref current)).Value)); } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } Enumerator enumerator2 = attrib.Fields.GetEnumerator(); CustomAttributeArgument argument; try { while (enumerator2.MoveNext()) { CustomAttributeNamedArgument current2 = enumerator2.Current; Collection fields = val.Fields; string name = ((CustomAttributeNamedArgument)(ref current2)).Name; argument = ((CustomAttributeNamedArgument)(ref current2)).Argument; TypeReference type = ((CustomAttributeArgument)(ref argument)).Type; argument = ((CustomAttributeNamedArgument)(ref current2)).Argument; fields.Add(new CustomAttributeNamedArgument(name, new CustomAttributeArgument(type, ((CustomAttributeArgument)(ref argument)).Value))); } } finally { ((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose(); } enumerator2 = attrib.Properties.GetEnumerator(); try { while (enumerator2.MoveNext()) { CustomAttributeNamedArgument current3 = enumerator2.Current; Collection properties = val.Properties; string name2 = ((CustomAttributeNamedArgument)(ref current3)).Name; argument = ((CustomAttributeNamedArgument)(ref current3)).Argument; TypeReference type2 = ((CustomAttributeArgument)(ref argument)).Type; argument = ((CustomAttributeNamedArgument)(ref current3)).Argument; properties.Add(new CustomAttributeNamedArgument(name2, new CustomAttributeArgument(type2, ((CustomAttributeArgument)(ref argument)).Value))); } return val; } finally { ((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose(); } } public static GenericParameter Relink(this GenericParameter param, Relinker relinker, IGenericParameterProvider context) { //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_0029: 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_0044: Expected O, but got Unknown //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_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(param, "param"); Helpers.ThrowIfArgumentNull(relinker, "relinker"); GenericParameter val = Update(new GenericParameter(((MemberReference)param).Name, param.Owner) { Attributes = param.Attributes }, param.Position, param.Type); Enumerator enumerator = param.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; val.CustomAttributes.Add(current.Relink(relinker, context)); } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } Enumerator enumerator2 = param.Constraints.GetEnumerator(); try { while (enumerator2.MoveNext()) { GenericParameterConstraint current2 = enumerator2.Current; val.Constraints.Add(current2.Relink(relinker, context)); } return val; } finally { ((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose(); } } public static GenericParameter Clone(this GenericParameter param) { //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_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_0039: 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_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(param, "param"); GenericParameter val = Update(new GenericParameter(((MemberReference)param).Name, param.Owner) { Attributes = param.Attributes }, param.Position, param.Type); Enumerator enumerator = param.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; val.CustomAttributes.Add(current.Clone()); } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } Enumerator enumerator2 = param.Constraints.GetEnumerator(); try { while (enumerator2.MoveNext()) { GenericParameterConstraint current2 = enumerator2.Current; val.Constraints.Add(current2); } return val; } finally { ((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose(); } } public static int GetManagedSize(this Type t) { if (!Helpers.ThrowIfNull(t, "t").IsByRef && !t.IsPointer) { return _GetManagedSizeCache.GetOrAdd(Helpers.ThrowIfNull(t, "t"), ComputeManagedSize); } return IntPtr.Size; } private static int ComputeManagedSize(Type t) { MethodInfo methodInfo = _GetManagedSizeHelper; if ((object)methodInfo == null) { methodInfo = (_GetManagedSizeHelper = typeof(Unsafe).GetMethod("SizeOf")); } if (t.IsByRef || t.IsPointer || TypeExtensions.IsByRefLike(t)) { return GenerateAndInvokeSizeofHelper(t); } return methodInfo.MakeGenericMethod(t).CreateDelegate>()(); } private static int GenerateAndInvokeSizeofHelper(Type t) { //IL_004d: 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) using DynamicMethodDefinition dynamicMethodDefinition = new DynamicMethodDefinition($"SizeOf<{t}>", typeof(int), Array.Empty()); ILProcessor iLProcessor = dynamicMethodDefinition.GetILProcessor(); iLProcessor.Emit(OpCodes.Sizeof, iLProcessor.Import(t)); iLProcessor.Emit(OpCodes.Ret); return (int)dynamicMethodDefinition.Generate().Invoke(null, null); } public static Type GetThisParamType(this MethodBase method) { Type type = Helpers.ThrowIfNull(method, "method").DeclaringType; if (type.IsValueType) { type = type.MakeByRefType(); } return type; } public static nint GetLdftnPointer(this MethodBase m) { //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(m, "m"); if (_GetLdftnPointerCache.TryGetValue(m, out Func value)) { return value(); } FormatInterpolatedStringHandler handler = new FormatInterpolatedStringHandler(17, 1); handler.AppendLiteral("GetLdftnPointer<"); handler.AppendFormatted(m); handler.AppendLiteral(">"); using DynamicMethodDefinition dynamicMethodDefinition = new DynamicMethodDefinition(DebugFormatter.Format(ref handler), typeof(nint), Type.EmptyTypes); ILProcessor iLProcessor = dynamicMethodDefinition.GetILProcessor(); iLProcessor.Emit(OpCodes.Ldftn, ((MemberReference)dynamicMethodDefinition.Definition).Module.ImportReference(m)); iLProcessor.Emit(OpCodes.Ret); lock (_GetLdftnPointerCache) { Func func = (_GetLdftnPointerCache[m] = dynamicMethodDefinition.Generate().CreateDelegate>()); return func(); } } public static string ToHexadecimalString(this byte[] data) { return BitConverter.ToString(data).Replace("-", string.Empty, StringComparison.Ordinal); } public static T? InvokePassing(this MulticastDelegate md, T val, params object?[] args) { if ((object)md == null) { return val; } Helpers.ThrowIfArgumentNull(args, "args"); object[] array = new object[args.Length + 1]; array[0] = val; Array.Copy(args, 0, array, 1, args.Length); Delegate[] invocationList = md.GetInvocationList(); for (int i = 0; i < invocationList.Length; i++) { array[0] = invocationList[i].DynamicInvoke(array); } return (T)array[0]; } public static bool InvokeWhileTrue(this MulticastDelegate md, params object[] args) { if ((object)md == null) { return true; } Helpers.ThrowIfArgumentNull(args, "args"); Delegate[] invocationList = md.GetInvocationList(); for (int i = 0; i < invocationList.Length; i++) { if (!(bool)invocationList[i].DynamicInvoke(args)) { return false; } } return true; } public static bool InvokeWhileFalse(this MulticastDelegate md, params object[] args) { if ((object)md == null) { return false; } Helpers.ThrowIfArgumentNull(args, "args"); Delegate[] invocationList = md.GetInvocationList(); for (int i = 0; i < invocationList.Length; i++) { if ((bool)invocationList[i].DynamicInvoke(args)) { return true; } } return false; } public static T? InvokeWhileNull(this MulticastDelegate? md, params object[] args) where T : class { if ((object)md == null) { return null; } Helpers.ThrowIfArgumentNull(args, "args"); Delegate[] invocationList = md.GetInvocationList(); for (int i = 0; i < invocationList.Length; i++) { T val = (T)invocationList[i].DynamicInvoke(args); if (val != null) { return val; } } return null; } public static string SpacedPascalCase(this string input) { Helpers.ThrowIfArgumentNull(input, "input"); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < input.Length; i++) { char c = input[i]; if (i > 0 && char.IsUpper(c)) { stringBuilder.Append(' '); } stringBuilder.Append(c); } return stringBuilder.ToString(); } public static string ReadNullTerminatedString(this BinaryReader stream) { Helpers.ThrowIfArgumentNull(stream, "stream"); string text = ""; char c; while ((c = stream.ReadChar()) != 0) { text += c; } return text; } public static void WriteNullTerminatedString(this BinaryWriter stream, string text) { Helpers.ThrowIfArgumentNull(stream, "stream"); Helpers.ThrowIfArgumentNull(text, "text"); if (text != null) { foreach (char ch in text) { stream.Write(ch); } } stream.Write('\0'); } private static MethodBase GetRealMethod(MethodBase method) { if ((object)RTDynamicMethod_m_owner != null && method.GetType() == RTDynamicMethod) { return (MethodBase)RTDynamicMethod_m_owner.GetValue(method); } return method; } public static T CastDelegate(this Delegate source) where T : Delegate { return (T)Helpers.ThrowIfNull(source, "source").CastDelegate(typeof(T)); } [return: NotNullIfNotNull("source")] public static Delegate? CastDelegate(this Delegate? source, Type type) { if ((object)source == null) { return null; } Helpers.ThrowIfArgumentNull(type, "type"); if (type.IsAssignableFrom(source.GetType())) { return source; } Delegate[] invocationList = source.GetInvocationList(); if (invocationList.Length == 1) { return GetRealMethod(invocationList[0].Method).CreateDelegate(type, invocationList[0].Target); } Delegate[] array = new Delegate[invocationList.Length]; for (int i = 0; i < invocationList.Length; i++) { array[i] = GetRealMethod(invocationList[i].Method).CreateDelegate(type, invocationList[i].Target); } return Delegate.Combine(array); } public static bool TryCastDelegate(this Delegate source, [MaybeNullWhen(false)] out T result) where T : Delegate { if ((object)source == null) { result = null; return false; } if (source is T val) { result = val; return true; } Delegate result3; bool result2 = source.TryCastDelegate(typeof(T), out result3); result = (T)result3; return result2; } public static bool TryCastDelegate(this Delegate source, Type type, [MaybeNullWhen(false)] out Delegate? result) { result = null; if ((object)source == null) { return false; } try { result = source.CastDelegate(type); return true; } catch (Exception value) { bool isEnabled; MMDbgLog.DebugLogWarningStringHandler message = new MMDbgLog.DebugLogWarningStringHandler(43, 3, out isEnabled); if (isEnabled) { message.AppendLiteral("Exception thrown in TryCastDelegate("); message.AppendFormatted(source.GetType()); message.AppendLiteral(" -> "); message.AppendFormatted(type); message.AppendLiteral("): "); message.AppendFormatted(value); } MMDbgLog.Warning(ref message); return false; } } public static MethodInfo? GetStateMachineTarget(this MethodInfo method) { if ((object)p_StateMachineType == null || (object)t_StateMachineAttribute == null) { return null; } Helpers.ThrowIfArgumentNull(method, "method"); object[] customAttributes = method.GetCustomAttributes(inherit: false); for (int i = 0; i < customAttributes.Length; i++) { Attribute attribute = (Attribute)customAttributes[i]; if (t_StateMachineAttribute.IsCompatible(attribute.GetType())) { return (p_StateMachineType.GetValue(attribute, null) as Type)?.GetMethod("MoveNext", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } } return null; } public static MethodBase GetActualGenericMethodDefinition(this MethodInfo method) { Helpers.ThrowIfArgumentNull(method, "method"); return (method.IsGenericMethod ? method.GetGenericMethodDefinition() : method).GetUnfilledMethodOnGenericType(); } public static MethodBase GetUnfilledMethodOnGenericType(this MethodBase method) { Helpers.ThrowIfArgumentNull(method, "method"); if (method.DeclaringType != null && method.DeclaringType.IsGenericType) { Type genericTypeDefinition = method.DeclaringType.GetGenericTypeDefinition(); method = MethodBase.GetMethodFromHandle(method.MethodHandle, genericTypeDefinition.TypeHandle); } return method; } public static bool Is(this MemberReference member, string fullName) { Helpers.ThrowIfArgumentNull(fullName, "fullName"); if (member == null) { return false; } return member.FullName.Replace("+", "/", StringComparison.Ordinal) == fullName.Replace("+", "/", StringComparison.Ordinal); } public static bool Is(this MemberReference member, string typeFullName, string name) { Helpers.ThrowIfArgumentNull(typeFullName, "typeFullName"); Helpers.ThrowIfArgumentNull(name, "name"); if (member == null) { return false; } if (((MemberReference)member.DeclaringType).FullName.Replace("+", "/", StringComparison.Ordinal) == typeFullName.Replace("+", "/", StringComparison.Ordinal)) { return member.Name == name; } return false; } public static bool Is(this MemberReference member, Type type, string name) { Helpers.ThrowIfArgumentNull(type, "type"); Helpers.ThrowIfArgumentNull(name, "name"); if (member == null) { return false; } if (((MemberReference)member.DeclaringType).FullName.Replace("+", "/", StringComparison.Ordinal) == type.FullName?.Replace("+", "/", StringComparison.Ordinal)) { return member.Name == name; } return false; } public static bool Is(this MethodReference method, string fullName) { Helpers.ThrowIfArgumentNull(fullName, "fullName"); if (method == null) { return false; } if (fullName.Contains(' ', StringComparison.Ordinal)) { if (method.GetID(null, null, withType: true, simple: true).Replace("+", "/", StringComparison.Ordinal) == fullName.Replace("+", "/", StringComparison.Ordinal)) { return true; } if (method.GetID().Replace("+", "/", StringComparison.Ordinal) == fullName.Replace("+", "/", StringComparison.Ordinal)) { return true; } } return ((MemberReference)method).FullName.Replace("+", "/", StringComparison.Ordinal) == fullName.Replace("+", "/", StringComparison.Ordinal); } public static bool Is(this MethodReference method, string typeFullName, string name) { Helpers.ThrowIfArgumentNull(typeFullName, "typeFullName"); Helpers.ThrowIfArgumentNull(name, "name"); if (method == null) { return false; } if (name.Contains(' ', StringComparison.Ordinal) && ((MemberReference)((MemberReference)method).DeclaringType).FullName.Replace("+", "/", StringComparison.Ordinal) == typeFullName.Replace("+", "/", StringComparison.Ordinal) && method.GetID(null, null, withType: false).Replace("+", "/", StringComparison.Ordinal) == name.Replace("+", "/", StringComparison.Ordinal)) { return true; } if (((MemberReference)((MemberReference)method).DeclaringType).FullName.Replace("+", "/", StringComparison.Ordinal) == typeFullName.Replace("+", "/", StringComparison.Ordinal)) { return ((MemberReference)method).Name == name; } return false; } public static bool Is(this MethodReference method, Type type, string name) { Helpers.ThrowIfArgumentNull(type, "type"); Helpers.ThrowIfArgumentNull(name, "name"); if (method == null) { return false; } if (name.Contains(' ', StringComparison.Ordinal) && ((MemberReference)((MemberReference)method).DeclaringType).FullName.Replace("+", "/", StringComparison.Ordinal) == type.FullName?.Replace("+", "/", StringComparison.Ordinal) && method.GetID(null, null, withType: false).Replace("+", "/", StringComparison.Ordinal) == name.Replace("+", "/", StringComparison.Ordinal)) { return true; } if (((MemberReference)((MemberReference)method).DeclaringType).FullName.Replace("+", "/", StringComparison.Ordinal) == type.FullName?.Replace("+", "/", StringComparison.Ordinal)) { return ((MemberReference)method).Name == name; } return false; } public static void ReplaceOperands(this ILProcessor il, object? from, object? to) { //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) Helpers.ThrowIfArgumentNull(il, "il"); Enumerator enumerator = il.Body.Instructions.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current = enumerator.Current; if (current.Operand?.Equals(from) ?? (from == null)) { current.Operand = to; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } } public static FieldReference Import(this ILProcessor il, FieldInfo field) { return ((MemberReference)Helpers.ThrowIfNull(il, "il").Body.Method).Module.ImportReference(field); } public static MethodReference Import(this ILProcessor il, MethodBase method) { return ((MemberReference)Helpers.ThrowIfNull(il, "il").Body.Method).Module.ImportReference(method); } public static TypeReference Import(this ILProcessor il, Type type) { return ((MemberReference)Helpers.ThrowIfNull(il, "il").Body.Method).Module.ImportReference(type); } public static MemberReference Import(this ILProcessor il, MemberInfo member) { Helpers.ThrowIfArgumentNull(il, "il"); Helpers.ThrowIfArgumentNull(member, "member"); if (!(member is FieldInfo field)) { if (!(member is MethodBase method)) { if (member is Type type) { return (MemberReference)(object)il.Import(type); } throw new NotSupportedException("Unsupported member type " + member.GetType().FullName); } return (MemberReference)(object)il.Import(method); } return (MemberReference)(object)il.Import(field); } public static Instruction Create(this ILProcessor il, OpCode opcode, FieldInfo field) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(il, "il").Create(opcode, il.Import(field)); } public static Instruction Create(this ILProcessor il, OpCode opcode, MethodBase method) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(il, "il"); return il.Create(opcode, il.Import(method)); } public static Instruction Create(this ILProcessor il, OpCode opcode, Type type) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) return Helpers.ThrowIfNull(il, "il").Create(opcode, il.Import(type)); } public static Instruction Create(this ILProcessor il, OpCode opcode, object operand) { //IL_000b: 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) Instruction obj = Helpers.ThrowIfNull(il, "il").Create(OpCodes.Nop); obj.OpCode = opcode; obj.Operand = operand; return obj; } public static Instruction Create(this ILProcessor il, OpCode opcode, MemberInfo member) { //IL_0037: 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_0049: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(il, "il"); Helpers.ThrowIfArgumentNull(member, "member"); if (!(member is FieldInfo field)) { if (!(member is MethodBase method)) { if (member is Type type) { return il.Create(opcode, type); } throw new NotSupportedException("Unsupported member type " + member.GetType().FullName); } return il.Create(opcode, method); } return il.Create(opcode, field); } public static void Emit(this ILProcessor il, OpCode opcode, FieldInfo field) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfNull(il, "il").Emit(opcode, il.Import(field)); } public static void Emit(this ILProcessor il, OpCode opcode, MethodBase method) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(il, "il"); Helpers.ThrowIfArgumentNull(method, "method"); il.Emit(opcode, il.Import(method)); } public static void Emit(this ILProcessor il, OpCode opcode, Type type) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfNull(il, "il").Emit(opcode, il.Import(type)); } public static void Emit(this ILProcessor il, OpCode opcode, MemberInfo member) { //IL_0037: 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_0049: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(il, "il"); Helpers.ThrowIfArgumentNull(member, "member"); if (!(member is FieldInfo field)) { if (!(member is MethodBase method)) { if (!(member is Type type)) { throw new NotSupportedException("Unsupported member type " + member.GetType().FullName); } il.Emit(opcode, type); } else { il.Emit(opcode, method); } } else { il.Emit(opcode, field); } } public static void Emit(this ILProcessor il, OpCode opcode, object operand) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfNull(il, "il").Append(il.Create(opcode, operand)); } } public delegate IMetadataTokenProvider Relinker(IMetadataTokenProvider mtp, IGenericParameterProvider? context); public sealed class WeakBox { public object? Value; } public static class FastReflectionHelper { public delegate object? FastInvoker(object? target, params object?[]? args); public delegate void FastStructInvoker(object? target, object? result, params object?[]? args); private static class TypedCache where T : struct { [ThreadStatic] public static StrongBox? NullableStrongBox; } private enum ReturnTypeClass { Void, ValueType, Nullable, ReferenceType } private sealed class FSITuple { public readonly FastStructInvoker FSI; public readonly ReturnTypeClass RTC; public readonly Type ReturnType; public FSITuple(FastStructInvoker fsi, ReturnTypeClass rtc, Type rt) { FSI = fsi; RTC = rtc; ReturnType = rt; } } private static readonly Type[] FastStructInvokerArgs = new Type[3] { typeof(object), typeof(object), typeof(object[]) }; private static readonly MethodInfo S2FValueType = typeof(FastReflectionHelper).GetMethod("FastInvokerForStructInvokerVT", BindingFlags.Static | BindingFlags.NonPublic); private static readonly MethodInfo S2FNullable = typeof(FastReflectionHelper).GetMethod("FastInvokerForStructInvokerNullable", BindingFlags.Static | BindingFlags.NonPublic); [ThreadStatic] private static WeakBox? CachedWeakBox; private static readonly MethodInfo S2FClass = typeof(FastReflectionHelper).GetMethod("FastInvokerForStructInvokerClass", BindingFlags.Static | BindingFlags.NonPublic); private static readonly MethodInfo S2FVoid = typeof(FastReflectionHelper).GetMethod("FastInvokerForStructInvokerVoid", BindingFlags.Static | BindingFlags.NonPublic); private static ConditionalWeakTable fastStructInvokers = new ConditionalWeakTable(); private static ConditionalWeakTable fastInvokers = new ConditionalWeakTable(); private static readonly MethodInfo CheckArgsMethod = typeof(FastReflectionHelper).GetMethod("CheckArgs", BindingFlags.Static | BindingFlags.NonPublic); private const int TargetArgId = -1; private const int ResultArgId = -2; private static readonly MethodInfo BadArgExceptionMethod = typeof(FastReflectionHelper).GetMethod("BadArgException", BindingFlags.Static | BindingFlags.NonPublic); private static readonly FieldInfo WeakBoxValueField = typeof(WeakBox).GetField("Value"); private static object? FastInvokerForStructInvokerVT(FastStructInvoker invoker, object? target, params object?[]? args) where T : struct { object result = default(T); invoker(target, result, args); return result; } private static object? FastInvokerForStructInvokerNullable(FastStructInvoker invoker, object? target, params object?[]? args) where T : struct { StrongBox strongBox = TypedCache.NullableStrongBox ?? (TypedCache.NullableStrongBox = new StrongBox(null)); invoker(target, strongBox, args); return strongBox.Value; } private static object? FastInvokerForStructInvokerClass(FastStructInvoker invoker, object? target, params object?[]? args) { WeakBox weakBox = CachedWeakBox ?? (CachedWeakBox = new WeakBox()); invoker(target, weakBox, args); return weakBox.Value; } private static object? FastInvokerForStructInvokerVoid(FastStructInvoker invoker, object? target, params object?[]? args) { invoker(target, null, args); return null; } private static FastInvoker CreateFastInvoker(FastStructInvoker fsi, ReturnTypeClass retTypeClass, Type returnType) { return retTypeClass switch { ReturnTypeClass.Void => S2FVoid.CreateDelegate(fsi), ReturnTypeClass.ValueType => S2FValueType.MakeGenericMethod(returnType).CreateDelegate(fsi), ReturnTypeClass.Nullable => S2FNullable.MakeGenericMethod(Nullable.GetUnderlyingType(returnType)).CreateDelegate(fsi), ReturnTypeClass.ReferenceType => S2FClass.CreateDelegate(fsi), _ => throw new NotImplementedException($"Invalid ReturnTypeClass {retTypeClass}"), }; } private static FSITuple GetFSITuple(MethodBase method) { ReturnTypeClass retTypeClass; Type retType; return fastStructInvokers.GetValue(method, (MemberInfo _) => new FSITuple(CreateMethodInvoker(method, out retTypeClass, out retType), retTypeClass, retType)); } private static FSITuple GetFSITuple(FieldInfo field) { ReturnTypeClass retTypeClass; Type retType; return fastStructInvokers.GetValue(field, (MemberInfo _) => new FSITuple(CreateFieldInvoker(field, out retTypeClass, out retType), retTypeClass, retType)); } private static FSITuple GetFSITuple(MemberInfo member) { if (!(member is MethodBase method)) { if (member is FieldInfo field) { return GetFSITuple(field); } throw new NotSupportedException($"Member type {member.GetType()} is not supported"); } return GetFSITuple(method); } private static FastInvoker GetFastInvoker(FSITuple tuple) { return fastInvokers.GetValue(tuple, (FSITuple t) => CreateFastInvoker(t.FSI, t.RTC, t.ReturnType)); } public static FastStructInvoker GetFastStructInvoker(MethodBase method) { return GetFSITuple(method).FSI; } public static FastStructInvoker GetFastStructInvoker(FieldInfo field) { return GetFSITuple(field).FSI; } public static FastStructInvoker GetFastStructInvoker(MemberInfo member) { return GetFSITuple(member).FSI; } public static FastInvoker GetFastInvoker(this MethodBase method) { return GetFastInvoker(GetFSITuple(method)); } public static FastInvoker GetFastInvoker(this FieldInfo field) { return GetFastInvoker(GetFSITuple(field)); } public static FastInvoker GetFastInvoker(this MemberInfo member) { return GetFastInvoker(GetFSITuple(member)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void CheckArgs(bool isStatic, object? target, int retTypeClass, object? result, int expectLen, object?[]? args) { if (!isStatic) { Helpers.ThrowIfArgumentNull(target, "target"); } if (retTypeClass != 0 && (uint)(retTypeClass - 1) <= 2u) { Helpers.ThrowIfArgumentNull(result, "result"); } if (expectLen != 0) { Helpers.ThrowIfArgumentNull(args, "args"); if (args.Length < expectLen) { ThrowArgumentOutOfRange(); } } [MethodImpl(MethodImplOptions.NoInlining)] static void ThrowArgumentOutOfRange() { throw new ArgumentOutOfRangeException("args", "Argument array has too few arguments!"); } } private static Exception BadArgException(int arg, RuntimeTypeHandle expectType, object? target, object? result, object?[] args) { Type typeFromHandle = Type.GetTypeFromHandle(expectType); Type type = arg switch { -1 => target?.GetType(), -2 => result?.GetType(), _ => args[arg]?.GetType(), }; string text; switch (arg) { case -1: text = "target"; break; case -2: text = "result"; break; default: { FormatInterpolatedStringHandler handler = new FormatInterpolatedStringHandler(6, 1); handler.AppendLiteral("args["); handler.AppendFormatted(arg); handler.AppendLiteral("]"); text = DebugFormatter.Format(ref handler); break; } } string paramName = text; if ((object)type == null) { return new ArgumentNullException(paramName); } switch (arg) { case -1: { FormatInterpolatedStringHandler handler4 = new FormatInterpolatedStringHandler(48, 2); handler4.AppendLiteral("Target object is the wrong type; expected "); handler4.AppendFormatted(typeFromHandle); handler4.AppendLiteral(", got "); handler4.AppendFormatted(type); text = DebugFormatter.Format(ref handler4); break; } case -2: { FormatInterpolatedStringHandler handler3 = new FormatInterpolatedStringHandler(48, 2); handler3.AppendLiteral("Result object is the wrong type; expected "); handler3.AppendFormatted(typeFromHandle); handler3.AppendLiteral(", got "); handler3.AppendFormatted(type); text = DebugFormatter.Format(ref handler3); break; } default: { FormatInterpolatedStringHandler handler2 = new FormatInterpolatedStringHandler(44, 3); handler2.AppendLiteral("Argument "); handler2.AppendFormatted(arg); handler2.AppendLiteral(" is the wrong type; expected "); handler2.AppendFormatted(typeFromHandle); handler2.AppendLiteral(", got "); handler2.AppendFormatted(type); text = DebugFormatter.Format(ref handler2); break; } } return new ArgumentException(text, paramName); } private static ReturnTypeClass ClassifyType(Type returnType) { if (returnType == typeof(void)) { return ReturnTypeClass.Void; } if (returnType.IsValueType) { if ((object)Nullable.GetUnderlyingType(returnType) != null) { return ReturnTypeClass.Nullable; } return ReturnTypeClass.ValueType; } return ReturnTypeClass.ReferenceType; } private static void EmitCheckArgs(ILCursor il, bool isStatic, ReturnTypeClass rtc, int expectParams) { //IL_0001: 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_001d: 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_0036: 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_004f: Unknown result type (might be due to invalid IL or missing references) il.Emit(OpCodes.Ldc_I4, isStatic ? 1 : 0); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldc_I4, (int)rtc); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Ldc_I4, expectParams); il.Emit(OpCodes.Ldarg_2); il.Emit(OpCodes.Call, (MethodBase)CheckArgsMethod); } private static void EmitCheckType(ILCursor il, int argId, Type expectType, ILLabel badArgLbl) { //IL_00cf: 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_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: 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_0046: Expected O, but got Unknown //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_006a: 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_008c: Unknown result type (might be due to invalid IL or missing references) ILLabel iLLabel = il.DefineLabel(); bool isByRef = expectType.IsByRef; VariableDefinition val = null; if (isByRef) { expectType = expectType.GetElementType() ?? expectType; ReturnTypeClass rtc = ClassifyType(expectType); if (!expectType.IsValueType) { val = new VariableDefinition(il.Module.TypeSystem.Object); il.Context.Body.Variables.Add(val); il.Emit(OpCodes.Stloc, val); il.Emit(OpCodes.Ldloc, val); } EmitCheckByref(il, rtc, expectType, badArgLbl, argId); if (expectType.IsValueType) { return; } if (val != null) { il.Emit(OpCodes.Ldloc, val); } EmitLoadByref(il, rtc, expectType); il.Emit(OpCodes.Ldind_Ref); } if (expectType != typeof(object)) { il.Emit(OpCodes.Isinst, expectType); } il.Emit(OpCodes.Brtrue, (object)iLLabel); il.Emit(OpCodes.Ldc_I4, argId); il.Emit(OpCodes.Ldtoken, expectType); il.Emit(OpCodes.Br, (object)badArgLbl); il.MarkLabel(iLLabel); } private static void EmitCheckAllowNull(ILCursor il, int argId, Type expectType, ILLabel badArgLbl) { //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Expected O, but got Unknown //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_0159: 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_0048: Expected O, but got Unknown //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) ILLabel iLLabel = il.DefineLabel(); bool isByRef = expectType.IsByRef; VariableDefinition val = null; if (isByRef) { expectType = expectType.GetElementType() ?? expectType; ReturnTypeClass rtc = ClassifyType(expectType); if (!expectType.IsValueType) { val = new VariableDefinition(il.Module.TypeSystem.Object); il.Context.Body.Variables.Add(val); il.Emit(OpCodes.Stloc, val); il.Emit(OpCodes.Ldloc, val); } EmitCheckByref(il, rtc, expectType, badArgLbl, argId); if (expectType.IsValueType) { return; } if (val != null) { il.Emit(OpCodes.Ldloc, val); } EmitLoadByref(il, rtc, expectType); il.Emit(OpCodes.Ldind_Ref); } if (expectType == typeof(object)) { il.Emit(OpCodes.Pop); return; } if (!expectType.IsValueType || (object)Nullable.GetUnderlyingType(expectType) != null) { ILLabel iLLabel2 = il.DefineLabel(); VariableDefinition val2 = new VariableDefinition(il.Module.TypeSystem.Object); il.Context.Body.Variables.Add(val2); il.Emit(OpCodes.Stloc, val2); il.Emit(OpCodes.Ldloc, val2); il.Emit(OpCodes.Brtrue, (object)iLLabel2); il.Emit(OpCodes.Br, (object)iLLabel); il.MarkLabel(iLLabel2); il.Emit(OpCodes.Ldloc, val2); } if (!expectType.IsValueType || (!isByRef && expectType.IsValueType)) { EmitCheckType(il, argId, expectType, badArgLbl); } il.MarkLabel(iLLabel); } private static void EmitBadArgCall(ILCursor il, ILLabel badArgLbl) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002c: 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.MarkLabel(badArgLbl); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Ldarg_2); il.Emit(OpCodes.Call, (MethodBase)BadArgExceptionMethod); il.Emit(OpCodes.Throw); } private static void EmitCheckByref(ILCursor il, ReturnTypeClass rtc, Type returnType, ILLabel badArgLbl, int argId = -2) { Type expectType; switch (rtc) { default: return; case ReturnTypeClass.ValueType: expectType = returnType; break; case ReturnTypeClass.Nullable: expectType = typeof(StrongBox<>).MakeGenericType(returnType); break; case ReturnTypeClass.ReferenceType: expectType = typeof(WeakBox); break; case ReturnTypeClass.Void: return; } EmitCheckType(il, argId, expectType, badArgLbl); } private static void EmitLoadByref(ILCursor il, ReturnTypeClass rtc, Type returnType) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_004a: 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) switch (rtc) { case ReturnTypeClass.ValueType: il.Emit(OpCodes.Unbox, returnType); break; case ReturnTypeClass.Nullable: { FieldInfo field = typeof(StrongBox<>).MakeGenericType(returnType).GetField("Value"); il.Emit(OpCodes.Ldflda, field); break; } case ReturnTypeClass.ReferenceType: il.Emit(OpCodes.Ldflda, WeakBoxValueField); break; case ReturnTypeClass.Void: break; } } private static void EmitLoadArgO(ILCursor il, int arg) { //IL_0001: 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_001a: Unknown result type (might be due to invalid IL or missing references) il.Emit(OpCodes.Ldarg_2); il.Emit(OpCodes.Ldc_I4, arg); il.Emit(OpCodes.Ldelem_Ref); } private static void EmitStoreByref(ILCursor il, ReturnTypeClass rtc, Type returnType) { //IL_001a: 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) if (rtc != ReturnTypeClass.Void) { if (returnType.IsValueType) { il.Emit(OpCodes.Stobj, returnType); } else { il.Emit(OpCodes.Stind_Ref); } } } private static FastStructInvoker CreateMethodInvoker(MethodBase method, out ReturnTypeClass retTypeClass, out Type retType) { if (!method.IsStatic) { Type? declaringType = method.DeclaringType; if ((object)declaringType != null && TypeExtensions.IsByRefLike(declaringType)) { throw new ArgumentException("Cannot create reflection invoker for instance method on byref-like type", "method"); } } Type returnType = ((method is MethodInfo methodInfo) ? methodInfo.ReturnType : method.DeclaringType); retType = returnType; if (returnType.IsByRef || TypeExtensions.IsByRefLike(returnType)) { throw new ArgumentException("Cannot create reflection invoker for method with byref or byref-like return type", "method"); } retTypeClass = ClassifyType(returnType); ReturnTypeClass typeClass = retTypeClass; ParameterInfo[] methParams = method.GetParameters(); FormatInterpolatedStringHandler handler = new FormatInterpolatedStringHandler(22, 1); handler.AppendLiteral("MM:FastStructInvoker<"); handler.AppendFormatted(method); handler.AppendLiteral(">"); using DynamicMethodDefinition dynamicMethodDefinition = new DynamicMethodDefinition(DebugFormatter.Format(ref handler), null, FastStructInvokerArgs); using ILContext iLContext = new ILContext(dynamicMethodDefinition.Definition); iLContext.Invoke(delegate(ILContext ilc) { //IL_0093: 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_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_0235: Unknown result type (might be due to invalid IL or missing references) //IL_026d: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) ILCursor iLCursor = new ILCursor(ilc); EmitCheckArgs(iLCursor, method.IsStatic || method is ConstructorInfo, typeClass, methParams.Length); ILLabel badArgLbl = iLCursor.DefineLabel(); if (!method.IsStatic && !(method is ConstructorInfo)) { Type declaringType2 = method.DeclaringType; Helpers.Assert((object)declaringType2 != null, null, "expectType is not null"); iLCursor.Emit(OpCodes.Ldarg_0); EmitCheckType(iLCursor, -1, declaringType2, badArgLbl); } if (typeClass != ReturnTypeClass.Void) { iLCursor.Emit(OpCodes.Ldarg_1); EmitCheckByref(iLCursor, typeClass, returnType, badArgLbl); } for (int i = 0; i < methParams.Length; i++) { Type parameterType = methParams[i].ParameterType; if (TypeExtensions.IsByRefLike(parameterType)) { throw new ArgumentException("Cannot create reflection invoker for method with byref-like argument types", "method"); } EmitLoadArgO(iLCursor, i); EmitCheckAllowNull(iLCursor, i, parameterType, badArgLbl); } if (typeClass != ReturnTypeClass.Void) { iLCursor.Emit(OpCodes.Ldarg_1); EmitLoadByref(iLCursor, typeClass, returnType); } if (!method.IsStatic && !(method is ConstructorInfo)) { Type declaringType3 = method.DeclaringType; Helpers.Assert((object)declaringType3 != null, null, "declType is not null"); iLCursor.Emit(OpCodes.Ldarg_0); if (declaringType3.IsValueType) { iLCursor.Emit(OpCodes.Unbox, declaringType3); } } for (int j = 0; j < methParams.Length; j++) { iLCursor.DefineLabel(); Type parameterType2 = methParams[j].ParameterType; Type type = (parameterType2.IsByRef ? (parameterType2.GetElementType() ?? parameterType2) : parameterType2); EmitLoadArgO(iLCursor, j); if (parameterType2.IsByRef) { EmitLoadByref(iLCursor, ClassifyType(type), type); } else if (parameterType2.IsValueType) { iLCursor.Emit(OpCodes.Unbox_Any, type); } } if (method is ConstructorInfo method2) { iLCursor.Emit(OpCodes.Newobj, (MethodBase)method2); } else if (method.IsVirtual) { iLCursor.Emit(OpCodes.Callvirt, method); } else { iLCursor.Emit(OpCodes.Call, method); } EmitStoreByref(iLCursor, typeClass, returnType); iLCursor.Emit(OpCodes.Ret); EmitBadArgCall(iLCursor, badArgLbl); }); return dynamicMethodDefinition.Generate().CreateDelegate(); } private static FastStructInvoker CreateFieldInvoker(FieldInfo field, out ReturnTypeClass retTypeClass, out Type retType) { if (!field.IsStatic) { Type? declaringType = field.DeclaringType; if ((object)declaringType != null && TypeExtensions.IsByRefLike(declaringType)) { throw new ArgumentException("Cannot create reflection invoker for instance field on byref-like type", "field"); } } Type returnType = field.FieldType; retType = returnType; retTypeClass = ClassifyType(returnType); ReturnTypeClass typeClass = retTypeClass; FormatInterpolatedStringHandler handler = new FormatInterpolatedStringHandler(22, 1); handler.AppendLiteral("MM:FastStructInvoker<"); handler.AppendFormatted(field); handler.AppendLiteral(">"); using DynamicMethodDefinition dynamicMethodDefinition = new DynamicMethodDefinition(DebugFormatter.Format(ref handler), null, FastStructInvokerArgs); using ILContext iLContext = new ILContext(dynamicMethodDefinition.Definition); iLContext.Invoke(delegate(ILContext ilc) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0089: 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_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: 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) //IL_0040: 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_0129: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_01e0: Unknown result type (might be due to invalid IL or missing references) //IL_0228: 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_0258: Unknown result type (might be due to invalid IL or missing references) //IL_023d: Unknown result type (might be due to invalid IL or missing references) //IL_0290: Unknown result type (might be due to invalid IL or missing references) ILCursor iLCursor = new ILCursor(ilc); EmitCheckArgs(iLCursor, field.IsStatic, typeClass, 0); ILLabel badArgLbl = iLCursor.DefineLabel(); if (!field.IsStatic) { Type declaringType2 = field.DeclaringType; iLCursor.Emit(OpCodes.Ldarg_0); EmitCheckType(iLCursor, -1, declaringType2, badArgLbl); } iLCursor.Emit(OpCodes.Ldarg_1); EmitCheckByref(iLCursor, typeClass, returnType, badArgLbl); ILLabel iLLabel = iLCursor.DefineLabel(); iLCursor.Emit(OpCodes.Ldarg_2); iLCursor.Emit(OpCodes.Brfalse, (object)iLLabel); iLCursor.Emit(OpCodes.Ldarg_2); iLCursor.Emit(OpCodes.Ldlen); iLCursor.Emit(OpCodes.Ldc_I4_1); iLCursor.Emit(OpCodes.Blt, (object)iLLabel); EmitLoadArgO(iLCursor, 0); EmitCheckAllowNull(iLCursor, 0, field.FieldType, badArgLbl); iLCursor.Emit(OpCodes.Ldarg_1); EmitLoadByref(iLCursor, typeClass, returnType); if (!field.IsStatic) { Type declaringType3 = field.DeclaringType; Helpers.Assert((object)declaringType3 != null, null, "declType is not null"); iLCursor.Emit(OpCodes.Ldarg_0); if (declaringType3.IsValueType) { iLCursor.Emit(OpCodes.Unbox, declaringType3); } } EmitLoadArgO(iLCursor, 0); iLCursor.Emit(OpCodes.Unbox_Any, field.FieldType); if (field.IsStatic) { iLCursor.Emit(OpCodes.Stsfld, field); } else { iLCursor.Emit(OpCodes.Stfld, field); } EmitLoadArgO(iLCursor, 0); iLCursor.Emit(OpCodes.Unbox_Any, field.FieldType); EmitStoreByref(iLCursor, typeClass, returnType); iLCursor.Emit(OpCodes.Ret); iLCursor.MarkLabel(iLLabel); iLCursor.Emit(OpCodes.Ldarg_1); EmitLoadByref(iLCursor, typeClass, returnType); if (!field.IsStatic) { Type declaringType4 = field.DeclaringType; Helpers.Assert((object)declaringType4 != null, null, "declType is not null"); iLCursor.Emit(OpCodes.Ldarg_0); if (declaringType4.IsValueType) { iLCursor.Emit(OpCodes.Unbox, declaringType4); } } if (field.IsStatic) { iLCursor.Emit(OpCodes.Ldsfld, field); } else { iLCursor.Emit(OpCodes.Ldfld, field); } EmitStoreByref(iLCursor, typeClass, returnType); iLCursor.Emit(OpCodes.Ret); EmitBadArgCall(iLCursor, badArgLbl); }); return dynamicMethodDefinition.Generate().CreateDelegate(); } } public class GenericMethodInstantiationComparer : IEqualityComparer { internal static Type? CannonicalFillType = typeof(object).Assembly.GetType("System.__Canon"); private readonly IEqualityComparer genericTypeComparer; public GenericMethodInstantiationComparer() : this(new GenericTypeInstantiationComparer()) { } public GenericMethodInstantiationComparer(IEqualityComparer typeComparer) { genericTypeComparer = typeComparer; } public bool Equals(MethodBase? x, MethodBase? y) { if ((object)x == null && (object)y == null) { return true; } if ((object)x == null || (object)y == null) { return false; } bool flag = (x.IsGenericMethod && !x.ContainsGenericParameters) || (x.DeclaringType?.IsGenericType ?? false); bool flag2 = (y.IsGenericMethod && !y.ContainsGenericParameters) || (y.DeclaringType?.IsGenericType ?? false); if (flag != flag2) { return false; } if (!flag) { return x.Equals(y); } if (!genericTypeComparer.Equals(x.DeclaringType, y.DeclaringType)) { return false; } MethodBase methodBase = ((!(x is MethodInfo method)) ? x.GetUnfilledMethodOnGenericType() : method.GetActualGenericMethodDefinition()); MethodBase methodBase2 = ((!(y is MethodInfo method2)) ? y.GetUnfilledMethodOnGenericType() : method2.GetActualGenericMethodDefinition()); if (!methodBase.Equals(methodBase2)) { return false; } if (methodBase.Name != methodBase2.Name) { return false; } ParameterInfo[] parameters = x.GetParameters(); ParameterInfo[] parameters2 = y.GetParameters(); if (parameters.Length != parameters2.Length) { return false; } ParameterInfo[] parameters3 = methodBase.GetParameters(); for (int i = 0; i < parameters.Length; i++) { Type type = parameters[i].ParameterType; Type type2 = parameters2[i].ParameterType; if (parameters3[i].ParameterType.IsGenericParameter) { if (!type.IsValueType) { type = CannonicalFillType ?? typeof(object); } if (!type2.IsValueType) { type2 = CannonicalFillType ?? typeof(object); } } if (!genericTypeComparer.Equals(type, type2)) { return false; } } return true; } public int GetHashCode(MethodBase obj) { Helpers.ThrowIfArgumentNull(obj, "obj"); if (!obj.IsGenericMethod || obj.ContainsGenericParameters) { Type? declaringType = obj.DeclaringType; if ((object)declaringType == null || !declaringType.IsGenericType) { return obj.GetHashCode(); } } int num = -559038737; if (obj.DeclaringType != null) { num ^= obj.DeclaringType.Assembly.GetHashCode(); num ^= genericTypeComparer.GetHashCode(obj.DeclaringType); } num ^= obj.Name.GetHashCode(StringComparison.Ordinal); ParameterInfo[] parameters = obj.GetParameters(); int num2 = parameters.Length; num2 ^= num2 << 4; num2 ^= num2 << 8; num2 ^= num2 << 16; num ^= num2; if (obj.IsGenericMethod) { Type[] genericArguments = obj.GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { int num3 = i % 32; Type type = genericArguments[i]; int num4 = (type.IsValueType ? genericTypeComparer.GetHashCode(type) : (CannonicalFillType?.GetHashCode() ?? 1431655765)); num4 = (num4 << num3) | (num4 >> 32 - num3); num ^= num4; } } MethodBase methodBase = ((!(obj is MethodInfo method)) ? obj.GetUnfilledMethodOnGenericType() : method.GetActualGenericMethodDefinition()); ParameterInfo[] parameters2 = methodBase.GetParameters(); for (int j = 0; j < parameters.Length; j++) { int num5 = j % 32; Type parameterType = parameters[j].ParameterType; int num6 = genericTypeComparer.GetHashCode(parameterType); if (parameters2[j].ParameterType.IsGenericParameter && !parameterType.IsValueType) { num6 = CannonicalFillType?.GetHashCode() ?? 1431655765; } num6 = (num6 >> num5) | (num6 << 32 - num5); num ^= num6; } return num; } } public class GenericTypeInstantiationComparer : IEqualityComparer { private static Type? CannonicalFillType = GenericMethodInstantiationComparer.CannonicalFillType; public bool Equals(Type? x, Type? y) { if ((object)x == null && (object)y == null) { return true; } if ((object)x == null || (object)y == null) { return false; } bool isGenericType = x.IsGenericType; bool isGenericType2 = y.IsGenericType; if (isGenericType != isGenericType2) { return false; } if (!isGenericType) { return x.Equals(y); } Type genericTypeDefinition = x.GetGenericTypeDefinition(); Type genericTypeDefinition2 = y.GetGenericTypeDefinition(); if (!genericTypeDefinition.Equals(genericTypeDefinition2)) { return false; } Type[] genericArguments = x.GetGenericArguments(); Type[] genericArguments2 = y.GetGenericArguments(); if (genericArguments.Length != genericArguments2.Length) { return false; } for (int i = 0; i < genericArguments.Length; i++) { Type type = genericArguments[i]; Type type2 = genericArguments2[i]; if (!type.IsValueType) { type = CannonicalFillType ?? typeof(object); } if (!type2.IsValueType) { type2 = CannonicalFillType ?? typeof(object); } if (!Equals(type, type2)) { return false; } } return true; } public int GetHashCode(Type obj) { Helpers.ThrowIfArgumentNull(obj, "obj"); if (!obj.IsGenericType) { return obj.GetHashCode(); } int num = -559038737; num ^= obj.Assembly.GetHashCode(); num ^= (num << 16) | (num >> 16); if (obj.Namespace != null) { num ^= obj.Namespace.GetHashCode(StringComparison.Ordinal); } num ^= obj.Name.GetHashCode(StringComparison.Ordinal); Type[] genericArguments = obj.GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { int num2 = i % 8 * 4; Type type = genericArguments[i]; int num3 = (type.IsValueType ? GetHashCode(type) : (CannonicalFillType?.GetHashCode() ?? (-1717986919))); num ^= (num3 << num2) | (num3 >> 32 - num2); } return num; } } public static class Helpers { private static class FuncInvokeHolder { public static readonly Func, T> InvokeFunc = (Func f) => f(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Swap(ref T a, ref T b) { T val = a; a = b; b = val; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Has(this T value, T flag) where T : struct, Enum { if (Unsafe.SizeOf() == 8) { long num = Unsafe.As(ref flag); return (Unsafe.As(ref value) & num) == num; } if (Unsafe.SizeOf() == 4) { int num2 = Unsafe.As(ref flag); return (Unsafe.As(ref value) & num2) == num2; } if (Unsafe.SizeOf() == 2) { short num3 = Unsafe.As(ref flag); return (Unsafe.As(ref value) & num3) == num3; } if (Unsafe.SizeOf() == 1) { byte b = Unsafe.As(ref flag); return (Unsafe.As(ref value) & b) == b; } throw new InvalidOperationException("unknown enum size?"); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfArgumentNull([NotNull] T? arg, [CallerArgumentExpression("arg")] string name = "") { if (arg == null) { ThrowArgumentNull(name); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T ThrowIfNull([NotNull] T? arg, [CallerArgumentExpression("arg")] string name = "") { if (arg == null) { ThrowArgumentNull(name); } return arg; } public static T EventAdd(ref T? evt, T del) where T : Delegate { T val; T val2; do { val = evt; val2 = (T)Delegate.Combine(val, del); } while (Interlocked.CompareExchange(ref evt, val2, val) != val); return val2; } public static T? EventRemove(ref T? evt, T del) where T : Delegate { T val; T val2; do { val = evt; val2 = (T)Delegate.Remove(val, del); } while (Interlocked.CompareExchange(ref evt, val2, val) != val); return val2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Assert([DoesNotReturnIf(false)] bool value, string? message = null, [CallerArgumentExpression("value")] string expr = "") { if (!value) { ThrowAssertionFailed(message, expr); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Conditional("DEBUG")] public static void DAssert([DoesNotReturnIf(false)] bool value, string? message = null, [CallerArgumentExpression("value")] string expr = "") { if (!value) { ThrowAssertionFailed(message, expr); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Assert([DoesNotReturnIf(false)] bool value, [InterpolatedStringHandlerArgument("value")] ref AssertionInterpolatedStringHandler message, [CallerArgumentExpression("value")] string expr = "") { if (!value) { ThrowAssertionFailed(ref message, expr); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Conditional("DEBUG")] public static void DAssert([DoesNotReturnIf(false)] bool value, [InterpolatedStringHandlerArgument("value")] ref AssertionInterpolatedStringHandler message, [CallerArgumentExpression("value")] string expr = "") { if (!value) { ThrowAssertionFailed(ref message, expr); } } [DoesNotReturn] private static void ThrowArgumentNull(string argName) { throw new ArgumentNullException(argName); } [DoesNotReturn] private static void ThrowAssertionFailed(string? msg, string expr) { LogLevel logLevel = LogLevel.Assert; LogLevel level = logLevel; bool isEnabled; DebugLogInterpolatedStringHandler message = new DebugLogInterpolatedStringHandler(19, 2, logLevel, out isEnabled); if (isEnabled) { message.AppendLiteral("Assertion failed! "); message.AppendFormatted(expr); message.AppendLiteral(" "); message.AppendFormatted(msg); } DebugLog.Log("MonoMod.Utils.Assert", level, ref message); throw new AssertionFailedException(msg, expr); } [DoesNotReturn] private static void ThrowAssertionFailed(ref AssertionInterpolatedStringHandler message, string expr) { string text = message.ToStringAndClear(); LogLevel logLevel = LogLevel.Assert; LogLevel level = logLevel; bool isEnabled; DebugLogInterpolatedStringHandler message2 = new DebugLogInterpolatedStringHandler(19, 2, logLevel, out isEnabled); if (isEnabled) { message2.AppendLiteral("Assertion failed! "); message2.AppendFormatted(expr); message2.AppendLiteral(" "); message2.AppendFormatted(text); } DebugLog.Log("MonoMod.Utils.Assert", level, ref message2); throw new AssertionFailedException(text, expr); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T GetOrInit(ref T? location, Func init) where T : class { if (location != null) { return location; } return InitializeValue>(ref location, FuncInvokeHolder.InvokeFunc, init); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T GetOrInitWithLock(ref T? location, object @lock, Func init) where T : class { if (location != null) { return location; } return InitializeValueWithLock>(ref location, @lock, FuncInvokeHolder.InvokeFunc, init); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T GetOrInit(ref T? location, Func init, TParam param) where T : class { ThrowIfArgumentNull(init, "init"); if (location != null) { return location; } return InitializeValue(ref location, init, param); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T GetOrInitWithLock(ref T? location, object @lock, Func init, TParam param) where T : class { ThrowIfArgumentNull(init, "init"); if (location != null) { return location; } return InitializeValueWithLock(ref location, @lock, init, param); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static T GetOrInit(ref T? location, delegate* init) where T : class { if (location != null) { return location; } return InitializeValue(ref location, (delegate*)(&ILHelpers.TailCallDelegatePtr), (nint)init); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static T GetOrInitWithLock(ref T? location, object @lock, delegate* init) where T : class { if (location != null) { return location; } return InitializeValueWithLock(ref location, @lock, (delegate*)(&ILHelpers.TailCallDelegatePtr), (nint)init); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static T GetOrInit(ref T? location, delegate* init, TParam obj) where T : class { if (location != null) { return location; } return InitializeValue(ref location, init, obj); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static T GetOrInitWithLock(ref T? location, object @lock, delegate* init, TParam obj) where T : class { if (location != null) { return location; } return InitializeValueWithLock(ref location, @lock, init, obj); } [MethodImpl(MethodImplOptions.NoInlining)] private unsafe static T InitializeValue(ref T? location, delegate* init, TParam obj) where T : class { Interlocked.CompareExchange(ref location, init(obj), null); return location; } [MethodImpl(MethodImplOptions.NoInlining)] private static T InitializeValue(ref T? location, Func init, TParam obj) where T : class { Interlocked.CompareExchange(ref location, init(obj), null); return location; } [MethodImpl(MethodImplOptions.NoInlining)] private unsafe static T InitializeValueWithLock(ref T? location, object @lock, delegate* init, TParam obj) where T : class { lock (@lock) { if (location != null) { return location; } return location = init(obj); } } [MethodImpl(MethodImplOptions.NoInlining)] private static T InitializeValueWithLock(ref T? location, object @lock, Func init, TParam obj) where T : class { lock (@lock) { if (location != null) { return location; } return location = init(obj); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool MaskedSequenceEqual(ReadOnlySpan first, ReadOnlySpan second, ReadOnlySpan mask) { if (mask.Length < first.Length || mask.Length < second.Length) { ThrowMaskTooShort(); } if (first.Length == second.Length) { return MaskedSequenceEqualCore(ref MemoryMarshal.GetReference(first), ref MemoryMarshal.GetReference(second), ref MemoryMarshal.GetReference(mask), (nuint)first.Length); } return false; } [DoesNotReturn] private static void ThrowMaskTooShort() { throw new ArgumentException("Mask too short", "mask"); } private unsafe static bool MaskedSequenceEqualCore(ref byte first, ref byte second, ref byte maskBytes, nuint length) { if (!Unsafe.AreSame(in first, in second)) { nint num = 0; nint num2 = (nint)length; if ((nuint)num2 >= (nuint)sizeof(nuint)) { num2 -= sizeof(nuint); while (true) { nuint num3; if ((nuint)num2 > (nuint)num) { num3 = Unsafe.ReadUnaligned(in Unsafe.AddByteOffset(ref maskBytes, num)); if ((Unsafe.ReadUnaligned(in Unsafe.AddByteOffset(ref first, num)) & num3) != (Unsafe.ReadUnaligned(in Unsafe.AddByteOffset(ref second, num)) & num3)) { break; } num += sizeof(nuint); continue; } num3 = Unsafe.ReadUnaligned(in Unsafe.AddByteOffset(ref maskBytes, num)); return (Unsafe.ReadUnaligned(in Unsafe.AddByteOffset(ref first, num2)) & num3) == (Unsafe.ReadUnaligned(in Unsafe.AddByteOffset(ref second, num2)) & num3); } goto IL_00b9; } while ((nuint)num2 > (nuint)num) { byte b = Unsafe.AddByteOffset(ref maskBytes, num); if ((Unsafe.AddByteOffset(ref first, num) & b) == (Unsafe.AddByteOffset(ref second, num) & b)) { num++; continue; } goto IL_00b9; } } return true; IL_00b9: return false; } public static byte[] ReadAllBytes(string path) { using FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1); long length = fileStream.Length; if (length > int.MaxValue) { throw new IOException("File is too long (more than 2GB)"); } if (length == 0L) { return ReadAllBytesUnknownLength(fileStream); } int num = 0; int num2 = (int)length; byte[] array = new byte[num2]; while (num2 > 0) { int num3 = fileStream.Read(array, num, num2); if (num3 == 0) { throw new IOException("Unexpected end of stream"); } num += num3; num2 -= num3; } return array; } private static byte[] ReadAllBytesUnknownLength(FileStream fs) { byte[] array = ArrayPool.Shared.Rent(256); try { int num = 0; while (true) { if (num == array.Length) { uint num2 = (uint)(array.Length * 2); if (num2 > ArrayEx.MaxLength) { num2 = (uint)Math.Max(ArrayEx.MaxLength, array.Length + 1); } byte[] array2 = ArrayPool.Shared.Rent((int)num2); Array.Copy(array, array2, array.Length); if (array != null) { ArrayPool.Shared.Return(array); } array = array2; } int num3 = fs.Read(array, num, array.Length - num); if (num3 == 0) { break; } num += num3; } return array.AsSpan(0, num).ToArray(); } finally { if (array != null) { ArrayPool.Shared.Return(array); } } } } [InterpolatedStringHandler] public ref struct AssertionInterpolatedStringHandler { private DebugLogInterpolatedStringHandler handler; [MethodImpl(MethodImplOptions.AggressiveInlining)] public AssertionInterpolatedStringHandler(int literalLen, int formattedCount, bool assertValue, out bool isEnabled) { handler = new DebugLogInterpolatedStringHandler(literalLen, formattedCount, !assertValue, recordHoles: false, out isEnabled); } public override string ToString() { return handler.ToString(); } public string ToStringAndClear() { return handler.ToStringAndClear(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendLiteral(string s) { handler.AppendLiteral(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(string? s) { handler.AppendFormatted(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(string? s, int alignment = 0, string? format = null) { handler.AppendFormatted(s, alignment, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(ReadOnlySpan s) { handler.AppendFormatted(s); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(ReadOnlySpan s, int alignment = 0, string? format = null) { handler.AppendFormatted(s, alignment, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value) { handler.AppendFormatted(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, int alignment) { handler.AppendFormatted(value, alignment); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, string? format) { handler.AppendFormatted(value, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormatted(T value, int alignment, string? format) { handler.AppendFormatted(value, alignment, format); } } public interface ICallSiteGenerator { CallSite ToCallSite(ModuleDefinition module); } public sealed class LazyDisposable : IDisposable { public event Action? OnDispose; public LazyDisposable() { } public LazyDisposable(Action a) : this() { OnDispose += a; } public void Dispose() { this.OnDispose?.Invoke(); } } public sealed class LazyDisposable : IDisposable { private T? Instance; public event Action? OnDispose; public LazyDisposable(T instance) { Instance = instance; } public LazyDisposable(T instance, Action a) : this(instance) { OnDispose += a; } public void Dispose() { this.OnDispose?.Invoke(Instance); Instance = default(T); } } public sealed class MethodSignature : IEquatable, IDebugFormattable { private sealed class CompatibleComparer : IEqualityComparer { public static readonly CompatibleComparer Instance = new CompatibleComparer(); public bool Equals(Type? x, Type? y) { if ((object)x == y) { return true; } if ((object)x == null || (object)y == null) { return false; } return x.IsCompatible(y); } public int GetHashCode([DisallowNull] Type obj) { throw new NotSupportedException(); } } private readonly Type[] parameters; private static readonly ConditionalWeakTable thisSigMap = new ConditionalWeakTable(); private static readonly ConditionalWeakTable noThisSigMap = new ConditionalWeakTable(); public Type ReturnType { get; } public int ParameterCount => parameters.Length; public IEnumerable Parameters => parameters; public Type? FirstParameter { get { if (parameters.Length < 1) { return null; } return parameters[0]; } } public MethodSignature(Type returnType, Type[] parameters) { ReturnType = returnType; this.parameters = parameters; } public MethodSignature(Type returnType, IEnumerable parameters) { ReturnType = returnType; this.parameters = parameters.ToArray(); } public MethodSignature(MethodBase method) : this(method, ignoreThis: false) { } public MethodSignature(MethodBase method, bool ignoreThis) { ReturnType = (method as MethodInfo)?.ReturnType ?? typeof(void); int num = ((!ignoreThis && !method.IsStatic) ? 1 : 0); ParameterInfo[] array = method.GetParameters(); parameters = new Type[array.Length + num]; for (int i = num; i < parameters.Length; i++) { parameters[i] = array[i - num].ParameterType; } if (!ignoreThis && !method.IsStatic) { parameters[0] = method.GetThisParamType(); } } public static MethodSignature ForMethod(MethodBase method) { return ForMethod(method, ignoreThis: false); } public static MethodSignature ForMethod(MethodBase method, bool ignoreThis) { return (ignoreThis ? noThisSigMap : thisSigMap).GetValue(method, (MethodBase m) => new MethodSignature(m, ignoreThis)); } public bool IsCompatibleWith(MethodSignature other) { Helpers.ThrowIfArgumentNull(other, "other"); if (this == other) { return true; } if (ReturnType.IsCompatible(other.ReturnType)) { return parameters.SequenceEqual(other.Parameters, CompatibleComparer.Instance); } return false; } public DynamicMethodDefinition CreateDmd(string name) { return new DynamicMethodDefinition(name, ReturnType, parameters); } public override string ToString() { int literalLength = 2 + parameters.Length - 1; int formattedCount = 1 + parameters.Length; DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(literalLength, formattedCount); defaultInterpolatedStringHandler.AppendFormatted(ReturnType); defaultInterpolatedStringHandler.AppendLiteral(" ("); for (int i = 0; i < parameters.Length; i++) { if (i != 0) { defaultInterpolatedStringHandler.AppendLiteral(", "); } defaultInterpolatedStringHandler.AppendFormatted(parameters[i]); } defaultInterpolatedStringHandler.AppendLiteral(")"); return defaultInterpolatedStringHandler.ToStringAndClear(); } bool IDebugFormattable.TryFormatInto(Span span, out int wrote) { wrote = 0; Span span2 = span; Span span3 = span2; bool enabled; FormatIntoInterpolatedStringHandler handler = new FormatIntoInterpolatedStringHandler(2, 1, span2, out enabled); if (enabled && handler.AppendFormatted(ReturnType)) { handler.AppendLiteral(" ("); } else _ = 0; if (!DebugFormatter.Into(span3, out var wrote2, ref handler)) { return false; } wrote += wrote2; for (int i = 0; i < parameters.Length; i++) { if (i != 0) { if (!", ".AsSpan().TryCopyTo(span.Slice(wrote))) { return false; } wrote += 2; } span2 = span.Slice(wrote); Span span4 = span2; bool enabled2; FormatIntoInterpolatedStringHandler handler2 = new FormatIntoInterpolatedStringHandler(0, 1, span2, out enabled2); if (enabled2) { handler2.AppendFormatted(parameters[i]); } else _ = 0; if (!DebugFormatter.Into(span4, out wrote2, ref handler2)) { return false; } wrote += wrote2; } if (span.Slice(wrote).Length < 1) { return false; } span[wrote++] = ')'; return true; } public bool Equals(MethodSignature? other) { if (other == null) { return false; } if (this == other) { return true; } if (!ReturnType.Equals(other.ReturnType)) { return false; } return Parameters.SequenceEqual(other.Parameters); } public override bool Equals(object? obj) { if (obj is MethodSignature other) { return Equals(other); } return false; } public override int GetHashCode() { HashCode hashCode = default(HashCode); hashCode.Add(ReturnType); hashCode.Add(parameters.Length); Type[] array = parameters; foreach (Type value in array) { hashCode.Add(value); } return hashCode.ToHashCode(); } } public sealed class MMReflectionImporter : IReflectionImporter { private class _Provider : IReflectionImporterProvider { public bool? UseDefault; public IReflectionImporter GetReflectionImporter(ModuleDefinition module) { Helpers.ThrowIfArgumentNull(module, "module"); MMReflectionImporter mMReflectionImporter = new MMReflectionImporter(module); if (UseDefault.HasValue) { mMReflectionImporter.UseDefault = UseDefault.Value; } return (IReflectionImporter)(object)mMReflectionImporter; } } private enum GenericImportKind { Open, Definition } public static readonly IReflectionImporterProvider Provider = (IReflectionImporterProvider)(object)new _Provider(); public static readonly IReflectionImporterProvider ProviderNoDefault = (IReflectionImporterProvider)(object)new _Provider { UseDefault = false }; private readonly ModuleDefinition Module; private readonly DefaultReflectionImporter Default; private readonly Dictionary CachedAsms = new Dictionary(); private readonly Dictionary CachedModuleTypes = new Dictionary(); private readonly Dictionary CachedTypes = new Dictionary(); private readonly Dictionary CachedFields = new Dictionary(); private readonly Dictionary CachedMethods = new Dictionary(); private readonly Dictionary ElementTypes; public bool UseDefault { get; set; } public MMReflectionImporter(ModuleDefinition module) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown Helpers.ThrowIfArgumentNull(module, "module"); Module = module; Default = new DefaultReflectionImporter(module); ElementTypes = new Dictionary { { typeof(void), module.TypeSystem.Void }, { typeof(bool), module.TypeSystem.Boolean }, { typeof(char), module.TypeSystem.Char }, { typeof(sbyte), module.TypeSystem.SByte }, { typeof(byte), module.TypeSystem.Byte }, { typeof(short), module.TypeSystem.Int16 }, { typeof(ushort), module.TypeSystem.UInt16 }, { typeof(int), module.TypeSystem.Int32 }, { typeof(uint), module.TypeSystem.UInt32 }, { typeof(long), module.TypeSystem.Int64 }, { typeof(ulong), module.TypeSystem.UInt64 }, { typeof(float), module.TypeSystem.Single }, { typeof(double), module.TypeSystem.Double }, { typeof(string), module.TypeSystem.String }, { typeof(TypedReference), module.TypeSystem.TypedReference }, { typeof(nint), module.TypeSystem.IntPtr }, { typeof(nuint), module.TypeSystem.UIntPtr }, { typeof(object), module.TypeSystem.Object } }; } private bool TryGetCachedType(Type type, [MaybeNullWhen(false)] out TypeReference typeRef, GenericImportKind importKind) { if (importKind == GenericImportKind.Definition) { typeRef = null; return false; } return CachedTypes.TryGetValue(type, out typeRef); } private TypeReference SetCachedType(Type type, TypeReference typeRef, GenericImportKind importKind) { if (importKind == GenericImportKind.Definition) { return typeRef; } return CachedTypes[type] = typeRef; } [Obsolete("Please use the Assembly overload instead.")] public AssemblyNameReference ImportReference(AssemblyName reference) { Helpers.ThrowIfArgumentNull(reference, "reference"); return Default.ImportReference(reference); } public AssemblyNameReference ImportReference(Assembly asm) { Helpers.ThrowIfArgumentNull(asm, "asm"); if (CachedAsms.TryGetValue(asm, out AssemblyNameReference value)) { return value; } value = ImportReference(asm.GetName()); value.ApplyRuntimeHash(asm); return CachedAsms[asm] = value; AssemblyNameReference ImportReference(AssemblyName name) { //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_002b: 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_0049: Expected O, but got Unknown if (TryGetAssemblyNameReference(name, out var assembly_reference)) { return assembly_reference; } assembly_reference = new AssemblyNameReference(name.Name, name.Version) { PublicKeyToken = name.GetPublicKeyToken(), Culture = name.CultureInfo.Name, HashAlgorithm = (AssemblyHashAlgorithm)name.HashAlgorithm }; Module.AssemblyReferences.Add(assembly_reference); return assembly_reference; } bool TryGetAssemblyNameReference(AssemblyName name, [NotNullWhen(true)] out AssemblyNameReference? assembly_reference) { Collection assemblyReferences = Module.AssemblyReferences; for (int i = 0; i < assemblyReferences.Count; i++) { AssemblyNameReference val2 = assemblyReferences[i]; if (!(name.FullName != val2.FullName) && val2.HashIs(asm)) { assembly_reference = val2; return true; } } assembly_reference = null; return false; } } public TypeReference ImportModuleType(Module module, IGenericParameterProvider? context) { //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: Expected O, but got Unknown //IL_004c: Expected O, but got Unknown Helpers.ThrowIfArgumentNull(module, "module"); if (CachedModuleTypes.TryGetValue(module, out TypeReference value)) { return value; } Dictionary cachedModuleTypes = CachedModuleTypes; TypeReference val = new TypeReference(string.Empty, "", Module, (IMetadataScope)(object)ImportReference(module.Assembly)); TypeReference result = val; cachedModuleTypes[module] = val; return result; } public TypeReference ImportReference(Type type, IGenericParameterProvider? context) { Helpers.ThrowIfArgumentNull(type, "type"); return _ImportReference(type, context, (context == null) ? GenericImportKind.Definition : GenericImportKind.Open); } private static bool _IsGenericInstance(Type type, GenericImportKind importKind) { Helpers.ThrowIfArgumentNull(type, "type"); if (!type.IsGenericType || type.IsGenericTypeDefinition) { if (type.IsGenericType && type.IsGenericTypeDefinition) { return importKind == GenericImportKind.Open; } return false; } return true; } private GenericInstanceType _ImportGenericInstance(Type type, IGenericParameterProvider? context, TypeReference typeRef) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown Helpers.ThrowIfArgumentNull(type, "type"); Helpers.ThrowIfArgumentNull(typeRef, "typeRef"); GenericInstanceType val = new GenericInstanceType(typeRef); Type[] genericArguments = type.GetGenericArguments(); foreach (Type type2 in genericArguments) { val.GenericArguments.Add(_ImportReference(type2, context)); } return val; } private TypeReference _ImportReference(Type type, IGenericParameterProvider? context, GenericImportKind importKind = GenericImportKind.Open) { //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Expected O, but got Unknown //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Expected O, but got Unknown //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Expected O, but got Unknown //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Expected O, but got Unknown //IL_00ec: 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_01f7: Expected O, but got Unknown Helpers.ThrowIfArgumentNull(type, "type"); if (TryGetCachedType(type, out TypeReference typeRef, importKind)) { if (!_IsGenericInstance(type, importKind)) { return typeRef; } return (TypeReference)(object)_ImportGenericInstance(type, context, typeRef); } if (UseDefault) { return SetCachedType(type, Default.ImportReference(type, context), importKind); } if (type.HasElementType) { if (type.IsByRef) { return SetCachedType(type, (TypeReference)new ByReferenceType(_ImportReference(type.GetElementType(), context)), importKind); } if (type.IsPointer) { return SetCachedType(type, (TypeReference)new PointerType(_ImportReference(type.GetElementType(), context)), importKind); } if (type.IsArray) { ArrayType val = new ArrayType(_ImportReference(type.GetElementType(), context), type.GetArrayRank()); if (type != type.GetElementType().MakeArrayType()) { for (int i = 0; i < val.Rank; i++) { val.Dimensions[i] = new ArrayDimension((int?)0, (int?)null); } } return CachedTypes[type] = (TypeReference)(object)val; } } if (_IsGenericInstance(type, importKind)) { return (TypeReference)(object)_ImportGenericInstance(type, context, _ImportReference(type.GetGenericTypeDefinition(), context, GenericImportKind.Definition)); } if (type.IsGenericParameter) { return SetCachedType(type, (TypeReference)(object)ImportGenericParameter(type, context), importKind); } if (ElementTypes.TryGetValue(type, out typeRef)) { return SetCachedType(type, typeRef, importKind); } typeRef = new TypeReference(string.Empty, type.Name, Module, (IMetadataScope)(object)ImportReference(type.Assembly), type.IsValueType); if (type.IsNested) { ((MemberReference)typeRef).DeclaringType = _ImportReference(type.DeclaringType, context, importKind); } else if (type.Namespace != null) { typeRef.Namespace = type.Namespace; } if (type.IsGenericType) { Type[] genericArguments = type.GetGenericArguments(); foreach (Type type2 in genericArguments) { typeRef.GenericParameters.Add(new GenericParameter(type2.Name, (IGenericParameterProvider)(object)typeRef)); } } return SetCachedType(type, typeRef, importKind); } private static GenericParameter ImportGenericParameter(Type type, IGenericParameterProvider? context) { Helpers.ThrowIfArgumentNull(type, "type"); MethodReference val = (MethodReference)(object)((context is MethodReference) ? context : null); if (val != null) { if (type.DeclaringMethod != null) { return val.GenericParameters[type.GenericParameterPosition]; } context = (IGenericParameterProvider?)(object)((MemberReference)val).DeclaringType; } Type minfo = type.DeclaringType ?? throw new InvalidOperationException(); TypeReference val2 = (TypeReference)(object)((context is TypeReference) ? context : null); if (val2 != null) { while (val2 != null) { TypeReference elementType = val2.GetElementType(); if (((MemberReference?)(object)elementType).Is(minfo)) { return elementType.GenericParameters[type.GenericParameterPosition]; } if (((MemberReference?)(object)val2).Is(minfo)) { return val2.GenericParameters[type.GenericParameterPosition]; } val2 = ((MemberReference)val2).DeclaringType; } } throw new NotSupportedException(); } public FieldReference ImportReference(FieldInfo field, IGenericParameterProvider? context) { //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Expected O, but got Unknown //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Expected O, but got Unknown //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Expected O, but got Unknown //IL_012d: Expected O, but got Unknown Helpers.ThrowIfArgumentNull(field, "field"); if (CachedFields.TryGetValue(field, out FieldReference value)) { return value; } if (UseDefault) { return CachedFields[field] = Default.ImportReference(field, context); } Type declaringType = field.DeclaringType; TypeReference val2 = ((declaringType != null) ? ImportReference(declaringType, context) : ImportModuleType(field.Module, context)); FieldInfo key = field; if (declaringType != null && declaringType.IsGenericType) { field = field.Module.ResolveField(field.MetadataToken); } TypeReference val3 = _ImportReference(field.FieldType, (IGenericParameterProvider?)(object)val2); Type[] requiredCustomModifiers = field.GetRequiredCustomModifiers(); Type[] optionalCustomModifiers = field.GetOptionalCustomModifiers(); Type[] array = requiredCustomModifiers; foreach (Type type in array) { val3 = (TypeReference)new RequiredModifierType(_ImportReference(type, (IGenericParameterProvider?)(object)val2), val3); } array = optionalCustomModifiers; foreach (Type type2 in array) { val3 = (TypeReference)new OptionalModifierType(_ImportReference(type2, (IGenericParameterProvider?)(object)val2), val3); } Dictionary cachedFields = CachedFields; FieldReference val4 = new FieldReference(field.Name, val3, val2); FieldReference result = val4; cachedFields[key] = val4; return result; } public MethodReference ImportReference(MethodBase method, IGenericParameterProvider? context) { Helpers.ThrowIfArgumentNull(method, "method"); return _ImportReference(method, context, (context == null) ? GenericImportKind.Definition : GenericImportKind.Open); } private MethodReference _ImportReference(MethodBase method, IGenericParameterProvider? context, GenericImportKind importKind) { //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Expected O, but got Unknown //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Expected O, but got Unknown //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Expected O, but got Unknown //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_0242: Expected O, but got Unknown Helpers.ThrowIfArgumentNull(method, "method"); if (CachedMethods.TryGetValue(method, out MethodReference value) && importKind == GenericImportKind.Open) { return value; } if (method is MethodInfo methodInfo && methodInfo.IsDynamicMethod()) { return (MethodReference)(object)new DynamicMethodReference(Module, methodInfo); } if (UseDefault) { return CachedMethods[method] = Default.ImportReference(method, context); } if ((method.IsGenericMethod && !method.IsGenericMethodDefinition) || (method.IsGenericMethod && method.IsGenericMethodDefinition && importKind == GenericImportKind.Open)) { GenericInstanceMethod val2 = new GenericInstanceMethod(_ImportReference(((MethodInfo)method).GetGenericMethodDefinition(), context, GenericImportKind.Definition)); Type[] genericArguments = method.GetGenericArguments(); foreach (Type type in genericArguments) { val2.GenericArguments.Add(_ImportReference(type, context)); } return CachedMethods[method] = (MethodReference)(object)val2; } Type declaringType = method.DeclaringType; value = new MethodReference(method.Name, _ImportReference(typeof(void), context), (declaringType != null) ? _ImportReference(declaringType, context, GenericImportKind.Definition) : ImportModuleType(method.Module, context)); value.HasThis = (method.CallingConvention & CallingConventions.HasThis) != 0; value.ExplicitThis = (method.CallingConvention & CallingConventions.ExplicitThis) != 0; if ((method.CallingConvention & CallingConventions.VarArgs) != 0) { value.CallingConvention = (MethodCallingConvention)5; } MethodBase key = method; if (declaringType != null && declaringType.IsGenericType) { method = method.Module.ResolveMethod(method.MetadataToken); } if (method.IsGenericMethodDefinition) { Type[] genericArguments = method.GetGenericArguments(); foreach (Type type2 in genericArguments) { value.GenericParameters.Add(new GenericParameter(type2.Name, (IGenericParameterProvider)(object)value)); } } value.ReturnType = _ImportReference((method as MethodInfo)?.ReturnType ?? typeof(void), (IGenericParameterProvider?)(object)value); ParameterInfo[] parameters = method.GetParameters(); foreach (ParameterInfo parameterInfo in parameters) { value.Parameters.Add(new ParameterDefinition(parameterInfo.Name, (ParameterAttributes)(ushort)parameterInfo.Attributes, _ImportReference(parameterInfo.ParameterType, (IGenericParameterProvider?)(object)value))); } return CachedMethods[key] = value; } } public enum OSKind { Unknown = 0, Posix = 1, Linux = 9, Android = 41, OSX = 5, IOS = 37, BSD = 17, Windows = 2, Wine = 34 } public static class OSKindExtensions { public static bool Is(this OSKind operatingSystem, OSKind test) { return operatingSystem.Has(test); } public static OSKind GetKernel(this OSKind operatingSystem) { return operatingSystem & (OSKind)31; } public static int GetSubtypeId(this OSKind operatingSystem) { return (int)operatingSystem >> 5; } } public static class PlatformDetection { private static int platInitState; private static OSKind os; private static ArchitectureKind arch; private static int runtimeInitState; private static RuntimeKind runtime; private static CorelibKind corelib; private static Version? runtimeVersion; public static OSKind OS { get { EnsurePlatformInfoInitialized(); return os; } } public static ArchitectureKind Architecture { get { EnsurePlatformInfoInitialized(); return arch; } } public static RuntimeKind Runtime { get { EnsureRuntimeInitialized(); return runtime; } } public static CorelibKind Corelib { get { EnsureRuntimeInitialized(); return corelib; } } public static Version RuntimeVersion { get { EnsureRuntimeInitialized(); return runtimeVersion; } } private static void EnsurePlatformInfoInitialized() { if (platInitState == 0) { (os, arch) = DetectPlatformInfo(); Thread.MemoryBarrier(); Interlocked.Exchange(ref platInitState, 1); } } private static (OSKind OS, ArchitectureKind Arch) DetectPlatformInfo() { OSKind oSKind = OSKind.Unknown; ArchitectureKind architectureKind = ArchitectureKind.Unknown; PropertyInfo property = typeof(Environment).GetProperty("Platform", BindingFlags.Static | BindingFlags.NonPublic); string text = ((!(property != null)) ? Environment.OSVersion.Platform.ToString() : property.GetValue(null, null)?.ToString())?.ToUpperInvariant() ?? ""; if (text.Contains("WIN", StringComparison.Ordinal)) { oSKind = OSKind.Windows; } else if (text.Contains("MAC", StringComparison.Ordinal) || text.Contains("OSX", StringComparison.Ordinal)) { oSKind = OSKind.OSX; } else if (text.Contains("LIN", StringComparison.Ordinal)) { oSKind = OSKind.Linux; } else if (text.Contains("BSD", StringComparison.Ordinal)) { oSKind = OSKind.BSD; } else if (text.Contains("UNIX", StringComparison.Ordinal)) { oSKind = OSKind.Posix; } if (oSKind == OSKind.Windows) { DetectInfoWindows(ref oSKind, ref architectureKind); } else if ((oSKind & OSKind.Posix) != OSKind.Unknown) { DetectInfoPosix(ref oSKind, ref architectureKind); } if (oSKind != OSKind.Unknown) { if (oSKind == OSKind.Linux && Directory.Exists("/data") && File.Exists("/system/build.prop")) { oSKind = OSKind.Android; } else if (oSKind == OSKind.Posix && Directory.Exists("/Applications") && Directory.Exists("/System") && Directory.Exists("/User") && !Directory.Exists("/Users")) { oSKind = OSKind.IOS; } else if (oSKind == OSKind.Windows && CheckWine()) { oSKind = OSKind.Wine; } } bool isEnabled; MMDbgLog.DebugLogInfoStringHandler message = new MMDbgLog.DebugLogInfoStringHandler(16, 2, out isEnabled); if (isEnabled) { message.AppendLiteral("Platform info: "); message.AppendFormatted(oSKind); message.AppendLiteral(" "); message.AppendFormatted(architectureKind); } MMDbgLog.Info(ref message); return (OS: oSKind, Arch: architectureKind); } private unsafe static int PosixUname(OSKind os, byte* buf) { if (os != OSKind.OSX) { return Libc(buf); } return Osx(buf); unsafe static int Libc(byte* buf2) { return Unix.Uname(buf2); } unsafe static int Osx(byte* buf2) { return OSX.Uname(buf2); } } private unsafe static string GetCString(ReadOnlySpan buffer, out int nullByte) { fixed (byte* ptr = buffer) { return Marshal.PtrToStringAnsi((nint)ptr, nullByte = buffer.IndexOf(0)); } } private unsafe static void DetectInfoPosix(ref OSKind os, ref ArchitectureKind arch) { bool isEnabled; try { Span span = new byte[3078]; fixed (byte* buf = span) { if (PosixUname(os, buf) < 0) { string message = new Win32Exception(Marshal.GetLastWin32Error()).Message; MMDbgLog.DebugLogErrorStringHandler message2 = new MMDbgLog.DebugLogErrorStringHandler(24, 1, out isEnabled); if (isEnabled) { message2.AppendLiteral("uname() syscall failed! "); message2.AppendFormatted(message); } MMDbgLog.Error(ref message2); return; } } int nullByte; string text = GetCString(span, out nullByte).ToUpperInvariant(); span = span.Slice(nullByte); MMDbgLog.DebugLogTraceStringHandler message3 = new MMDbgLog.DebugLogTraceStringHandler(22, 1, out isEnabled); if (isEnabled) { message3.AppendLiteral("uname() call returned "); message3.AppendFormatted(text); } MMDbgLog.Trace(ref message3); if (text.Contains("LINUX", StringComparison.Ordinal)) { os = OSKind.Linux; } else if (text.Contains("DARWIN", StringComparison.Ordinal)) { os = OSKind.OSX; } else if (text.Contains("BSD", StringComparison.Ordinal)) { os = OSKind.BSD; } string text2 = GetMachineNamePosix(os, span).ToUpperInvariant(); if (text2.Contains("X86_64", StringComparison.Ordinal) || text2.Contains("AMD64", StringComparison.Ordinal)) { arch = ArchitectureKind.x86_64; } else if (text2.Contains("X86", StringComparison.Ordinal) || text2.Contains("I686", StringComparison.Ordinal)) { arch = ArchitectureKind.x86; } else if (text2.Contains("AARCH64", StringComparison.Ordinal) || text2.Contains("ARM64", StringComparison.Ordinal)) { arch = ArchitectureKind.Arm64; } else if (text2.Contains("ARM", StringComparison.Ordinal)) { arch = ArchitectureKind.Arm; } MMDbgLog.DebugLogTraceStringHandler message4 = new MMDbgLog.DebugLogTraceStringHandler(37, 2, out isEnabled); if (isEnabled) { message4.AppendLiteral("uname() detected architecture info: "); message4.AppendFormatted(os); message4.AppendLiteral(" "); message4.AppendFormatted(arch); } MMDbgLog.Trace(ref message4); } catch (Exception value) { MMDbgLog.DebugLogErrorStringHandler message5 = new MMDbgLog.DebugLogErrorStringHandler(49, 1, out isEnabled); if (isEnabled) { message5.AppendLiteral("Error trying to detect info on POSIX-like system "); message5.AppendFormatted(value); } MMDbgLog.Error(ref message5); } } private unsafe static string GetMachineNamePosix(OSKind os, Span unameBuffer) { string text = null; bool isEnabled; int i; if (os == OSKind.Linux) { DynDll.InitializeBackend(os); if (DynDll.OpenLibrary("libc").TryGetExport("getauxval", out var functionPtr)) { nint num = ((delegate* unmanaged[Cdecl])functionPtr)(15); if (num != 0) { text = Marshal.PtrToStringAnsi(num); MMDbgLog.DebugLogTraceStringHandler message = new MMDbgLog.DebugLogTraceStringHandler(35, 1, out isEnabled); if (isEnabled) { message.AppendLiteral("Got architecture from getauxval(): "); message.AppendFormatted(text); } MMDbgLog.Trace(ref message); } } if (text == null) { try { Span span = MemoryMarshal.Cast(Helpers.ReadAllBytes("/proc/self/auxv").AsSpan()); text = string.Empty; Span span2 = span; for (i = 0; i < span2.Length; i++) { Unix.LinuxAuxvEntry linuxAuxvEntry = span2[i]; if (linuxAuxvEntry.Key == 15) { text = Marshal.PtrToStringAnsi(linuxAuxvEntry.Value) ?? string.Empty; break; } } if (text.Length == 0) { MMDbgLog.DebugLogWarningStringHandler message2 = new MMDbgLog.DebugLogWarningStringHandler(56, 1, out isEnabled); if (isEnabled) { message2.AppendLiteral("Auxv table did not inlcude useful AT_PLATFORM (0x"); message2.AppendFormatted(15, "x"); message2.AppendLiteral(") entry"); } MMDbgLog.Warning(ref message2); Span span3 = span; for (i = 0; i < span3.Length; i++) { Unix.LinuxAuxvEntry linuxAuxvEntry2 = span3[i]; MMDbgLog.DebugLogTraceStringHandler message3 = new MMDbgLog.DebugLogTraceStringHandler(3, 2, out isEnabled); if (isEnabled) { message3.AppendFormatted(linuxAuxvEntry2.Key, "x16"); message3.AppendLiteral(" = "); message3.AppendFormatted(linuxAuxvEntry2.Value, "x16"); } MMDbgLog.Trace(ref message3); } text = null; } else { MMDbgLog.DebugLogTraceStringHandler message4 = new MMDbgLog.DebugLogTraceStringHandler(43, 1, out isEnabled); if (isEnabled) { message4.AppendLiteral("Got architecture name "); message4.AppendFormatted(text); message4.AppendLiteral(" from /proc/self/auxv"); } MMDbgLog.Trace(ref message4); } } catch (UnauthorizedAccessException value) { MMDbgLog.Warning("Could not read /proc/self/auxv, and libc does not have getauxval"); MMDbgLog.Warning("Falling back to parsing out of uname() result..."); MMDbgLog.DebugLogWarningStringHandler message5 = new MMDbgLog.DebugLogWarningStringHandler(0, 1, out isEnabled); if (isEnabled) { message5.AppendFormatted(value); } MMDbgLog.Warning(ref message5); } } } if (text == null) { for (int j = 0; j < 4; j++) { if (j != 0) { int num2 = unameBuffer.IndexOf(0); unameBuffer = unameBuffer.Slice(num2); if (j == 1 && num2 < 5 && unameBuffer.Length >= 2 && unameBuffer[1] != 0) { num2 = unameBuffer.Slice(1).IndexOf(0); unameBuffer = unameBuffer.Slice(num2 + 1); } } int k; for (k = 0; k < unameBuffer.Length && unameBuffer[k] == 0; k++) { } unameBuffer = unameBuffer.Slice(k); } text = GetCString(unameBuffer, out i); MMDbgLog.DebugLogTraceStringHandler message6 = new MMDbgLog.DebugLogTraceStringHandler(35, 1, out isEnabled); if (isEnabled) { message6.AppendLiteral("Got architecture name "); message6.AppendFormatted(text); message6.AppendLiteral(" from uname()"); } MMDbgLog.Trace(ref message6); } return text; } private unsafe static void DetectInfoWindows(ref OSKind os, ref ArchitectureKind arch) { Windows.SYSTEM_INFO sYSTEM_INFO = default(Windows.SYSTEM_INFO); Windows.GetSystemInfo(&sYSTEM_INFO); ushort wProcessorArchitecture = sYSTEM_INFO.Anonymous.Anonymous.wProcessorArchitecture; arch = wProcessorArchitecture switch { 9 => ArchitectureKind.x86_64, 6 => throw new PlatformNotSupportedException("You're running .NET on an Itanium device!?!?"), 0 => ArchitectureKind.x86, 5 => ArchitectureKind.Arm, 12 => ArchitectureKind.Arm64, _ => throw new PlatformNotSupportedException($"Unknown Windows processor architecture {wProcessorArchitecture}"), }; } private unsafe static bool CheckWine() { if (Switches.TryGetSwitchEnabled("RunningOnWine", out var isEnabled)) { return isEnabled; } string text = Environment.GetEnvironmentVariable("XL_WINEONLINUX")?.ToUpperInvariant(); if (text == "TRUE") { return true; } if (text == "FALSE") { return false; } fixed (char* lpModuleName = "ntdll.dll".AsSpan()) { Windows.HMODULE moduleHandleW = Windows.GetModuleHandleW((ushort*)lpModuleName); if (moduleHandleW != Windows.HMODULE.NULL && moduleHandleW != Windows.HMODULE.INVALID_VALUE) { fixed (byte* lpProcName = "wineGetVersion"u8) { if (Windows.GetProcAddress(moduleHandleW, (sbyte*)lpProcName) != IntPtr.Zero) { return true; } } } } return false; } [MemberNotNull("runtimeVersion")] private static void EnsureRuntimeInitialized() { if (runtimeInitState != 0) { if ((object)runtimeVersion == null) { throw new InvalidOperationException("Despite runtimeInitState being set, runtimeVersion was somehow null"); } } else { (runtime, corelib, runtimeVersion) = DetermineRuntimeInfo(); Thread.MemoryBarrier(); Interlocked.Exchange(ref runtimeInitState, 1); } } private static (RuntimeKind Rt, CorelibKind Cor, Version Ver) DetermineRuntimeInfo() { Version version = null; bool flag = Type.GetType("Mono.Runtime") != null || Type.GetType("Mono.RuntimeStructs") != null; bool flag2 = typeof(object).Assembly.GetName().Name == "System.Private.CoreLib"; CorelibKind corelibKind = (flag2 ? CorelibKind.Core : CorelibKind.Framework); RuntimeKind runtimeKind = (flag ? RuntimeKind.Mono : ((!flag2 || flag) ? RuntimeKind.Framework : RuntimeKind.CoreCLR)); bool isEnabled; MMDbgLog.DebugLogTraceStringHandler message = new MMDbgLog.DebugLogTraceStringHandler(21, 2, out isEnabled); if (isEnabled) { message.AppendLiteral("IsMono: "); message.AppendFormatted(flag); message.AppendLiteral(", IsCoreBcl: "); message.AppendFormatted(flag2); } MMDbgLog.Trace(ref message); Version version2 = Environment.Version; MMDbgLog.DebugLogTraceStringHandler message2 = new MMDbgLog.DebugLogTraceStringHandler(25, 1, out isEnabled); if (isEnabled) { message2.AppendLiteral("Returned system version: "); message2.AppendFormatted(version2); } MMDbgLog.Trace(ref message2); Type type = Type.GetType("System.Runtime.InteropServices.RuntimeInformation"); if ((object)type == null) { type = Type.GetType("System.Runtime.InteropServices.RuntimeInformation, System.Runtime.InteropServices.RuntimeInformation"); } string text = (string)type?.GetProperty("FrameworkDescription")?.GetValue(null, null); MMDbgLog.DebugLogTraceStringHandler message3 = new MMDbgLog.DebugLogTraceStringHandler(22, 1, out isEnabled); if (isEnabled) { message3.AppendLiteral("FrameworkDescription: "); message3.AppendFormatted(text ?? "(null)"); } MMDbgLog.Trace(ref message3); if (text != null) { int length; if (text.StartsWith("Mono ", StringComparison.Ordinal)) { runtimeKind = RuntimeKind.Mono; length = "Mono ".Length; } else if (text.StartsWith(".NET Core ", StringComparison.Ordinal)) { runtimeKind = RuntimeKind.CoreCLR; length = ".NET Core ".Length; } else if (text.StartsWith(".NET Framework ", StringComparison.Ordinal)) { runtimeKind = RuntimeKind.Framework; length = ".NET Framework ".Length; } else if (text.StartsWith(".NET ", StringComparison.Ordinal)) { runtimeKind = (flag ? RuntimeKind.Mono : RuntimeKind.CoreCLR); length = ".NET ".Length; } else { runtimeKind = RuntimeKind.Unknown; length = text.Length; } int num = text.IndexOfAny(new char[2] { ' ', '-' }, length); if (num < 0) { num = text.Length; } string version3 = text.Substring(length, num - length); try { version = new Version(version3); } catch (Exception value) { MMDbgLog.DebugLogErrorStringHandler message4 = new MMDbgLog.DebugLogErrorStringHandler(61, 2, out isEnabled); if (isEnabled) { message4.AppendLiteral("Invalid version string pulled from FrameworkDescription ('"); message4.AppendFormatted(text); message4.AppendLiteral("') "); message4.AppendFormatted(value); } MMDbgLog.Error(ref message4); } } if (runtimeKind == RuntimeKind.Framework && (object)version == null) { version = version2; } MMDbgLog.DebugLogInfoStringHandler message5 = new MMDbgLog.DebugLogInfoStringHandler(34, 3, out isEnabled); if (isEnabled) { message5.AppendLiteral("Detected runtime: "); message5.AppendFormatted(runtimeKind); message5.AppendLiteral(" "); message5.AppendFormatted(version?.ToString() ?? "(null)"); message5.AppendLiteral(" using "); message5.AppendFormatted(corelibKind); message5.AppendLiteral(" corelib"); } MMDbgLog.Info(ref message5); return (Rt: runtimeKind, Cor: corelibKind, Ver: version ?? new Version(0, 0)); } } public static class ReflectionHelper { private delegate SignatureHelper GetUnmanagedSigHelperDelegate(Module? module, CallingConvention callConv, Type? returnType); private class CacheFixEntry { public object? Cache; public Array? Properties; public Array? Fields; public bool NeedsVerify; } internal static readonly bool IsCoreBCL; internal static readonly Dictionary AssemblyCache; internal static readonly Dictionary AssembliesCache; internal static readonly Dictionary ResolveReflectionCache; public static readonly byte[] AssemblyHashPrefix; public static readonly string AssemblyHashNameTag; private const BindingFlags _BindingFlagsAll = (BindingFlags)(-1); private static readonly MethodInfo? GetUnmanagedSigHelperMethod; private static readonly GetUnmanagedSigHelperDelegate GetUnmanagedSigHelper; private static readonly object?[] _CacheGetterArgs; private static Type? t_RuntimeType; private static Type? t_RuntimeTypeCache; private static PropertyInfo? p_RuntimeType_Cache; private static MethodInfo? m_RuntimeTypeCache_GetFieldList; private static MethodInfo? m_RuntimeTypeCache_GetPropertyList; private static readonly ConditionalWeakTable _CacheFixed; private static Type? t_RuntimeModule; private static PropertyInfo? p_RuntimeModule_RuntimeType; private static FieldInfo? f_RuntimeModule__impl; private static MethodInfo? m_RuntimeModule_GetGlobalType; private static readonly FieldInfo? f_SignatureHelper_module; private static MemberInfo _Cache(string cacheKey, MemberInfo value) { if (cacheKey != null && value == null) { bool isEnabled; MMDbgLog.DebugLogErrorStringHandler message = new MMDbgLog.DebugLogErrorStringHandler(21, 1, out isEnabled); if (isEnabled) { message.AppendLiteral("ResolveRefl failure: "); message.AppendFormatted(cacheKey); } MMDbgLog.Error(ref message); } if (cacheKey != null && value != null) { lock (ResolveReflectionCache) { ResolveReflectionCache[cacheKey] = new WeakReference(value); } } return value; } public static Assembly Load(ModuleDefinition module) { Helpers.ThrowIfArgumentNull(module, "module"); using MemoryStream memoryStream = new MemoryStream(); module.Write((Stream)memoryStream); memoryStream.Seek(0L, SeekOrigin.Begin); return Load((Stream)memoryStream); } public static Assembly Load(Stream stream) { Helpers.ThrowIfArgumentNull(stream, "stream"); Assembly asm; if (stream is MemoryStream memoryStream) { asm = Assembly.Load(memoryStream.GetBuffer()); } else { using MemoryStream memoryStream2 = new MemoryStream(); stream.CopyTo(memoryStream2); memoryStream2.Seek(0L, SeekOrigin.Begin); asm = Assembly.Load(memoryStream2.GetBuffer()); } AppDomain.CurrentDomain.AssemblyResolve += (object? s, ResolveEventArgs e) => (!(e.Name == asm.FullName)) ? null : asm; return asm; } public static Type? GetType(string name) { if (string.IsNullOrEmpty(name)) { return null; } Type type = Type.GetType(name); if (type != null) { return type; } Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { type = assemblies[i].GetType(name); if (type != null) { return type; } } return null; } public static bool HashIs(this AssemblyNameReference asmRef, Assembly asm, bool defaultIfNoHash = true) { Helpers.ThrowIfArgumentNull(asmRef, "asmRef"); Helpers.ThrowIfArgumentNull(asm, "asm"); if (asmRef.Hash?.Length == AssemblyHashPrefix.Length + 4) { byte[] hash = asmRef.Hash; for (int i = 0; i < AssemblyHashPrefix.Length; i++) { if (hash[i] != AssemblyHashPrefix[i]) { return false; } } byte[] bytes = BitConverter.GetBytes(asm.GetHashCode()); for (int j = 0; j < 4; j++) { if (hash[AssemblyHashPrefix.Length + j] != bytes[j]) { return false; } } return true; } return defaultIfNoHash; } public static void ApplyRuntimeHash(this AssemblyNameReference asmRef, Assembly asm) { Helpers.ThrowIfArgumentNull(asmRef, "asmRef"); Helpers.ThrowIfArgumentNull(asm, "asm"); byte[] array = new byte[AssemblyHashPrefix.Length + 4]; Array.Copy(AssemblyHashPrefix, 0, array, 0, AssemblyHashPrefix.Length); Array.Copy(BitConverter.GetBytes(asm.GetHashCode()), 0, array, AssemblyHashPrefix.Length, 4); asmRef.HashAlgorithm = (AssemblyHashAlgorithm)(-1); asmRef.Hash = array; } public static string GetRuntimeHashedFullName(this Assembly asm) { Helpers.ThrowIfArgumentNull(asm, "asm"); return $"{asm.FullName}{AssemblyHashNameTag}{asm.GetHashCode()}"; } public static string GetRuntimeHashedFullName(this AssemblyNameReference asm) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Invalid comparison between Unknown and I4 Helpers.ThrowIfArgumentNull(asm, "asm"); if ((int)asm.HashAlgorithm != -1) { return asm.FullName; } byte[] hash = asm.Hash; if (hash.Length != AssemblyHashPrefix.Length + 4) { return asm.FullName; } for (int i = 0; i < AssemblyHashPrefix.Length; i++) { if (hash[i] != AssemblyHashPrefix[i]) { return asm.FullName; } } return $"{asm.FullName}{AssemblyHashNameTag}{BitConverter.ToInt32(hash, AssemblyHashPrefix.Length)}"; } public static Type ResolveReflection(this TypeReference mref) { return (Type)_ResolveReflection((MemberReference?)(object)mref, null); } public static MethodBase ResolveReflection(this MethodReference mref) { return (MethodBase)_ResolveReflection((MemberReference?)(object)mref, null); } public static FieldInfo ResolveReflection(this FieldReference mref) { return (FieldInfo)_ResolveReflection((MemberReference?)(object)mref, null); } public static PropertyInfo ResolveReflection(this PropertyReference mref) { return (PropertyInfo)_ResolveReflection((MemberReference?)(object)mref, null); } public static EventInfo ResolveReflection(this EventReference mref) { return (EventInfo)_ResolveReflection((MemberReference?)(object)mref, null); } public static MemberInfo ResolveReflection(this MemberReference mref) { return _ResolveReflection(mref, null); } [return: NotNullIfNotNull("mref")] private static MemberInfo? _ResolveReflection(MemberReference? mref, Module[]? modules) { //IL_05e5: Unknown result type (might be due to invalid IL or missing references) //IL_0629: Unknown result type (might be due to invalid IL or missing references) //IL_05f5: Unknown result type (might be due to invalid IL or missing references) if (mref == null) { return null; } if (mref is DynamicMethodReference dynamicMethodReference) { return dynamicMethodReference.DynamicMethod; } MemberReference? obj = mref; string text = ((MethodReference)(object)((obj is MethodReference) ? obj : null))?.GetID() ?? mref.FullName; TypeReference val = (TypeReference)(((object)mref.DeclaringType) ?? ((object)(((mref is TypeReference) ? mref : null) ?? null))); var (asmName, moduleName) = GetScope(mref); if (mref is IGenericInstance) { IEnumerable source = GetGenericArgumentsRecursive(mref).Select(delegate(MemberReference x) { var (asmName2, moduleName2) = GetScope(x); return ToCacheKeyPart(asmName2, moduleName2); }); text = string.Concat(text, string.Concat(source.ToArray())); } else { text += ToCacheKeyPart(asmName, moduleName); } lock (ResolveReflectionCache) { if (ResolveReflectionCache.TryGetValue(text, out WeakReference value) && value != null && value.SafeGetTarget() is MemberInfo result) { return result; } } if (mref is GenericParameter) { throw new NotSupportedException("ResolveReflection on GenericParameter currently not supported"); } MemberReference? obj2 = mref; MethodReference val2 = (MethodReference)(object)((obj2 is MethodReference) ? obj2 : null); if (val2 != null && mref.DeclaringType is ArrayType) { Type type = (Type)_ResolveReflection((MemberReference?)(object)mref.DeclaringType, modules); string methodID = val2.GetID(null, null, withType: false); MethodBase methodBase = type.GetMethods((BindingFlags)(-1)).Cast().Concat(type.GetConstructors((BindingFlags)(-1))) .FirstOrDefault((MethodBase m) => m.GetID(null, null, withType: false) == methodID); if (methodBase != null) { return _Cache(text, methodBase); } } if (val == null) { throw new ArgumentException("MemberReference hasn't got a DeclaringType / isn't a TypeReference in itself"); } if (asmName == null && moduleName == null) { throw new NotSupportedException("Unsupported scope type " + ((object)val.Scope).GetType().FullName); } bool flag = true; bool flag2 = false; bool flag3 = false; MemberInfo memberInfo; while (true) { if (flag3) { modules = null; } flag3 = true; if (modules == null) { Assembly[] array = null; if (flag && flag2) { flag2 = false; flag = false; } if (flag) { lock (AssemblyCache) { if (AssemblyCache.TryGetValue(asmName, out WeakReference value2) && value2.SafeGetTarget() is Assembly assembly) { array = new Assembly[1] { assembly }; } } } if (array == null && !flag2) { lock (AssembliesCache) { if (AssembliesCache.TryGetValue(asmName, out WeakReference[] value3)) { array = (from asmRef in value3 select asmRef.SafeGetTarget() as Assembly into asm where asm != null select asm).ToArray(); } } } if (array == null) { int num = asmName.IndexOf(AssemblyHashNameTag, StringComparison.Ordinal); if (num != -1 && int.TryParse(asmName.Substring(num + 2), out var hash)) { array = (from other in AppDomain.CurrentDomain.GetAssemblies() where other.GetHashCode() == hash select other).ToArray(); if (array.Length == 0) { array = null; } asmName = asmName.Substring(0, num); } if (array == null) { array = (from other in AppDomain.CurrentDomain.GetAssemblies() where other.GetName().FullName == asmName select other).ToArray(); if (array.Length == 0) { array = (from other in AppDomain.CurrentDomain.GetAssemblies() where other.GetName().Name == asmName select other).ToArray(); } if (array.Length == 0) { Assembly assembly2 = Assembly.Load(new AssemblyName(asmName)); if ((object)assembly2 != null) { array = new Assembly[1] { assembly2 }; } } } if (array.Length != 0) { lock (AssembliesCache) { AssembliesCache[asmName] = array.Select((Assembly asm) => new WeakReference(asm)).ToArray(); } } } modules = (string.IsNullOrEmpty(moduleName) ? array.SelectMany((Assembly asm) => asm.GetModules()) : array.Select((Assembly asm) => asm.GetModule(moduleName))).Where((Module mod) => mod != null).ToArray(); if (modules.Length == 0) { throw new MissingMemberException("Cannot resolve assembly / module " + asmName + " / " + moduleName); } } MemberReference? obj3 = mref; TypeReference val3 = (TypeReference)(object)((obj3 is TypeReference) ? obj3 : null); if (val3 != null) { if (((MemberReference)val3).FullName == "") { throw new ArgumentException("Type cannot be resolved to a runtime reflection type"); } MemberReference? obj4 = mref; TypeSpecification val4 = (TypeSpecification)(object)((obj4 is TypeSpecification) ? obj4 : null); Type type; if (val4 != null) { type = (Type)_ResolveReflection((MemberReference?)(object)val4.ElementType, null); if (((TypeReference)val4).IsByReference) { return _Cache(text, type.MakeByRefType()); } if (((TypeReference)val4).IsPointer) { return _Cache(text, type.MakePointerType()); } if (((TypeReference)val4).IsArray) { return _Cache(text, ((ArrayType)val4).IsVector ? type.MakeArrayType() : type.MakeArrayType(((ArrayType)val4).Dimensions.Count)); } if (((TypeReference)val4).IsGenericInstance) { return _Cache(text, type.MakeGenericType(((IEnumerable)((GenericInstanceType)val4).GenericArguments).Select((TypeReference arg) => _ResolveReflection((MemberReference?)(object)arg, null) as Type).ToArray())); } } else { type = modules.Select((Module module) => module.GetType(mref.FullName.Replace("/", "+", StringComparison.Ordinal), throwOnError: false, ignoreCase: false)).FirstOrDefault((Type m) => m != null); if (type == null) { type = modules.Select((Module module) => module.GetTypes().FirstOrDefault((Type m) => mref.Is(m))).FirstOrDefault((Type m) => m != null); } if (type == null && !flag2) { goto IL_0252; } } return _Cache(text, type); } TypeReference declaringType = mref.DeclaringType; bool flag4 = ((declaringType != null) ? ((MemberReference)declaringType).FullName : null) == ""; MemberReference? obj5 = mref; GenericInstanceMethod val5 = (GenericInstanceMethod)(object)((obj5 is GenericInstanceMethod) ? obj5 : null); if (val5 != null) { memberInfo = _ResolveReflection((MemberReference?)(object)((MethodSpecification)val5).ElementMethod, modules); memberInfo = (memberInfo as MethodInfo)?.MakeGenericMethod(((IEnumerable)val5.GenericArguments).Select((TypeReference arg) => _ResolveReflection((MemberReference?)(object)arg, null) as Type).ToArray()); } else if (flag4) { if (mref is MethodReference) { memberInfo = modules.Select((Module module) => module.GetMethods((BindingFlags)(-1)).FirstOrDefault((MethodInfo m) => mref.Is(m))).FirstOrDefault((MethodInfo m) => m != null); } else { if (!(mref is FieldReference)) { throw new NotSupportedException("Unsupported member type " + ((object)mref).GetType().FullName); } memberInfo = modules.Select((Module module) => module.GetFields((BindingFlags)(-1)).FirstOrDefault((FieldInfo m) => mref.Is(m))).FirstOrDefault((FieldInfo m) => m != null); } } else { Type type2 = (Type)_ResolveReflection((MemberReference?)(object)mref.DeclaringType, modules); memberInfo = ((mref is MethodReference) ? type2.GetMethods((BindingFlags)(-1)).Cast().Concat(type2.GetConstructors((BindingFlags)(-1))) .FirstOrDefault((MethodBase m) => mref.Is(m)) : ((!(mref is FieldReference)) ? type2.GetMembers((BindingFlags)(-1)).FirstOrDefault((MemberInfo m) => mref.Is(m)) : type2.GetFields((BindingFlags)(-1)).FirstOrDefault((FieldInfo m) => mref.Is(m)))); } if (!(memberInfo == null) || flag2) { break; } goto IL_0252; IL_0252: flag2 = true; } return _Cache(text, memberInfo); static IEnumerable GetGenericArgumentsRecursive(MemberReference val6) { yield return val6; TypeReference declaringType2 = val6.DeclaringType; IGenericInstance val7 = (IGenericInstance)(object)((declaringType2 is IGenericInstance) ? declaringType2 : null); if (val7 != null) { Enumerator enumerator = val7.GenericArguments.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeReference current = enumerator.Current; foreach (MemberReference item in GetGenericArgumentsRecursive((MemberReference)(object)current)) { yield return item; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } } IGenericInstance val8 = (IGenericInstance)(object)((val6 is IGenericInstance) ? val6 : null); if (val8 != null) { Enumerator enumerator = val8.GenericArguments.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeReference current2 = enumerator.Current; foreach (MemberReference item2 in GetGenericArgumentsRecursive((MemberReference)(object)current2)) { yield return item2; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } } } static (string?, string?) GetScope(MemberReference val7) { TypeReference val6 = (TypeReference)(((object)val7.DeclaringType) ?? ((object)(((val7 is TypeReference) ? val7 : null) ?? null))); IMetadataScope val8 = ((val6 != null) ? val6.Scope : null); AssemblyNameReference val9 = (AssemblyNameReference)(object)((val8 is AssemblyNameReference) ? val8 : null); if (val9 != null) { return (val9.GetRuntimeHashedFullName(), null); } ModuleDefinition val10 = (ModuleDefinition)(object)((val8 is ModuleDefinition) ? val8 : null); if (val10 != null) { return (((AssemblyNameReference)(object)val10.Assembly.Name).GetRuntimeHashedFullName(), ((ModuleReference)val10).Name); } if (val8 is ModuleReference) { return (((AssemblyNameReference)(object)((MemberReference)val6).Module.Assembly.Name).GetRuntimeHashedFullName(), ((ModuleReference)((MemberReference)val6).Module).Name); } return (null, null); } static string ToCacheKeyPart(string? text2, string? text3) { return " | " + (text2 ?? "NOASSEMBLY") + ", " + (text3 ?? "NOMODULE"); } } public static SignatureHelper ResolveReflection(this CallSite csite, Module context) { return ((IMethodSignature)(object)csite).ResolveReflectionSignature(context); } public static SignatureHelper ResolveReflectionSignature(this IMethodSignature csite, Module context) { //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_001d: 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_0039: Expected I4, but got Unknown //IL_020b: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) Helpers.ThrowIfArgumentNull(csite, "csite"); Helpers.ThrowIfArgumentNull(context, "context"); MethodCallingConvention callingConvention = csite.CallingConvention; SignatureHelper signatureHelper = (callingConvention - 1) switch { 0 => GetUnmanagedSigHelper(context, CallingConvention.Cdecl, csite.ReturnType.ResolveReflection()), 1 => GetUnmanagedSigHelper(context, CallingConvention.StdCall, csite.ReturnType.ResolveReflection()), 2 => GetUnmanagedSigHelper(context, CallingConvention.ThisCall, csite.ReturnType.ResolveReflection()), 3 => GetUnmanagedSigHelper(context, CallingConvention.FastCall, csite.ReturnType.ResolveReflection()), 4 => SignatureHelper.GetMethodSigHelper(context, CallingConventions.VarArgs, csite.ReturnType.ResolveReflection()), _ => (!csite.ExplicitThis) ? SignatureHelper.GetMethodSigHelper(context, CallingConventions.Standard, csite.ReturnType.ResolveReflection()) : SignatureHelper.GetMethodSigHelper(context, CallingConventions.ExplicitThis, csite.ReturnType.ResolveReflection()), }; if (context != null) { List list = new List(); List list2 = new List(); Enumerator enumerator = csite.Parameters.GetEnumerator(); try { while (enumerator.MoveNext()) { ParameterDefinition current = enumerator.Current; if (((ParameterReference)current).ParameterType.IsSentinel) { signatureHelper.AddSentinel(); } if (((ParameterReference)current).ParameterType.IsPinned) { signatureHelper.AddArgument(((ParameterReference)current).ParameterType.ResolveReflection(), pinned: true); continue; } list2.Clear(); list.Clear(); TypeReference val = ((ParameterReference)current).ParameterType; while (true) { TypeSpecification val2 = (TypeSpecification)(object)((val is TypeSpecification) ? val : null); if (val2 == null) { break; } RequiredModifierType val3 = (RequiredModifierType)(object)((val is RequiredModifierType) ? val : null); if (val3 == null) { OptionalModifierType val4 = (OptionalModifierType)(object)((val is OptionalModifierType) ? val : null); if (val4 != null) { list2.Add(val4.ModifierType.ResolveReflection()); } } else { list.Add(val3.ModifierType.ResolveReflection()); } val = val2.ElementType; } signatureHelper.AddArgument(((ParameterReference)current).ParameterType.ResolveReflection(), list.ToArray(), list2.ToArray()); } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } } else { Enumerator enumerator = csite.Parameters.GetEnumerator(); try { while (enumerator.MoveNext()) { ParameterDefinition current2 = enumerator.Current; signatureHelper.AddArgument(((ParameterReference)current2).ParameterType.ResolveReflection()); } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } } return signatureHelper; } static ReflectionHelper() { IsCoreBCL = typeof(object).Assembly.GetName().Name == "System.Private.CoreLib"; AssemblyCache = new Dictionary(); AssembliesCache = new Dictionary(); ResolveReflectionCache = new Dictionary(); AssemblyHashPrefix = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes("MonoModRefl").Concat(new byte[1]).ToArray(); AssemblyHashNameTag = "@#"; GetUnmanagedSigHelperMethod = typeof(SignatureHelper).GetMethod("GetMethodSigHelper", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[3] { typeof(Module), typeof(CallingConvention), typeof(Type) }, null); GetUnmanagedSigHelper = GetUnmanagedSigHelperMethod?.TryCreateDelegate() ?? ((GetUnmanagedSigHelperDelegate)delegate { throw new NotImplementedException("Unmanaged calling conventions are not supported"); }); _CacheGetterArgs = new object[2] { 0, null }; t_RuntimeType = typeof(Type).Assembly.GetType("System.RuntimeType"); t_RuntimeTypeCache = t_RuntimeType?.GetNestedType("RuntimeTypeCache", BindingFlags.Public | BindingFlags.NonPublic); p_RuntimeType_Cache = ((t_RuntimeTypeCache == null) ? null : t_RuntimeType?.GetProperty("Cache", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, t_RuntimeTypeCache, Type.EmptyTypes, null)); m_RuntimeTypeCache_GetFieldList = t_RuntimeTypeCache?.GetMethod("GetFieldList", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); m_RuntimeTypeCache_GetPropertyList = t_RuntimeTypeCache?.GetMethod("GetPropertyList", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); _CacheFixed = new ConditionalWeakTable(); t_RuntimeModule = typeof(Module).Assembly.GetType("System.Reflection.RuntimeModule"); p_RuntimeModule_RuntimeType = typeof(Module).Assembly.GetType("System.Reflection.RuntimeModule")?.GetProperty("RuntimeType", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); f_RuntimeModule__impl = typeof(Module).Assembly.GetType("System.Reflection.RuntimeModule")?.GetField("_impl", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); m_RuntimeModule_GetGlobalType = typeof(Module).Assembly.GetType("System.Reflection.RuntimeModule")?.GetMethod("GetGlobalType", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); f_SignatureHelper_module = typeof(SignatureHelper).GetField("m_module", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? typeof(SignatureHelper).GetField("module", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } public static void FixReflectionCacheAuto(this Type type) { } public static void FixReflectionCache(this Type? type) { if (t_RuntimeType == null || p_RuntimeType_Cache == null || m_RuntimeTypeCache_GetFieldList == null || m_RuntimeTypeCache_GetPropertyList == null) { return; } while (type != null) { if (t_RuntimeType.IsInstanceOfType(type)) { CacheFixEntry value = _CacheFixed.GetValue(type, delegate(Type rt) { CacheFixEntry cacheFixEntry = new CacheFixEntry(); object cache = (cacheFixEntry.Cache = p_RuntimeType_Cache.GetValue(rt, ArrayEx.Empty())); Array orig = (cacheFixEntry.Properties = _GetArray(cache, m_RuntimeTypeCache_GetPropertyList)); Array orig2 = (cacheFixEntry.Fields = _GetArray(cache, m_RuntimeTypeCache_GetFieldList)); _FixReflectionCacheOrder(orig); _FixReflectionCacheOrder(orig2); cacheFixEntry.NeedsVerify = false; return cacheFixEntry; }); if (value.NeedsVerify && !_Verify(value, type)) { lock (value) { _FixReflectionCacheOrder(value.Properties); _FixReflectionCacheOrder(value.Fields); } } value.NeedsVerify = true; } type = type.DeclaringType; } } private static bool _Verify(CacheFixEntry entry, Type type) { object value; if (entry.Cache != (value = p_RuntimeType_Cache.GetValue(type, ArrayEx.Empty()))) { entry.Cache = value; entry.Properties = _GetArray(value, m_RuntimeTypeCache_GetPropertyList); entry.Fields = _GetArray(value, m_RuntimeTypeCache_GetFieldList); return false; } Array properties; if (entry.Properties != (properties = _GetArray(value, m_RuntimeTypeCache_GetPropertyList))) { entry.Properties = properties; entry.Fields = _GetArray(value, m_RuntimeTypeCache_GetFieldList); return false; } Array fields; if (entry.Fields != (fields = _GetArray(value, m_RuntimeTypeCache_GetFieldList))) { entry.Fields = fields; return false; } return true; } private static Array _GetArray(object? cache, MethodInfo getter) { getter.Invoke(cache, _CacheGetterArgs); object obj = getter.Invoke(cache, _CacheGetterArgs); if (obj is Array result) { return result; } Type returnType = getter.ReturnType; if ((object)returnType != null && returnType.Namespace == "System.Reflection" && returnType.Name == "CerArrayList`1") { return (Array)returnType.GetField("m_array", (BindingFlags)(-1)).GetValue(obj); } throw new InvalidOperationException($"Unknown reflection cache type {obj.GetType()}"); } private static void _FixReflectionCacheOrder(Array? orig) where T : MemberInfo { if (orig == null) { return; } List list = new List(orig.Length); for (int i = 0; i < orig.Length; i++) { list.Add((T)orig.GetValue(i)); } list.Sort(delegate(T? a, T? b) { if (a == b) { return 0; } if ((object)a == null) { return 1; } return ((object)b == null) ? (-1) : (a.MetadataToken - b.MetadataToken); }); for (int num = orig.Length - 1; num >= 0; num--) { orig.SetValue(list[num], num); } } public static Type? GetModuleType(this Module? module) { if (module == null || t_RuntimeModule == null || !t_RuntimeModule.IsInstanceOfType(module)) { return null; } if (p_RuntimeModule_RuntimeType != null) { return (Type)p_RuntimeModule_RuntimeType.GetValue(module, ArrayEx.Empty()); } if (f_RuntimeModule__impl != null && m_RuntimeModule_GetGlobalType != null) { return (Type)m_RuntimeModule_GetGlobalType.Invoke(null, new object[1] { f_RuntimeModule__impl.GetValue(module) }); } return null; } public static Type? GetRealDeclaringType(this MemberInfo member) { Type? type = Helpers.ThrowIfNull(member, "member").DeclaringType; if ((object)type == null) { Module module = member.Module; if ((object)module == null) { return null; } type = module.GetModuleType(); } return type; } private static Module GetSignatureHelperModule(SignatureHelper signature) { if (f_SignatureHelper_module == null) { throw new InvalidOperationException("Unable to find module field for SignatureHelper"); } return (Module)f_SignatureHelper_module.GetValue(signature); } public static CallSite ImportCallSite(this ModuleDefinition moduleTo, ICallSiteGenerator signature) { return Helpers.ThrowIfNull(signature, "signature").ToCallSite(moduleTo); } public static CallSite ImportCallSite(this ModuleDefinition moduleTo, SignatureHelper signature) { return Helpers.ThrowIfNull(moduleTo, "moduleTo").ImportCallSite(GetSignatureHelperModule(signature), Helpers.ThrowIfNull(signature, "signature").GetSignature()); } public static CallSite ImportCallSite(this ModuleDefinition moduleTo, Module moduleFrom, int token) { return Helpers.ThrowIfNull(moduleTo, "moduleTo").ImportCallSite(moduleFrom, Helpers.ThrowIfNull(moduleFrom, "moduleFrom").ResolveSignature(token)); } public static CallSite ImportCallSite(this ModuleDefinition moduleTo, Module moduleFrom, byte[] data) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown Helpers.ThrowIfArgumentNull(moduleTo, "moduleTo"); Helpers.ThrowIfArgumentNull(moduleFrom, "moduleFrom"); Helpers.ThrowIfArgumentNull(data, "data"); CallSite val = new CallSite(moduleTo.TypeSystem.Void); BinaryReader reader; using (MemoryStream input = new MemoryStream(data, writable: false)) { reader = new BinaryReader(input); try { ReadMethodSignature((IMethodSignature)(object)val); return val; } finally { if (reader != null) { ((IDisposable)reader).Dispose(); } } void ReadMethodSignature(IMethodSignature method) { //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Expected O, but got Unknown byte b = reader.ReadByte(); if ((b & 0x20) != 0) { method.HasThis = true; b = (byte)(b & -33); } if ((b & 0x40) != 0) { method.ExplicitThis = true; b = (byte)(b & -65); } method.CallingConvention = (MethodCallingConvention)b; if ((b & 0x10) != 0) { ReadCompressedUInt(); } uint num = ReadCompressedUInt(); method.MethodReturnType.ReturnType = ReadTypeSignature(); for (int i = 0; i < num; i++) { method.Parameters.Add(new ParameterDefinition(ReadTypeSignature())); } } } TypeReference GetTypeDefOrRef() { uint num = ReadCompressedUInt(); uint num2 = num >> 2; return moduleTo.ImportReference(moduleFrom.ResolveType((num & 3) switch { 0u => (int)(0x2000000 | num2), 1u => (int)(0x1000000 | num2), 2u => (int)(0x1B000000 | num2), _ => 0, })); } int ReadCompressedInt() { byte b = reader.ReadByte(); reader.BaseStream.Seek(-1L, SeekOrigin.Current); uint num = ReadCompressedUInt(); int num2 = (int)num >> 1; if ((num & 1) == 0) { return num2; } switch (b & 0xC0) { case 0: case 64: return num2 - 64; case 128: return num2 - 8192; default: return num2 - 268435456; } } uint ReadCompressedUInt() { byte b = reader.ReadByte(); if ((b & 0x80) == 0) { return b; } if ((b & 0x40) == 0) { return (uint)(((b & -129) << 8) | reader.ReadByte()); } return (uint)(((b & -193) << 24) | (reader.ReadByte() << 16) | (reader.ReadByte() << 8) | reader.ReadByte()); } TypeReference ReadTypeSignature() { //IL_000b: 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_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Expected I4, but got Unknown //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Expected O, but got Unknown //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Expected O, but got Unknown //IL_0234: 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_00fd: Expected O, but got Unknown //IL_0391: 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_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Expected O, but got Unknown //IL_00c9: Expected O, but got Unknown //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Expected O, but got Unknown //IL_0209: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Expected O, but got Unknown //IL_01f5: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Expected O, but got Unknown //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Invalid comparison between Unknown and I4 //IL_0216: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Expected O, but got Unknown //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Invalid comparison between Unknown and I4 //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Expected O, but got Unknown //IL_01ce: Unknown result type (might be due to invalid IL or missing references) MetadataType val2 = (MetadataType)reader.ReadByte(); switch (val2 - 1) { default: if ((int)val2 == 65) { return (TypeReference)new SentinelType(ReadTypeSignature()); } if ((int)val2 == 69) { return (TypeReference)new PinnedType(ReadTypeSignature()); } break; case 16: case 17: return GetTypeDefOrRef(); case 14: return (TypeReference)new PointerType(ReadTypeSignature()); case 26: { FunctionPointerType val4 = new FunctionPointerType(); ReadMethodSignature((IMethodSignature)val4); return (TypeReference)val4; } case 15: return (TypeReference)new ByReferenceType(ReadTypeSignature()); case 28: return (TypeReference)new ArrayType(ReadTypeSignature()); case 19: { ArrayType val3 = new ArrayType(ReadTypeSignature()); uint num = ReadCompressedUInt(); uint[] array = new uint[ReadCompressedUInt()]; for (int i = 0; i < array.Length; i++) { array[i] = ReadCompressedUInt(); } int[] array2 = new int[ReadCompressedUInt()]; for (int j = 0; j < array2.Length; j++) { array2[j] = ReadCompressedInt(); } val3.Dimensions.Clear(); for (int k = 0; k < num; k++) { int? num2 = null; int? num3 = null; if (k < array2.Length) { num2 = array2[k]; } if (k < array.Length) { num3 = num2 + (int)array[k] - 1; } val3.Dimensions.Add(new ArrayDimension(num2, num3)); } return (TypeReference)(object)val3; } case 31: return (TypeReference)new OptionalModifierType(GetTypeDefOrRef(), ReadTypeSignature()); case 30: return (TypeReference)new RequiredModifierType(GetTypeDefOrRef(), ReadTypeSignature()); case 18: case 20: case 29: throw new NotSupportedException($"Unsupported generic callsite element: {val2}"); case 27: return moduleTo.TypeSystem.Object; case 0: return moduleTo.TypeSystem.Void; case 21: return moduleTo.TypeSystem.TypedReference; case 23: return moduleTo.TypeSystem.IntPtr; case 24: return moduleTo.TypeSystem.UIntPtr; case 1: return moduleTo.TypeSystem.Boolean; case 2: return moduleTo.TypeSystem.Char; case 3: return moduleTo.TypeSystem.SByte; case 4: return moduleTo.TypeSystem.Byte; case 5: return moduleTo.TypeSystem.Int16; case 6: return moduleTo.TypeSystem.UInt16; case 7: return moduleTo.TypeSystem.Int32; case 8: return moduleTo.TypeSystem.UInt32; case 9: return moduleTo.TypeSystem.Int64; case 10: return moduleTo.TypeSystem.UInt64; case 11: return moduleTo.TypeSystem.Single; case 12: return moduleTo.TypeSystem.Double; case 13: return moduleTo.TypeSystem.String; case 22: case 25: break; } throw new NotSupportedException($"Unsupported callsite element: {val2}"); } } } [Serializable] public class RelinkFailedException : Exception { public const string DefaultMessage = "MonoMod failed relinking"; public IMetadataTokenProvider MTP { get; } public IMetadataTokenProvider? Context { get; } public RelinkFailedException(IMetadataTokenProvider mtp, IMetadataTokenProvider? context = null) : this(Format("MonoMod failed relinking", mtp, context), mtp, context) { } public RelinkFailedException(string message, IMetadataTokenProvider mtp, IMetadataTokenProvider? context = null) : base(message) { MTP = mtp; Context = context; } public RelinkFailedException(string message, Exception innerException, IMetadataTokenProvider mtp, IMetadataTokenProvider? context = null) : base(message ?? Format("MonoMod failed relinking", mtp, context), innerException) { MTP = mtp; Context = context; } protected static string Format(string message, IMetadataTokenProvider mtp, IMetadataTokenProvider? context) { if (mtp == null && context == null) { return message; } StringBuilder stringBuilder = new StringBuilder(message); stringBuilder.Append(' '); if (mtp != null) { stringBuilder.Append(((object)mtp).ToString()); } if (context != null) { stringBuilder.Append(' '); } if (context != null) { stringBuilder.Append("(context: ").Append(((object)context).ToString()).Append(')'); } return stringBuilder.ToString(); } } [Serializable] public class RelinkTargetNotFoundException : RelinkFailedException { public new const string DefaultMessage = "MonoMod relinker failed finding"; public RelinkTargetNotFoundException(IMetadataTokenProvider mtp, IMetadataTokenProvider? context = null) : base(RelinkFailedException.Format("MonoMod relinker failed finding", mtp, context), mtp, context) { } public RelinkTargetNotFoundException(string message, IMetadataTokenProvider mtp, IMetadataTokenProvider? context = null) : base(message ?? "MonoMod relinker failed finding", mtp, context) { } public RelinkTargetNotFoundException(string message, Exception innerException, IMetadataTokenProvider mtp, IMetadataTokenProvider? context = null) : base(message ?? "MonoMod relinker failed finding", innerException, mtp, context) { } } public enum RuntimeKind { Unknown, Framework, CoreCLR, Mono } public sealed class WeakReferenceComparer : EqualityComparer { public override bool Equals(WeakReference? x, WeakReference? y) { if (x?.SafeGetTarget() == y?.SafeGetTarget()) { return x?.SafeGetIsAlive() == y?.SafeGetIsAlive(); } return false; } public override int GetHashCode(WeakReference obj) { return obj.SafeGetTarget()?.GetHashCode() ?? 0; } } internal static class AssemblyInfo { public const string AssemblyName = "MonoMod.Utils"; public const string AssemblyVersion = "25.0.12"; } } namespace MonoMod.Utils.Interop { internal static class OSX { public const string LibSystem = "libSystem"; [LibraryImport("libSystem", EntryPoint = "uname", SetLastError = true)] [GeneratedCode("Microsoft.Interop.LibraryImportGenerator", "8.0.13.2707")] [SkipLocalsInit] public unsafe static int Uname(byte* buf) { Marshal.SetLastSystemError(0); int result = __PInvoke(buf); Marshal.SetLastPInvokeError(Marshal.GetLastSystemError()); return result; [DllImport("libSystem", EntryPoint = "uname", ExactSpelling = true)] static extern unsafe int __PInvoke(byte* __buf_native); } } internal static class Unix { public struct LinuxAuxvEntry { public nint Key; public nint Value; } public enum DlopenFlags { RTLD_LAZY = 1, RTLD_NOW = 2, RTLD_LOCAL = 0, RTLD_GLOBAL = 256 } private enum LibDlType { LibC, LibDl2 } public const string LibC = "libc"; public const string DL2 = "libdl.so.2"; public const int AT_PLATFORM = 15; private static LibDlType? currentLibDlType = DetermineLibDlType(); [LibraryImport("libc", EntryPoint = "uname", SetLastError = true)] [GeneratedCode("Microsoft.Interop.LibraryImportGenerator", "8.0.13.2707")] [SkipLocalsInit] public unsafe static int Uname(byte* buf) { Marshal.SetLastSystemError(0); int result = __PInvoke(buf); Marshal.SetLastPInvokeError(Marshal.GetLastSystemError()); return result; [DllImport("libc", EntryPoint = "uname", ExactSpelling = true)] static extern unsafe int __PInvoke(byte* __buf_native); } [DllImport("libc", CallingConvention = CallingConvention.Cdecl, EntryPoint = "dlopen")] private unsafe static extern nint LibCdlopen(byte* filename, DlopenFlags flags); [DllImport("libc", CallingConvention = CallingConvention.Cdecl, EntryPoint = "dlclose")] private static extern int LibCdlclose(nint handle); [DllImport("libc", CallingConvention = CallingConvention.Cdecl, EntryPoint = "dlsym")] private unsafe static extern nint LibCdlsym(nint handle, byte* symbol); [DllImport("libc", CallingConvention = CallingConvention.Cdecl, EntryPoint = "dlerror")] private static extern nint LibCdlerror(); [DllImport("libdl.so.2", CallingConvention = CallingConvention.Cdecl, EntryPoint = "dlopen")] private unsafe static extern nint DL2dlopen(byte* filename, DlopenFlags flags); [DllImport("libdl.so.2", CallingConvention = CallingConvention.Cdecl, EntryPoint = "dlclose")] private static extern int DL2dlclose(nint handle); [DllImport("libdl.so.2", CallingConvention = CallingConvention.Cdecl, EntryPoint = "dlsym")] private unsafe static extern nint DL2dlsym(nint handle, byte* symbol); [DllImport("libdl.so.2", CallingConvention = CallingConvention.Cdecl, EntryPoint = "dlerror")] private static extern nint DL2dlerror(); internal static byte[]? MarshalToUtf8(string? str) { if (str == null) { return null; } int byteCount = Encoding.UTF8.GetByteCount(str); byte[] array = ArrayPool.Shared.Rent(byteCount + 1); array.AsSpan().Clear(); Encoding.UTF8.GetBytes(str, 0, str.Length, array, 0); return array; } internal static void FreeMarshalledArray(byte[]? arr) { if (arr != null) { ArrayPool.Shared.Return(arr); } } private static LibDlType DetermineLibDlType() { try { LibCdlerror(); return LibDlType.LibC; } catch (DllNotFoundException) { } catch (EntryPointNotFoundException) { } try { DL2dlerror(); return LibDlType.LibDl2; } catch (DllNotFoundException) { } throw new PlatformNotSupportedException("Could not find the library containing dynamic linker functions"); } public unsafe static nint DlOpen(string? filename, DlopenFlags flags) { byte[] array = MarshalToUtf8(filename); try { fixed (byte* filename2 = array) { return currentLibDlType switch { LibDlType.LibC => LibCdlopen(filename2, flags), LibDlType.LibDl2 => DL2dlopen(filename2, flags), _ => throw new InvalidOperationException(), }; } } finally { FreeMarshalledArray(array); } } public static bool DlClose(nint handle) { return currentLibDlType switch { LibDlType.LibC => LibCdlclose(handle) == 0, LibDlType.LibDl2 => DL2dlclose(handle) == 0, _ => throw new InvalidOperationException(), }; } public unsafe static nint DlSym(nint handle, string symbol) { byte[] array = MarshalToUtf8(symbol); try { fixed (byte* symbol2 = array) { return currentLibDlType switch { LibDlType.LibC => LibCdlsym(handle, symbol2), LibDlType.LibDl2 => DL2dlsym(handle, symbol2), _ => throw new InvalidOperationException(), }; } } finally { FreeMarshalledArray(array); } } public static nint DlError() { return currentLibDlType switch { LibDlType.LibC => LibCdlerror(), LibDlType.LibDl2 => DL2dlerror(), _ => throw new InvalidOperationException(), }; } } internal static class Windows { [Conditional("NEVER")] [AttributeUsage(AttributeTargets.All)] private sealed class SetsLastSystemErrorAttribute : Attribute { } [Conditional("NEVER")] [AttributeUsage(AttributeTargets.All)] private sealed class NativeTypeNameAttribute : Attribute { public NativeTypeNameAttribute(string x) { } } public struct SYSTEM_INFO { [StructLayout(LayoutKind.Explicit)] public struct _Anonymous_e__Union { public struct _Anonymous_e__Struct { public ushort wProcessorArchitecture; public ushort wReserved; } [FieldOffset(0)] public uint dwOemId; [FieldOffset(0)] public _Anonymous_e__Struct Anonymous; } public _Anonymous_e__Union Anonymous; public uint dwPageSize; public unsafe void* lpMinimumApplicationAddress; public unsafe void* lpMaximumApplicationAddress; public nuint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public ushort wProcessorLevel; public ushort wProcessorRevision; [UnscopedRef] public ref uint dwOemId { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref Anonymous.dwOemId; } } [UnscopedRef] public ref ushort wProcessorArchitecture { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref Anonymous.Anonymous.wProcessorArchitecture; } } [UnscopedRef] public ref ushort wReserved { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref Anonymous.Anonymous.wReserved; } } } public readonly struct BOOL : IComparable, IComparable, IEquatable, IFormattable { public readonly int Value; public static BOOL FALSE => new BOOL(0); public static BOOL TRUE => new BOOL(1); public BOOL(int value) { Value = value; } public static bool operator ==(BOOL left, BOOL right) { return left.Value == right.Value; } public static bool operator !=(BOOL left, BOOL right) { return left.Value != right.Value; } public static bool operator <(BOOL left, BOOL right) { return left.Value < right.Value; } public static bool operator <=(BOOL left, BOOL right) { return left.Value <= right.Value; } public static bool operator >(BOOL left, BOOL right) { return left.Value > right.Value; } public static bool operator >=(BOOL left, BOOL right) { return left.Value >= right.Value; } public static implicit operator bool(BOOL value) { return value.Value != 0; } public static implicit operator BOOL(bool value) { return new BOOL(value ? 1 : 0); } public static bool operator false(BOOL value) { return value.Value == 0; } public static bool operator true(BOOL value) { return value.Value != 0; } public static implicit operator BOOL(byte value) { return new BOOL(value); } public static explicit operator byte(BOOL value) { return (byte)value.Value; } public static implicit operator BOOL(short value) { return new BOOL(value); } public static explicit operator short(BOOL value) { return (short)value.Value; } public static implicit operator BOOL(int value) { return new BOOL(value); } public static implicit operator int(BOOL value) { return value.Value; } public static explicit operator BOOL(long value) { return new BOOL((int)value); } public static implicit operator long(BOOL value) { return value.Value; } public static explicit operator BOOL(nint value) { return new BOOL((int)value); } public static implicit operator nint(BOOL value) { return value.Value; } public static implicit operator BOOL(sbyte value) { return new BOOL(value); } public static explicit operator sbyte(BOOL value) { return (sbyte)value.Value; } public static implicit operator BOOL(ushort value) { return new BOOL(value); } public static explicit operator ushort(BOOL value) { return (ushort)value.Value; } public static explicit operator BOOL(uint value) { return new BOOL((int)value); } public static explicit operator uint(BOOL value) { return (uint)value.Value; } public static explicit operator BOOL(ulong value) { return new BOOL((int)value); } public static explicit operator ulong(BOOL value) { return (ulong)value.Value; } public static explicit operator BOOL(nuint value) { return new BOOL((int)value); } public static explicit operator nuint(BOOL value) { return (nuint)value.Value; } public int CompareTo(object? obj) { if (obj is BOOL other) { return CompareTo(other); } if (obj != null) { throw new ArgumentException("obj is not an instance of BOOL."); } return 1; } public int CompareTo(BOOL other) { return Value.CompareTo(other.Value); } public override bool Equals(object? obj) { if (obj is BOOL other) { return Equals(other); } return false; } public bool Equals(BOOL other) { return Value.Equals(other.Value); } public override int GetHashCode() { return Value.GetHashCode(); } public override string ToString() { return Value.ToString((IFormatProvider?)null); } public string ToString(string? format, IFormatProvider? formatProvider) { return Value.ToString(format, formatProvider); } } public readonly struct HANDLE : IComparable, IComparable, IEquatable, IFormattable { public unsafe readonly void* Value; public unsafe static HANDLE INVALID_VALUE => new HANDLE((void*)(-1)); public static HANDLE NULL => new HANDLE(null); public unsafe HANDLE(void* value) { Value = value; } public unsafe static bool operator ==(HANDLE left, HANDLE right) { return left.Value == right.Value; } public unsafe static bool operator !=(HANDLE left, HANDLE right) { return left.Value != right.Value; } public unsafe static bool operator <(HANDLE left, HANDLE right) { return left.Value < right.Value; } public unsafe static bool operator <=(HANDLE left, HANDLE right) { return left.Value <= right.Value; } public unsafe static bool operator >(HANDLE left, HANDLE right) { return left.Value > right.Value; } public unsafe static bool operator >=(HANDLE left, HANDLE right) { return left.Value >= right.Value; } public unsafe static explicit operator HANDLE(void* value) { return new HANDLE(value); } public unsafe static implicit operator void*(HANDLE value) { return value.Value; } public unsafe static explicit operator HANDLE(byte value) { return new HANDLE((void*)value); } public unsafe static explicit operator byte(HANDLE value) { return (byte)value.Value; } public unsafe static explicit operator HANDLE(short value) { return new HANDLE((void*)value); } public unsafe static explicit operator short(HANDLE value) { return (short)value.Value; } public unsafe static explicit operator HANDLE(int value) { return new HANDLE((void*)value); } public unsafe static explicit operator int(HANDLE value) { return (int)value.Value; } public unsafe static explicit operator HANDLE(long value) { return new HANDLE((void*)value); } public unsafe static explicit operator long(HANDLE value) { return (long)value.Value; } public unsafe static explicit operator HANDLE(nint value) { return new HANDLE((void*)value); } public unsafe static implicit operator nint(HANDLE value) { return (nint)value.Value; } public unsafe static explicit operator HANDLE(sbyte value) { return new HANDLE((void*)value); } public unsafe static explicit operator sbyte(HANDLE value) { return (sbyte)value.Value; } public unsafe static explicit operator HANDLE(ushort value) { return new HANDLE((void*)value); } public unsafe static explicit operator ushort(HANDLE value) { return (ushort)value.Value; } public unsafe static explicit operator HANDLE(uint value) { return new HANDLE((void*)value); } public unsafe static explicit operator uint(HANDLE value) { return (uint)value.Value; } public unsafe static explicit operator HANDLE(ulong value) { return new HANDLE((void*)value); } public unsafe static explicit operator ulong(HANDLE value) { return (ulong)value.Value; } public unsafe static explicit operator HANDLE(nuint value) { return new HANDLE((void*)value); } public unsafe static implicit operator nuint(HANDLE value) { return (nuint)value.Value; } public int CompareTo(object? obj) { if (obj is HANDLE other) { return CompareTo(other); } if (obj != null) { throw new ArgumentException("obj is not an instance of HANDLE."); } return 1; } public unsafe int CompareTo(HANDLE other) { if (sizeof(nint) != 4) { return ((ulong)Value).CompareTo((ulong)other.Value); } return ((uint)Value).CompareTo((uint)other.Value); } public override bool Equals(object? obj) { if (obj is HANDLE other) { return Equals(other); } return false; } public unsafe bool Equals(HANDLE other) { nuint value = (nuint)Value; return ((UIntPtr)value).Equals((nuint)other.Value); } public unsafe override int GetHashCode() { nuint value = (nuint)Value; return ((UIntPtr)value).GetHashCode(); } public unsafe override string ToString() { if (sizeof(nuint) != 4) { return ((ulong)Value).ToString("X16", null); } return ((uint)Value).ToString("X8", null); } public unsafe string ToString(string? format, IFormatProvider? formatProvider) { if (sizeof(nint) != 4) { return ((ulong)Value).ToString(format, formatProvider); } return ((uint)Value).ToString(format, formatProvider); } } public readonly struct HMODULE : IComparable, IComparable, IEquatable, IFormattable { public unsafe readonly void* Value; public unsafe static HMODULE INVALID_VALUE => new HMODULE((void*)(-1)); public static HMODULE NULL => new HMODULE(null); public unsafe HMODULE(void* value) { Value = value; } public unsafe static bool operator ==(HMODULE left, HMODULE right) { return left.Value == right.Value; } public unsafe static bool operator !=(HMODULE left, HMODULE right) { return left.Value != right.Value; } public unsafe static bool operator <(HMODULE left, HMODULE right) { return left.Value < right.Value; } public unsafe static bool operator <=(HMODULE left, HMODULE right) { return left.Value <= right.Value; } public unsafe static bool operator >(HMODULE left, HMODULE right) { return left.Value > right.Value; } public unsafe static bool operator >=(HMODULE left, HMODULE right) { return left.Value >= right.Value; } public unsafe static explicit operator HMODULE(void* value) { return new HMODULE(value); } public unsafe static implicit operator void*(HMODULE value) { return value.Value; } public static explicit operator HMODULE(HANDLE value) { return new HMODULE(value); } public unsafe static implicit operator HANDLE(HMODULE value) { return new HANDLE(value.Value); } public unsafe static explicit operator HMODULE(byte value) { return new HMODULE((void*)value); } public unsafe static explicit operator byte(HMODULE value) { return (byte)value.Value; } public unsafe static explicit operator HMODULE(short value) { return new HMODULE((void*)value); } public unsafe static explicit operator short(HMODULE value) { return (short)value.Value; } public unsafe static explicit operator HMODULE(int value) { return new HMODULE((void*)value); } public unsafe static explicit operator int(HMODULE value) { return (int)value.Value; } public unsafe static explicit operator HMODULE(long value) { return new HMODULE((void*)value); } public unsafe static explicit operator long(HMODULE value) { return (long)value.Value; } public unsafe static explicit operator HMODULE(nint value) { return new HMODULE((void*)value); } public unsafe static implicit operator nint(HMODULE value) { return (nint)value.Value; } public unsafe static explicit operator HMODULE(sbyte value) { return new HMODULE((void*)value); } public unsafe static explicit operator sbyte(HMODULE value) { return (sbyte)value.Value; } public unsafe static explicit operator HMODULE(ushort value) { return new HMODULE((void*)value); } public unsafe static explicit operator ushort(HMODULE value) { return (ushort)value.Value; } public unsafe static explicit operator HMODULE(uint value) { return new HMODULE((void*)value); } public unsafe static explicit operator uint(HMODULE value) { return (uint)value.Value; } public unsafe static explicit operator HMODULE(ulong value) { return new HMODULE((void*)value); } public unsafe static explicit operator ulong(HMODULE value) { return (ulong)value.Value; } public unsafe static explicit operator HMODULE(nuint value) { return new HMODULE((void*)value); } public unsafe static implicit operator nuint(HMODULE value) { return (nuint)value.Value; } public int CompareTo(object? obj) { if (obj is HMODULE other) { return CompareTo(other); } if (obj != null) { throw new ArgumentException("obj is not an instance of HMODULE."); } return 1; } public unsafe int CompareTo(HMODULE other) { if (sizeof(nint) != 4) { return ((ulong)Value).CompareTo((ulong)other.Value); } return ((uint)Value).CompareTo((uint)other.Value); } public override bool Equals(object? obj) { if (obj is HMODULE other) { return Equals(other); } return false; } public unsafe bool Equals(HMODULE other) { nuint value = (nuint)Value; return ((UIntPtr)value).Equals((nuint)other.Value); } public unsafe override int GetHashCode() { nuint value = (nuint)Value; return ((UIntPtr)value).GetHashCode(); } public unsafe override string ToString() { if (sizeof(nuint) != 4) { return ((ulong)Value).ToString("X16", null); } return ((uint)Value).ToString("X8", null); } public unsafe string ToString(string? format, IFormatProvider? formatProvider) { if (sizeof(nint) != 4) { return ((ulong)Value).ToString(format, formatProvider); } return ((uint)Value).ToString(format, formatProvider); } } public const int PROCESSOR_ARCHITECTURE_INTEL = 0; public const int PROCESSOR_ARCHITECTURE_MIPS = 1; public const int PROCESSOR_ARCHITECTURE_ALPHA = 2; public const int PROCESSOR_ARCHITECTURE_PPC = 3; public const int PROCESSOR_ARCHITECTURE_SHX = 4; public const int PROCESSOR_ARCHITECTURE_ARM = 5; public const int PROCESSOR_ARCHITECTURE_IA64 = 6; public const int PROCESSOR_ARCHITECTURE_ALPHA64 = 7; public const int PROCESSOR_ARCHITECTURE_MSIL = 8; public const int PROCESSOR_ARCHITECTURE_AMD64 = 9; public const int PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 = 10; public const int PROCESSOR_ARCHITECTURE_NEUTRAL = 11; public const int PROCESSOR_ARCHITECTURE_ARM64 = 12; public const int PROCESSOR_ARCHITECTURE_ARM32_ON_WIN64 = 13; public const int PROCESSOR_ARCHITECTURE_IA32_ON_ARM64 = 14; public const int PROCESSOR_ARCHITECTURE_UNKNOWN = 65535; [DllImport("kernel32", ExactSpelling = true)] [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] public unsafe static extern void GetSystemInfo(SYSTEM_INFO* lpSystemInfo); [DllImport("kernel32", ExactSpelling = true)] [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] public unsafe static extern HMODULE GetModuleHandleW(ushort* lpModuleName); [DllImport("kernel32", ExactSpelling = true)] [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] public unsafe static extern nint GetProcAddress(HMODULE hModule, sbyte* lpProcName); [DllImport("kernel32", ExactSpelling = true)] [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] public unsafe static extern HMODULE LoadLibraryW(ushort* lpLibFileName); [DllImport("kernel32", ExactSpelling = true)] [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] public static extern BOOL FreeLibrary(HMODULE hLibModule); [DllImport("kernel32", ExactSpelling = true)] [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] public static extern uint GetLastError(); } } namespace MonoMod.Utils.Cil { public sealed class CecilILGenerator : ILGeneratorShim { private class LabelInfo { public bool Emitted; public Instruction Instruction = Instruction.Create(OpCodes.Nop); public readonly List Branches = new List(); } private class LabelledExceptionHandler { public Label TryStart = NullLabel; public Label TryEnd = NullLabel; public Label HandlerStart = NullLabel; public Label HandlerEnd = NullLabel; public Label FilterStart = NullLabel; public ExceptionHandlerType HandlerType; public TypeReference? ExceptionType; } private class ExceptionHandlerChain { private readonly CecilILGenerator IL; private readonly Label _Start; public readonly Label SkipAll; private Label _SkipHandler; private LabelledExceptionHandler? _Prev; private LabelledExceptionHandler? _Handler; public ExceptionHandlerChain(CecilILGenerator il) { IL = il; _Start = il.DefineLabel(); il.MarkLabel(_Start); SkipAll = il.DefineLabel(); } public LabelledExceptionHandler BeginHandler(ExceptionHandlerType type) { //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Invalid comparison between Unknown and I4 LabelledExceptionHandler labelledExceptionHandler = (_Prev = _Handler); if (labelledExceptionHandler != null) { EndHandler(labelledExceptionHandler); } IL.Emit(OpCodes.Leave, _SkipHandler = IL.DefineLabel()); Label label = IL.DefineLabel(); IL.MarkLabel(label); LabelledExceptionHandler labelledExceptionHandler2 = (_Handler = new LabelledExceptionHandler { TryStart = _Start, TryEnd = label, HandlerType = type, HandlerEnd = _SkipHandler }); if ((int)type == 1) { labelledExceptionHandler2.FilterStart = label; } else { labelledExceptionHandler2.HandlerStart = label; } return labelledExceptionHandler2; } public void EndHandler(LabelledExceptionHandler handler) { //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_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Invalid comparison between Unknown and I4 //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 Label skipHandler = _SkipHandler; ExceptionHandlerType handlerType = handler.HandlerType; if ((int)handlerType != 1) { if ((int)handlerType == 2) { ((ILGeneratorShim)IL).Emit(OpCodes.Endfinally); } else { IL.Emit(OpCodes.Leave, skipHandler); } } else { ((ILGeneratorShim)IL).Emit(OpCodes.Endfilter); } IL.MarkLabel(skipHandler); IL._ExceptionHandlersToMark.Add(handler); } public void End() { EndHandler(_Handler ?? throw new InvalidOperationException("Cannot end when there is no current handler!")); IL.MarkLabel(SkipAll); } } private static readonly Type t_LocalBuilder; private static readonly ConstructorInfo c_LocalBuilder; private static readonly FieldInfo? f_LocalBuilder_position; private static readonly FieldInfo? f_LocalBuilder_is_pinned; private static int c_LocalBuilder_params; private static readonly Dictionary _MCCOpCodes; private static Label NullLabel; private readonly Dictionary _LabelInfos = new Dictionary(); private readonly List _LabelsToMark = new List(); private readonly List _ExceptionHandlersToMark = new List(); private readonly Dictionary _Variables = new Dictionary(); private readonly Stack _ExceptionHandlers = new Stack(); private int labelCounter; private int _ILOffset; public ILProcessor IL { get; } public override int ILOffset => _ILOffset; static CecilILGenerator() { //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) t_LocalBuilder = Type.GetType("System.Reflection.Emit.RuntimeLocalBuilder") ?? typeof(LocalBuilder); c_LocalBuilder = (from c in t_LocalBuilder.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) orderby c.GetParameters().Length descending select c).First(); f_LocalBuilder_position = t_LocalBuilder.GetField("position", BindingFlags.Instance | BindingFlags.NonPublic); f_LocalBuilder_is_pinned = t_LocalBuilder.GetField("is_pinned", BindingFlags.Instance | BindingFlags.NonPublic); c_LocalBuilder_params = c_LocalBuilder.GetParameters().Length; _MCCOpCodes = new Dictionary(); FieldInfo[] fields = typeof(OpCodes).GetFields(BindingFlags.Static | BindingFlags.Public); for (int num = 0; num < fields.Length; num++) { OpCode value = (OpCode)fields[num].GetValue(null); _MCCOpCodes[((OpCode)(ref value)).Value] = value; } Label source = default(Label); Unsafe.As(ref source) = -1; NullLabel = source; } public CecilILGenerator(ILProcessor il) { IL = il; } private static OpCode _(OpCode opcode) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) return _MCCOpCodes[opcode.Value]; } private LabelInfo? _(Label handle) { if (!_LabelInfos.TryGetValue(handle, out LabelInfo value)) { return null; } return value; } private VariableDefinition _(LocalBuilder handle) { return _Variables[handle]; } private TypeReference _(Type info) { return ((MemberReference)IL.Body.Method).Module.ImportReference(info); } private FieldReference _(FieldInfo info) { return ((MemberReference)IL.Body.Method).Module.ImportReference(info); } private MethodReference _(MethodBase info) { return ((MemberReference)IL.Body.Method).Module.ImportReference(info); } private Instruction ProcessLabels(Instruction ins) { //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: 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_01d2: Expected O, but got Unknown if (_LabelsToMark.Count != 0) { foreach (LabelInfo item in _LabelsToMark) { foreach (Instruction branch in item.Branches) { object operand = branch.Operand; if (!(operand is Instruction)) { if (!(operand is Instruction[] array)) { continue; } for (int i = 0; i < array.Length; i++) { if (array[i] == item.Instruction) { array[i] = ins; break; } } } else { branch.Operand = ins; } } item.Emitted = true; item.Instruction = ins; } _LabelsToMark.Clear(); } if (_ExceptionHandlersToMark.Count != 0) { foreach (LabelledExceptionHandler item2 in _ExceptionHandlersToMark) { IL.Body.ExceptionHandlers.Add(new ExceptionHandler(item2.HandlerType) { TryStart = _(item2.TryStart)?.Instruction, TryEnd = _(item2.TryEnd)?.Instruction, HandlerStart = _(item2.HandlerStart)?.Instruction, HandlerEnd = _(item2.HandlerEnd)?.Instruction, FilterStart = _(item2.FilterStart)?.Instruction, CatchType = item2.ExceptionType }); } _ExceptionHandlersToMark.Clear(); } return ins; } public unsafe override Label DefineLabel() { Label label = default(Label); *(int*)(&label) = labelCounter++; _LabelInfos[label] = new LabelInfo(); return label; } public override void MarkLabel(Label loc) { if (_LabelInfos.TryGetValue(loc, out LabelInfo value) && !value.Emitted) { _LabelsToMark.Add(value); } } public override LocalBuilder DeclareLocal(Type localType) { return DeclareLocal(localType, pinned: false); } public override LocalBuilder DeclareLocal(Type localType, bool pinned) { //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Expected O, but got Unknown //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Expected O, but got Unknown int count = IL.Body.Variables.Count; object obj; if (c_LocalBuilder_params != 4) { if (c_LocalBuilder_params != 3) { if (c_LocalBuilder_params != 2) { if (c_LocalBuilder_params != 0) { throw new NotSupportedException(); } obj = c_LocalBuilder.Invoke(ArrayEx.Empty()); } else { obj = c_LocalBuilder.Invoke(new object[2] { localType, null }); } } else { obj = c_LocalBuilder.Invoke(new object[3] { count, localType, null }); } } else { obj = c_LocalBuilder.Invoke(new object[4] { count, localType, null, pinned }); } LocalBuilder localBuilder = (LocalBuilder)obj; f_LocalBuilder_position?.SetValue(localBuilder, (ushort)count); f_LocalBuilder_is_pinned?.SetValue(localBuilder, pinned); TypeReference val = _(localType); if (pinned) { val = (TypeReference)new PinnedType(val); } VariableDefinition val2 = new VariableDefinition(val); IL.Body.Variables.Add(val2); _Variables[localBuilder] = val2; return localBuilder; } private void Emit(Instruction ins) { ins.Offset = _ILOffset; _ILOffset += ins.GetSize(); IL.Append(ProcessLabels(ins)); } public override void Emit(OpCode opcode) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) Emit(IL.Create(_(opcode))); } public override void Emit(OpCode opcode, byte arg) { //IL_0018: 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) if (opcode.OperandType == OperandType.ShortInlineVar || opcode.OperandType == OperandType.InlineVar) { _EmitInlineVar(_(opcode), arg); } else { Emit(IL.Create(_(opcode), arg)); } } public override void Emit(OpCode opcode, sbyte arg) { //IL_0018: 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) if (opcode.OperandType == OperandType.ShortInlineVar || opcode.OperandType == OperandType.InlineVar) { _EmitInlineVar(_(opcode), arg); } else { Emit(IL.Create(_(opcode), arg)); } } public override void Emit(OpCode opcode, short arg) { //IL_0018: 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) if (opcode.OperandType == OperandType.ShortInlineVar || opcode.OperandType == OperandType.InlineVar) { _EmitInlineVar(_(opcode), arg); } else { Emit(IL.Create(_(opcode), (int)arg)); } } public override void Emit(OpCode opcode, int arg) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) if (opcode.OperandType == OperandType.ShortInlineVar || opcode.OperandType == OperandType.InlineVar) { _EmitInlineVar(_(opcode), arg); return; } string? name = opcode.Name; if (name != null && name.EndsWith(".s", StringComparison.Ordinal)) { Emit(IL.Create(_(opcode), (sbyte)arg)); } else { Emit(IL.Create(_(opcode), arg)); } } public override void Emit(OpCode opcode, long arg) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) Emit(IL.Create(_(opcode), arg)); } public override void Emit(OpCode opcode, float arg) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) Emit(IL.Create(_(opcode), arg)); } public override void Emit(OpCode opcode, double arg) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) Emit(IL.Create(_(opcode), arg)); } public override void Emit(OpCode opcode, string str) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) Emit(IL.Create(_(opcode), str)); } public override void Emit(OpCode opcode, Type cls) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) Emit(IL.Create(_(opcode), _(cls))); } public override void Emit(OpCode opcode, FieldInfo field) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) Emit(IL.Create(_(opcode), _(field))); } public override void Emit(OpCode opcode, ConstructorInfo con) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) Emit(IL.Create(_(opcode), _(con))); } public override void Emit(OpCode opcode, MethodInfo meth) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) Emit(IL.Create(_(opcode), _(meth))); } public override void Emit(OpCode opcode, Label label) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) LabelInfo? labelInfo = _(label); Instruction val = IL.Create(_(opcode), _(label).Instruction); labelInfo.Branches.Add(val); Emit(ProcessLabels(val)); } public override void Emit(OpCode opcode, Label[] labels) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) LabelInfo[] array = (from x in labels.Distinct().Select(_) where x != null select x).ToArray(); Instruction val = IL.Create(_(opcode), array.Select((LabelInfo labelInfo) => labelInfo.Instruction).ToArray()); LabelInfo[] array2 = array; for (int num = 0; num < array2.Length; num++) { array2[num].Branches.Add(val); } Emit(ProcessLabels(val)); } public override void Emit(OpCode opcode, LocalBuilder local) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) Emit(IL.Create(_(opcode), _(local))); } public override void Emit(OpCode opcode, SignatureHelper signature) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) Emit(IL.Create(_(opcode), ((MemberReference)IL.Body.Method).Module.ImportCallSite(signature))); } public void Emit(OpCode opcode, ICallSiteGenerator signature) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) Emit(IL.Create(_(opcode), ((MemberReference)IL.Body.Method).Module.ImportCallSite(signature))); } private void _EmitInlineVar(OpCode opcode, int index) { //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_000b: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected I4, but got Unknown //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) OperandType operandType = ((OpCode)(ref opcode)).OperandType; switch (operandType - 13) { case 1: case 6: Emit(IL.Create(opcode, ((MethodReference)IL.Body.Method).Parameters[index])); return; case 0: case 5: Emit(IL.Create(opcode, IL.Body.Variables[index])); return; } throw new NotSupportedException($"Unsupported SRE InlineVar -> Cecil {((OpCode)(ref opcode)).OperandType} for {opcode} {index}"); } public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[]? optionalParameterTypes) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) Emit(IL.Create(_(opcode), _(methodInfo))); } public override void EmitCalli(OpCode opcode, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, Type[]? optionalParameterTypes) { throw new NotSupportedException(); } public override void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type? returnType, Type[]? parameterTypes) { throw new NotSupportedException(); } public override void EmitWriteLine(FieldInfo fld) { //IL_002e: 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_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) if (fld.IsStatic) { Emit(IL.Create(OpCodes.Ldsfld, _(fld))); } else { Emit(IL.Create(OpCodes.Ldarg_0)); Emit(IL.Create(OpCodes.Ldfld, _(fld))); } Emit(IL.Create(OpCodes.Call, _(typeof(Console).GetMethod("WriteLine", new Type[1] { fld.FieldType })))); } public override void EmitWriteLine(LocalBuilder localBuilder) { //IL_0007: 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) Emit(IL.Create(OpCodes.Ldloc, _(localBuilder))); Emit(IL.Create(OpCodes.Call, _(typeof(Console).GetMethod("WriteLine", new Type[1] { localBuilder.LocalType })))); } public override void EmitWriteLine(string value) { //IL_0007: 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) Emit(IL.Create(OpCodes.Ldstr, value)); Emit(IL.Create(OpCodes.Call, _(typeof(Console).GetMethod("WriteLine", new Type[1] { typeof(string) })))); } public override void ThrowException(Type excType) { //IL_0007: 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) Emit(IL.Create(OpCodes.Newobj, _(excType.GetConstructor(Type.EmptyTypes) ?? throw new InvalidOperationException("No default constructor")))); Emit(IL.Create(OpCodes.Throw)); } public override Label BeginExceptionBlock() { ExceptionHandlerChain exceptionHandlerChain = new ExceptionHandlerChain(this); _ExceptionHandlers.Push(exceptionHandlerChain); return exceptionHandlerChain.SkipAll; } public override void BeginCatchBlock(Type exceptionType) { _ExceptionHandlers.Peek().BeginHandler((ExceptionHandlerType)0).ExceptionType = (((object)exceptionType == null) ? null : _(exceptionType)); } public override void BeginExceptFilterBlock() { _ExceptionHandlers.Peek().BeginHandler((ExceptionHandlerType)1); } public override void BeginFaultBlock() { _ExceptionHandlers.Peek().BeginHandler((ExceptionHandlerType)4); } public override void BeginFinallyBlock() { _ExceptionHandlers.Peek().BeginHandler((ExceptionHandlerType)2); } public override void EndExceptionBlock() { _ExceptionHandlers.Pop().End(); } public override void BeginScope() { } public override void EndScope() { } public override void UsingNamespace(string usingNamespace) { } } public abstract class ILGeneratorShim { internal static class ILGeneratorBuilder { public const string Namespace = "MonoMod.Utils.Cil"; public const string Name = "ILGeneratorProxy"; public const string FullName = "MonoMod.Utils.Cil.ILGeneratorProxy"; public const string TargetName = "Target"; private static Type? ProxyType; public static Type GenerateProxy() { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: 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_004a: Expected O, but got Unknown //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Expected O, but got Unknown //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Expected O, but got Unknown //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Expected O, but got Unknown //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Expected O, but got Unknown //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Expected O, but got Unknown //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Expected O, but got Unknown //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Expected O, but got Unknown //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Expected O, but got Unknown //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_01b9: 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_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Unknown result type (might be due to invalid IL or missing references) //IL_025e: Expected O, but got Unknown //IL_0288: Unknown result type (might be due to invalid IL or missing references) //IL_0292: Expected O, but got Unknown //IL_02be: Unknown result type (might be due to invalid IL or missing references) //IL_02ca: 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_02e2: Unknown result type (might be due to invalid IL or missing references) //IL_02f1: Unknown result type (might be due to invalid IL or missing references) //IL_0328: Unknown result type (might be due to invalid IL or missing references) //IL_0321: Unknown result type (might be due to invalid IL or missing references) //IL_034c: Unknown result type (might be due to invalid IL or missing references) if (ProxyType != null) { return ProxyType; } Type typeFromHandle = typeof(ILGenerator); Type typeFromHandle2 = typeof(ILGeneratorShim); ModuleDefinition val = ModuleDefinition.CreateModule("MonoMod.Utils.Cil.ILGeneratorProxy", new ModuleParameters { Kind = (ModuleKind)0, ReflectionImporterProvider = MMReflectionImporter.Provider }); Assembly assembly; try { CustomAttribute val2 = new CustomAttribute(val.ImportReference((MethodBase)DynamicMethodDefinition.c_IgnoresAccessChecksToAttribute)); val2.ConstructorArguments.Add(new CustomAttributeArgument(val.TypeSystem.String, (object)typeof(ILGeneratorShim).Assembly.GetName().Name)); val.Assembly.CustomAttributes.Add(val2); TypeDefinition val3 = new TypeDefinition("MonoMod.Utils.Cil", "ILGeneratorProxy", (TypeAttributes)1) { BaseType = val.ImportReference(typeFromHandle) }; val.Types.Add(val3); TypeReference val4 = val.ImportReference(typeFromHandle2); GenericParameter val5 = new GenericParameter("TTarget", (IGenericParameterProvider)(object)val3); val5.Constraints.Add(new GenericParameterConstraint(val4)); ((TypeReference)val3).GenericParameters.Add(val5); FieldDefinition val6 = new FieldDefinition("Target", (FieldAttributes)6, (TypeReference)(object)val5); val3.Fields.Add(val6); GenericInstanceType val7 = new GenericInstanceType((TypeReference)(object)val3); val7.GenericArguments.Add((TypeReference)(object)val5); FieldReference val8 = new FieldReference("Target", (TypeReference)(object)val5, (TypeReference)(object)val7); MethodDefinition val9 = new MethodDefinition(".ctor", (MethodAttributes)6278, val.TypeSystem.Void); ((MethodReference)val9).Parameters.Add(new ParameterDefinition((TypeReference)(object)val5)); val3.Methods.Add(val9); ILProcessor iLProcessor = val9.Body.GetILProcessor(); iLProcessor.Emit(OpCodes.Ldarg_0); iLProcessor.Emit(OpCodes.Ldarg_1); iLProcessor.Emit(OpCodes.Stfld, val8); iLProcessor.Emit(OpCodes.Ret); MethodInfo[] methods = typeFromHandle.GetMethods(BindingFlags.Instance | BindingFlags.Public); foreach (MethodInfo methodInfo in methods) { MethodInfo method = typeFromHandle2.GetMethod(methodInfo.Name, (from p in methodInfo.GetParameters() select p.ParameterType).ToArray()); if (method == null) { continue; } MethodDefinition val10 = new MethodDefinition(methodInfo.Name, (MethodAttributes)198, val.ImportReference(methodInfo.ReturnType)) { HasThis = true }; ParameterInfo[] parameters = methodInfo.GetParameters(); foreach (ParameterInfo parameterInfo in parameters) { ((MethodReference)val10).Parameters.Add(new ParameterDefinition(val.ImportReference(parameterInfo.ParameterType))); } val3.Methods.Add(val10); iLProcessor = val10.Body.GetILProcessor(); iLProcessor.Emit(OpCodes.Ldarg_0); iLProcessor.Emit(OpCodes.Ldfld, val8); Enumerator enumerator = ((MethodReference)val10).Parameters.GetEnumerator(); try { while (enumerator.MoveNext()) { ParameterDefinition current = enumerator.Current; iLProcessor.Emit(OpCodes.Ldarg, current); } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } iLProcessor.Emit(method.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, ((MemberReference)iLProcessor.Body.Method).Module.ImportReference((MethodBase)method)); iLProcessor.Emit(OpCodes.Ret); } assembly = ReflectionHelper.Load(val); assembly.SetMonoCorlibInternal(value: true); } finally { ((IDisposable)val)?.Dispose(); } ResolveEventHandler value = (object? asmSender, ResolveEventArgs asmArgs) => (new AssemblyName(asmArgs.Name).Name == typeof(ILGeneratorBuilder).Assembly.GetName().Name) ? typeof(ILGeneratorBuilder).Assembly : null; AppDomain.CurrentDomain.AssemblyResolve += value; try { ProxyType = assembly.GetType("MonoMod.Utils.Cil.ILGeneratorProxy"); } finally { AppDomain.CurrentDomain.AssemblyResolve -= value; } if (ProxyType == null) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("Couldn't find ILGeneratorShim proxy \"").Append("MonoMod.Utils.Cil.ILGeneratorProxy").Append("\" in autogenerated \"") .Append(assembly.FullName) .AppendLine("\""); Type[] types; Exception[] array; try { types = assembly.GetTypes(); array = null; } catch (ReflectionTypeLoadException ex) { types = ex.Types; array = new Exception[ex.LoaderExceptions.Length + 1]; array[0] = ex; for (int num2 = 0; num2 < ex.LoaderExceptions.Length; num2++) { array[num2 + 1] = ex.LoaderExceptions[num2]; } } stringBuilder.AppendLine("Listing all types in autogenerated assembly:"); Type[] array2 = types; for (int i = 0; i < array2.Length; i++) { stringBuilder.AppendLine(array2[i]?.FullName ?? ""); } if (array != null && array.Length != 0) { stringBuilder.AppendLine("Listing all exceptions:"); for (int num3 = 0; num3 < array.Length; num3++) { stringBuilder.Append('#').Append(num3).Append(": ") .AppendLine(array[num3]?.ToString() ?? "NULL"); } } throw new InvalidOperationException(stringBuilder.ToString()); } return ProxyType; } } public abstract int ILOffset { get; } public static Type GenericProxyType => ILGeneratorBuilder.GenerateProxy(); public abstract void BeginCatchBlock(Type exceptionType); public abstract void BeginExceptFilterBlock(); public abstract Label BeginExceptionBlock(); public abstract void BeginFaultBlock(); public abstract void BeginFinallyBlock(); public abstract void BeginScope(); public abstract LocalBuilder DeclareLocal(Type localType); public abstract LocalBuilder DeclareLocal(Type localType, bool pinned); public abstract Label DefineLabel(); public abstract void Emit(OpCode opcode); public abstract void Emit(OpCode opcode, byte arg); public abstract void Emit(OpCode opcode, double arg); public abstract void Emit(OpCode opcode, short arg); public abstract void Emit(OpCode opcode, int arg); public abstract void Emit(OpCode opcode, long arg); public abstract void Emit(OpCode opcode, ConstructorInfo con); public abstract void Emit(OpCode opcode, Label label); public abstract void Emit(OpCode opcode, Label[] labels); public abstract void Emit(OpCode opcode, LocalBuilder local); public abstract void Emit(OpCode opcode, SignatureHelper signature); public abstract void Emit(OpCode opcode, FieldInfo field); public abstract void Emit(OpCode opcode, MethodInfo meth); public abstract void Emit(OpCode opcode, sbyte arg); public abstract void Emit(OpCode opcode, float arg); public abstract void Emit(OpCode opcode, string str); public abstract void Emit(OpCode opcode, Type cls); public abstract void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[]? optionalParameterTypes); public abstract void EmitCalli(OpCode opcode, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, Type[]? optionalParameterTypes); public abstract void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type? returnType, Type[]? parameterTypes); public abstract void EmitWriteLine(LocalBuilder localBuilder); public abstract void EmitWriteLine(FieldInfo fld); public abstract void EmitWriteLine(string value); public abstract void EndExceptionBlock(); public abstract void EndScope(); public abstract void MarkLabel(Label loc); public abstract void ThrowException(Type excType); public abstract void UsingNamespace(string usingNamespace); public ILGenerator GetProxy() { return (ILGenerator)ILGeneratorBuilder.GenerateProxy().MakeGenericType(GetType()).GetConstructors()[0].Invoke(new object[1] { this }); } public static Type GetProxyType() where TShim : ILGeneratorShim { return GetProxyType(typeof(TShim)); } public static Type GetProxyType(Type tShim) { return GenericProxyType.MakeGenericType(tShim); } } public static class ILGeneratorShimExt { private static readonly Dictionary _Emitters; private static readonly Dictionary _EmittersShim; static ILGeneratorShimExt() { _Emitters = new Dictionary(); _EmittersShim = new Dictionary(); MethodInfo[] methods = typeof(ILGenerator).GetMethods(); foreach (MethodInfo methodInfo in methods) { if (!(methodInfo.Name != "Emit")) { ParameterInfo[] parameters = methodInfo.GetParameters(); if (parameters.Length == 2 && !(parameters[0].ParameterType != typeof(OpCode))) { _Emitters[parameters[1].ParameterType] = methodInfo; } } } methods = typeof(ILGeneratorShim).GetMethods(); foreach (MethodInfo methodInfo2 in methods) { if (!(methodInfo2.Name != "Emit")) { ParameterInfo[] parameters2 = methodInfo2.GetParameters(); if (parameters2.Length == 2 && !(parameters2[0].ParameterType != typeof(OpCode))) { _EmittersShim[parameters2[1].ParameterType] = methodInfo2; } } } } public static ILGeneratorShim GetProxiedShim(this ILGenerator il) { return (ILGeneratorShim)(Helpers.ThrowIfNull(il, "il").GetType().GetField("Target", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(il)); } public static T GetProxiedShim(this ILGenerator il) where T : ILGeneratorShim { return (T)il.GetProxiedShim(); } public static object? DynEmit(this ILGenerator il, OpCode opcode, object operand) { return il.DynEmit(new object[2] { opcode, operand }); } public static object? DynEmit(this ILGenerator il, object[] emitArgs) { Helpers.ThrowIfArgumentNull(emitArgs, "emitArgs"); Type operandType = emitArgs[1].GetType(); object obj = ((object)il.GetProxiedShim()) ?? ((object)il); Dictionary dictionary = ((obj is ILGeneratorShim) ? _EmittersShim : _Emitters); if (!dictionary.TryGetValue(operandType, out var value)) { value = dictionary.FirstOrDefault((KeyValuePair kvp) => kvp.Key.IsAssignableFrom(operandType)).Value; } if (value == null) { throw new InvalidOperationException("Unexpected unemittable operand type " + operandType.FullName); } return value.Invoke(obj, emitArgs); } } } namespace System.Runtime.CompilerServices { [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal static class IsExternalInit { } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class IgnoresAccessChecksToAttribute : Attribute { public string AssemblyName { get; } public IgnoresAccessChecksToAttribute(string assemblyName) { AssemblyName = assemblyName; } } }